blob: e37402045c386de54aebe200b2c9d88fa55bb84f [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)
Neslisah Torosdagli054b5e32020-03-26 12:24:31 -04001186 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.
alelenv999d4fd2020-06-01 23:24:41 -07001295 if (type.getBasicType() == glslang::EbtSampler ||
1296 type.getBasicType() == glslang::EbtAccStruct)
John Kessenich6c292d32016-02-15 20:58:50 -07001297 return type.getQualifier().isUniformOrBuffer();
1298
1299 // None of the above.
1300 return false;
1301}
1302
John Kesseniche0b6cad2015-12-24 10:30:13 -07001303void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1304{
1305 if (child.layoutMatrix == glslang::ElmNone)
1306 child.layoutMatrix = parent.layoutMatrix;
1307
1308 if (parent.invariant)
1309 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001310 if (parent.flat)
1311 child.flat = true;
1312 if (parent.centroid)
1313 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001314#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001315 if (parent.nopersp)
1316 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001317 if (parent.explicitInterp)
1318 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001319 if (parent.perPrimitiveNV)
1320 child.perPrimitiveNV = true;
1321 if (parent.perViewNV)
1322 child.perViewNV = true;
1323 if (parent.perTaskNV)
1324 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001325 if (parent.patch)
1326 child.patch = true;
1327 if (parent.sample)
1328 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001329 if (parent.coherent)
1330 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001331 if (parent.devicecoherent)
1332 child.devicecoherent = true;
1333 if (parent.queuefamilycoherent)
1334 child.queuefamilycoherent = true;
1335 if (parent.workgroupcoherent)
1336 child.workgroupcoherent = true;
1337 if (parent.subgroupcoherent)
1338 child.subgroupcoherent = true;
Daniel Kochdb32b242020-03-17 20:42:47 -04001339 if (parent.shadercallcoherent)
1340 child.shadercallcoherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001341 if (parent.nonprivate)
1342 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001343 if (parent.volatil)
1344 child.volatil = true;
1345 if (parent.restrict)
1346 child.restrict = true;
1347 if (parent.readonly)
1348 child.readonly = true;
1349 if (parent.writeonly)
1350 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001351#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001352}
1353
John Kessenichf2b7f332016-09-01 17:05:23 -06001354bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001355{
John Kessenich7b9fa252016-01-21 18:56:57 -07001356 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001357 // - struct members might inherit from a struct declaration
1358 // (note that non-block structs don't explicitly inherit,
1359 // only implicitly, meaning no decoration involved)
1360 // - affect decorations on the struct members
1361 // (note smooth does not, and expecting something like volatile
1362 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001363 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001364 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001365}
1366
John Kessenich140f3df2015-06-26 16:58:36 -06001367//
1368// Implement the TGlslangToSpvTraverser class.
1369//
1370
John Kessenich8985fc92020-03-03 10:25:07 -07001371TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion,
1372 const glslang::TIntermediate* glslangIntermediate,
1373 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options) :
1374 TIntermTraverser(true, false, true),
1375 options(options),
1376 shaderEntry(nullptr), currentFunction(nullptr),
1377 sequenceDepth(0), logger(buildLogger),
1378 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
1379 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
1380 glslangIntermediate(glslangIntermediate),
Jeff Bolz04d73732019-05-31 13:06:01 -05001381 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp()),
1382 nonSemanticDebugPrintf(0)
John Kessenich140f3df2015-06-26 16:58:36 -06001383{
1384 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1385
1386 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001387 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1388 glslangIntermediate->getVersion());
1389
John Kessenich121853f2017-05-31 17:11:16 -06001390 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001391 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001392 builder.setSourceFile(glslangIntermediate->getSourceFile());
1393
1394 // Set the source shader's text. If for SPV version 1.0, include
1395 // a preamble in comments stating the OpModuleProcessed instructions.
1396 // Otherwise, emit those as actual instructions.
1397 std::string text;
1398 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1399 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001400 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001401 text.append("// OpModuleProcessed ");
1402 text.append(processes[p]);
1403 text.append("\n");
1404 } else
1405 builder.addModuleProcessed(processes[p]);
1406 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001407 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001408 text.append("#line 1\n");
1409 text.append(glslangIntermediate->getSourceText());
1410 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001411 // Pass name and text for all included files
1412 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1413 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1414 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001415 }
John Kessenich140f3df2015-06-26 16:58:36 -06001416 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001417
1418 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1419 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1420
1421 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1422 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
John Kessenich1ff0c182019-10-10 12:01:13 -06001423 builder.addIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001424 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
John Kessenich8985fc92020-03-03 10:25:07 -07001425 }
Jeff Bolz36831c92018-09-05 10:11:41 -05001426 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001427 memoryModel = spv::MemoryModelVulkanKHR;
1428 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001429 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001430 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001431 builder.setMemoryModel(addressingModel, memoryModel);
1432
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001433 if (glslangIntermediate->usingVariablePointers()) {
1434 builder.addCapability(spv::CapabilityVariablePointers);
1435 }
1436
John Kessenicheee9d532016-09-19 18:09:30 -06001437 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1438 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001439
1440 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001441 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1442 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
Pankaj Mistry2a8ead22020-04-26 17:52:31 -07001443 builder.addSourceExtension(it->first.c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001444
1445 // Add the top-level modes for this shader.
1446
John Kessenich92187592016-02-01 13:45:25 -07001447 if (glslangIntermediate->getXfbMode()) {
1448 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001449 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001450 }
John Kessenich140f3df2015-06-26 16:58:36 -06001451
alelenv59216d52020-05-21 04:38:41 -07001452 if (glslangIntermediate->getLayoutPrimitiveCulling()) {
alelenv75de1962020-04-08 21:09:20 -07001453 builder.addCapability(spv::CapabilityRayTraversalPrimitiveCullingProvisionalKHR);
1454 }
1455
John Kessenich140f3df2015-06-26 16:58:36 -06001456 unsigned int mode;
1457 switch (glslangIntermediate->getStage()) {
1458 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001459 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001460 break;
1461
John Kessenicha28f7a72019-08-06 07:00:58 -06001462 case EShLangFragment:
1463 builder.addCapability(spv::CapabilityShader);
1464 if (glslangIntermediate->getPixelCenterInteger())
1465 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1466
1467 if (glslangIntermediate->getOriginUpperLeft())
1468 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1469 else
1470 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1471
1472 if (glslangIntermediate->getEarlyFragmentTests())
1473 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1474
1475 if (glslangIntermediate->getPostDepthCoverage()) {
1476 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1477 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1478 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1479 }
1480
John Kessenichb9197c82019-08-11 07:41:45 -06001481 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1482 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1483
1484#ifndef GLSLANG_WEB
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001485
John Kessenicha28f7a72019-08-06 07:00:58 -06001486 switch(glslangIntermediate->getDepth()) {
1487 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1488 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1489 default: mode = spv::ExecutionModeMax; break;
1490 }
1491 if (mode != spv::ExecutionModeMax)
1492 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001493 switch (glslangIntermediate->getInterlockOrdering()) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001494 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT;
1495 break;
1496 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT;
1497 break;
1498 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT;
1499 break;
1500 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT;
1501 break;
1502 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT;
1503 break;
1504 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT;
1505 break;
1506 default: mode = spv::ExecutionModeMax;
1507 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001508 }
1509 if (mode != spv::ExecutionModeMax) {
1510 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1511 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1512 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1513 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1514 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1515 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1516 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1517 } else {
1518 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1519 }
1520 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1521 }
John Kessenichb9197c82019-08-11 07:41:45 -06001522#endif
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001523 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001524
John Kessenicha28f7a72019-08-06 07:00:58 -06001525 case EShLangCompute:
1526 builder.addCapability(spv::CapabilityShader);
1527 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1528 glslangIntermediate->getLocalSize(1),
1529 glslangIntermediate->getLocalSize(2));
1530 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1531 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1532 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1533 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1534 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1535 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1536 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1537 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1538 }
1539 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001540#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001541 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001542 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001543 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001544
steve-lunarge7412492017-03-23 11:56:07 -06001545 glslang::TLayoutGeometry primitive;
1546
1547 if (glslangIntermediate->getStage() == EShLangTessControl) {
John Kessenich8985fc92020-03-03 10:25:07 -07001548 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1549 glslangIntermediate->getVertices());
steve-lunarge7412492017-03-23 11:56:07 -06001550 primitive = glslangIntermediate->getOutputPrimitive();
1551 } else {
1552 primitive = glslangIntermediate->getInputPrimitive();
1553 }
1554
1555 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001556 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1557 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1558 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001559 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001560 }
John Kessenich4016e382016-07-15 11:53:56 -06001561 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001562 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1563
John Kesseniche6903322015-10-13 16:29:02 -06001564 switch (glslangIntermediate->getVertexSpacing()) {
1565 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1566 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1567 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001568 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001569 }
John Kessenich4016e382016-07-15 11:53:56 -06001570 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001571 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1572
1573 switch (glslangIntermediate->getVertexOrder()) {
1574 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1575 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001576 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001577 }
John Kessenich4016e382016-07-15 11:53:56 -06001578 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001579 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1580
1581 if (glslangIntermediate->getPointMode())
1582 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001583 break;
1584
1585 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001586 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001587 switch (glslangIntermediate->getInputPrimitive()) {
1588 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1589 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1590 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001591 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001592 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001593 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001594 }
John Kessenich4016e382016-07-15 11:53:56 -06001595 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001596 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001597
John Kessenich140f3df2015-06-26 16:58:36 -06001598 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1599
1600 switch (glslangIntermediate->getOutputPrimitive()) {
1601 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1602 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1603 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001604 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001605 }
John Kessenich4016e382016-07-15 11:53:56 -06001606 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001607 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1608 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1609 break;
1610
Daniel Kochdb32b242020-03-17 20:42:47 -04001611 case EShLangRayGen:
1612 case EShLangIntersect:
1613 case EShLangAnyHit:
1614 case EShLangClosestHit:
1615 case EShLangMiss:
1616 case EShLangCallable:
1617 {
1618 auto& extensions = glslangIntermediate->getRequestedExtensions();
1619 if (extensions.find("GL_NV_ray_tracing") == extensions.end()) {
1620 builder.addCapability(spv::CapabilityRayTracingProvisionalKHR);
1621 builder.addExtension("SPV_KHR_ray_tracing");
1622 }
1623 else {
1624 builder.addCapability(spv::CapabilityRayTracingNV);
1625 builder.addExtension("SPV_NV_ray_tracing");
1626 }
Chao Chenb50c02e2018-09-19 11:42:24 -07001627 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04001628 }
Chao Chen3c366992018-09-19 11:41:59 -07001629 case EShLangTaskNV:
1630 case EShLangMeshNV:
1631 builder.addCapability(spv::CapabilityMeshShadingNV);
1632 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1633 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1634 glslangIntermediate->getLocalSize(1),
1635 glslangIntermediate->getLocalSize(2));
1636 if (glslangIntermediate->getStage() == EShLangMeshNV) {
John Kessenich8985fc92020-03-03 10:25:07 -07001637 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1638 glslangIntermediate->getVertices());
1639 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV,
1640 glslangIntermediate->getPrimitives());
Chao Chen3c366992018-09-19 11:41:59 -07001641
1642 switch (glslangIntermediate->getOutputPrimitive()) {
1643 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1644 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1645 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1646 default: mode = spv::ExecutionModeMax; break;
1647 }
1648 if (mode != spv::ExecutionModeMax)
1649 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1650 }
1651 break;
1652#endif
1653
John Kessenich140f3df2015-06-26 16:58:36 -06001654 default:
1655 break;
1656 }
John Kessenich140f3df2015-06-26 16:58:36 -06001657}
1658
John Kessenichfca82622016-11-26 13:23:20 -07001659// Finish creating SPV, after the traversal is complete.
1660void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001661{
John Kessenichf04c51b2018-08-03 15:56:12 -06001662 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001663 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001664 builder.setBuildPoint(shaderEntry->getLastBlock());
1665 builder.leaveFunction();
1666 }
1667
John Kessenich7ba63412015-12-20 17:37:07 -07001668 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001669 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1670 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001671
David Neto8c3d5b42019-10-21 14:50:31 -04001672 // Add capabilities, extensions, remove unneeded decorations, etc.,
John Kessenichf04c51b2018-08-03 15:56:12 -06001673 // based on the resulting SPIR-V.
David Neto8c3d5b42019-10-21 14:50:31 -04001674 // Note: WebGPU code generation must have the opportunity to aggressively
1675 // prune unreachable merge blocks and continue targets.
John Kessenichf04c51b2018-08-03 15:56:12 -06001676 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001677}
1678
John Kessenichfca82622016-11-26 13:23:20 -07001679// Write the SPV into 'out'.
1680void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001681{
John Kessenichfca82622016-11-26 13:23:20 -07001682 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001683}
1684
1685//
1686// Implement the traversal functions.
1687//
1688// Return true from interior nodes to have the external traversal
1689// continue on to children. Return false if children were
1690// already processed.
1691//
1692
1693//
qining25262b32016-05-06 17:25:16 -04001694// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001695// - uniform/input reads
1696// - output writes
1697// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1698// - something simple that degenerates into the last bullet
1699//
1700void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1701{
qining75d1d802016-04-06 14:42:01 -04001702 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
Roy05a5b532020-01-03 16:21:34 +08001703 if (symbol->getType().isStruct())
1704 glslangTypeToIdMap[symbol->getType().getStruct()] = symbol->getId();
1705
qining75d1d802016-04-06 14:42:01 -04001706 if (symbol->getType().getQualifier().isSpecConstant())
1707 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1708
John Kessenich140f3df2015-06-26 16:58:36 -06001709 // getSymbolId() will set up all the IO decorations on the first call.
1710 // Formal function parameters were mapped during makeFunctions().
1711 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001712
John Kessenich7ba63412015-12-20 17:37:07 -07001713 if (builder.isPointer(id)) {
John Kessenich9c14f772019-06-17 08:38:35 -06001714 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
John Kessenich7c7731e2019-01-04 16:47:06 +07001715 // Consider adding to the OpEntryPoint interface list.
1716 // Only looking at structures if they have at least one member.
1717 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1718 spv::StorageClass sc = builder.getStorageClass(id);
1719 // Before SPIR-V 1.4, we only want to include Input and Output.
1720 // Starting with SPIR-V 1.4, we want all globals.
1721 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1722 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001723 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001724 }
John Kessenich5f77d862017-09-19 11:09:59 -06001725 }
John Kessenich9c14f772019-06-17 08:38:35 -06001726
Daniel Kochdb32b242020-03-17 20:42:47 -04001727 // If the SPIR-V type is required to be different than the AST type
1728 // (for ex SubgroupMasks or 3x4 ObjectToWorld/WorldToObject matrices),
John Kessenich9c14f772019-06-17 08:38:35 -06001729 // translate now from the SPIR-V type to the AST type, for the consuming
1730 // operation.
1731 // Note this turns it from an l-value to an r-value.
1732 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1733 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1734 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001735 }
1736
1737 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001738 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001739 // Prepare to generate code for the access
1740
1741 // L-value chains will be computed left to right. We're on the symbol now,
1742 // which is the left-most part of the access chain, so now is "clear" time,
1743 // followed by setting the base.
1744 builder.clearAccessChain();
1745
1746 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001747 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001748 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001749 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001750 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001751 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001752 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001753 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001754 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1755 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001756 builder.setAccessChainRValue(id);
1757 else
1758 builder.setAccessChainLValue(id);
1759 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001760
John Kessenichb9197c82019-08-11 07:41:45 -06001761#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001762 // Process linkage-only nodes for any special additional interface work.
1763 if (linkageOnly) {
1764 if (glslangIntermediate->getHlslFunctionality1()) {
1765 // Map implicit counter buffers to their originating buffers, which should have been
1766 // seen by now, given earlier pruning of unused counters, and preservation of order
1767 // of declaration.
1768 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1769 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1770 // Save possible originating buffers for counter buffers, keyed by
1771 // making the potential counter-buffer name.
1772 std::string keyName = symbol->getName().c_str();
1773 keyName = glslangIntermediate->addCounterBufferName(keyName);
1774 counterOriginator[keyName] = symbol;
1775 } else {
1776 // Handle a counter buffer, by finding the saved originating buffer.
1777 std::string keyName = symbol->getName().c_str();
1778 auto it = counterOriginator.find(keyName);
1779 if (it != counterOriginator.end()) {
1780 id = getSymbolId(it->second);
1781 if (id != spv::NoResult) {
1782 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001783 if (counterId != spv::NoResult) {
1784 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001785 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001786 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001787 }
1788 }
1789 }
1790 }
1791 }
1792 }
John Kessenich155d3512019-08-08 23:29:20 -06001793#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001794}
1795
1796bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1797{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001798 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Roy05a5b532020-01-03 16:21:34 +08001799 if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
1800 glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
1801 }
1802 if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
1803 glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
1804 }
John Kesseniche485c7a2017-05-31 18:50:53 -06001805
qining40887662016-04-03 22:20:42 -04001806 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1807 if (node->getType().getQualifier().isSpecConstant())
1808 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1809
John Kessenich140f3df2015-06-26 16:58:36 -06001810 // First, handle special cases
1811 switch (node->getOp()) {
1812 case glslang::EOpAssign:
1813 case glslang::EOpAddAssign:
1814 case glslang::EOpSubAssign:
1815 case glslang::EOpMulAssign:
1816 case glslang::EOpVectorTimesMatrixAssign:
1817 case glslang::EOpVectorTimesScalarAssign:
1818 case glslang::EOpMatrixTimesScalarAssign:
1819 case glslang::EOpMatrixTimesMatrixAssign:
1820 case glslang::EOpDivAssign:
1821 case glslang::EOpModAssign:
1822 case glslang::EOpAndAssign:
1823 case glslang::EOpInclusiveOrAssign:
1824 case glslang::EOpExclusiveOrAssign:
1825 case glslang::EOpLeftShiftAssign:
1826 case glslang::EOpRightShiftAssign:
1827 // A bin-op assign "a += b" means the same thing as "a = a + b"
1828 // where a is evaluated before b. For a simple assignment, GLSL
1829 // says to evaluate the left before the right. So, always, left
1830 // node then right node.
1831 {
1832 // get the left l-value, save it away
1833 builder.clearAccessChain();
1834 node->getLeft()->traverse(this);
1835 spv::Builder::AccessChain lValue = builder.getAccessChain();
1836
1837 // evaluate the right
1838 builder.clearAccessChain();
1839 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001840 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001841
1842 if (node->getOp() != glslang::EOpAssign) {
1843 // the left is also an r-value
1844 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001845 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001846
1847 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001848 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001849 TranslateNoContractionDecoration(node->getType().getQualifier()),
1850 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001851 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001852 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1853 node->getType().getBasicType());
1854
1855 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001856 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001857 }
1858
1859 // store the result
1860 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001861 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001862
1863 // assignments are expressions having an rValue after they are evaluated...
1864 builder.clearAccessChain();
1865 builder.setAccessChainRValue(rValue);
1866 }
1867 return false;
1868 case glslang::EOpIndexDirect:
1869 case glslang::EOpIndexDirectStruct:
1870 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001871 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001872 // Get the left part of the access chain.
1873 node->getLeft()->traverse(this);
1874
1875 // Add the next element in the chain
1876
David Netoa901ffe2016-06-08 14:11:40 +01001877 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001878 if (! node->getLeft()->getType().isArray() &&
1879 node->getLeft()->getType().isVector() &&
1880 node->getOp() == glslang::EOpIndexDirect) {
1881 // This is essentially a hard-coded vector swizzle of size 1,
1882 // so short circuit the access-chain stuff with a swizzle.
1883 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001884 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001885 int dummySize;
1886 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1887 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001888 glslangIntermediate->getBaseAlignmentScalar(
1889 node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001890 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001891
1892 // Load through a block reference is performed with a dot operator that
1893 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1894 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001895 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001896 !node->getLeft()->getType().isArray() &&
1897 node->getOp() == glslang::EOpIndexDirectStruct)
1898 {
1899 spv::Id left = accessChainLoad(node->getLeft()->getType());
1900 builder.clearAccessChain();
1901 builder.setAccessChainLValue(left);
1902 }
1903
David Netoa901ffe2016-06-08 14:11:40 +01001904 int spvIndex = glslangIndex;
1905 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1906 node->getOp() == glslang::EOpIndexDirectStruct)
1907 {
1908 // This may be, e.g., an anonymous block-member selection, which generally need
1909 // index remapping due to hidden members in anonymous blocks.
Roy05a5b532020-01-03 16:21:34 +08001910 int glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
1911 if (memberRemapper.find(glslangId) != memberRemapper.end()) {
1912 std::vector<int>& remapper = memberRemapper[glslangId];
1913 assert(remapper.size() > 0);
1914 spvIndex = remapper[glslangIndex];
1915 }
David Netoa901ffe2016-06-08 14:11:40 +01001916 }
John Kessenichebb50532016-05-16 19:22:05 -06001917
David Netoa901ffe2016-06-08 14:11:40 +01001918 // normal case for indexing array or structure or block
John Kessenich8985fc92020-03-03 10:25:07 -07001919 builder.accessChainPush(builder.makeIntConstant(spvIndex),
1920 TranslateCoherent(node->getLeft()->getType()),
1921 node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001922
1923 // Add capabilities here for accessing PointSize and clip/cull distance.
1924 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001925 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001926 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001927 }
1928 }
1929 return false;
1930 case glslang::EOpIndexIndirect:
1931 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001932 // Array, matrix, or vector indirection with variable index.
1933 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001934 // matrices are arrays of vectors, so will also work for a matrix.
1935 // Will use the access chain's 'component' for variable index into a vector.
1936
1937 // This adapter is building access chains left to right.
1938 // Set up the access chain to the left.
1939 node->getLeft()->traverse(this);
1940
1941 // save it so that computing the right side doesn't trash it
1942 spv::Builder::AccessChain partial = builder.getAccessChain();
1943
1944 // compute the next index in the chain
1945 builder.clearAccessChain();
1946 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001947 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001948
John Kessenich5611c6d2018-04-05 11:25:02 -06001949 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1950
John Kessenich140f3df2015-06-26 16:58:36 -06001951 // restore the saved access chain
1952 builder.setAccessChain(partial);
1953
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001954 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1955 int dummySize;
1956 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1957 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001958 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1959 dummySize));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001960 } else
John Kessenich8985fc92020-03-03 10:25:07 -07001961 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()),
1962 node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001963 }
1964 return false;
1965 case glslang::EOpVectorSwizzle:
1966 {
1967 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001968 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001969 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001970 int dummySize;
1971 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1972 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001973 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1974 dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001975 }
1976 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001977 case glslang::EOpMatrixSwizzle:
1978 logger->missingFunctionality("matrix swizzle");
1979 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001980 case glslang::EOpLogicalOr:
1981 case glslang::EOpLogicalAnd:
1982 {
1983
1984 // These may require short circuiting, but can sometimes be done as straight
1985 // binary operations. The right operand must be short circuited if it has
1986 // side effects, and should probably be if it is complex.
1987 if (isTrivial(node->getRight()->getAsTyped()))
1988 break; // handle below as a normal binary operation
1989 // otherwise, we need to do dynamic short circuiting on the right operand
John Kessenich8985fc92020-03-03 10:25:07 -07001990 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(),
1991 *node->getRight()->getAsTyped());
John Kessenich7c1aa102015-10-15 13:29:11 -06001992 builder.clearAccessChain();
1993 builder.setAccessChainRValue(result);
1994 }
1995 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001996 default:
1997 break;
1998 }
1999
2000 // Assume generic binary op...
2001
John Kessenich32cfd492016-02-02 12:37:46 -07002002 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06002003 builder.clearAccessChain();
2004 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002005 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002006
John Kessenich32cfd492016-02-02 12:37:46 -07002007 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06002008 builder.clearAccessChain();
2009 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002010 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002011
John Kessenich32cfd492016-02-02 12:37:46 -07002012 // get result
John Kessenichead86222018-03-28 18:01:20 -06002013 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002014 TranslateNoContractionDecoration(node->getType().getQualifier()),
2015 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002016 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07002017 convertGlslangToSpvType(node->getType()), left, right,
2018 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002019
John Kessenich50e57562015-12-21 21:21:11 -07002020 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06002021 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002022 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07002023 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06002024 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06002025 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06002026 return false;
2027 }
John Kessenich140f3df2015-06-26 16:58:36 -06002028}
2029
John Kessenich9c14f772019-06-17 08:38:35 -06002030// Figure out what, if any, type changes are needed when accessing a specific built-in.
2031// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
2032// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
Daniel Kochdb32b242020-03-17 20:42:47 -04002033std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(glslang::TBuiltInVariable glslangBuiltIn,
John Kessenich9c14f772019-06-17 08:38:35 -06002034 const glslang::TType& glslangType)
2035{
Daniel Kochdb32b242020-03-17 20:42:47 -04002036 switch(glslangBuiltIn)
John Kessenich9c14f772019-06-17 08:38:35 -06002037 {
Daniel Kochdb32b242020-03-17 20:42:47 -04002038 case glslang::EbvSubGroupEqMask:
2039 case glslang::EbvSubGroupGeMask:
2040 case glslang::EbvSubGroupGtMask:
2041 case glslang::EbvSubGroupLeMask:
2042 case glslang::EbvSubGroupLtMask: {
John Kessenich9c14f772019-06-17 08:38:35 -06002043 // these require changing a 64-bit scaler -> a vector of 32-bit components
2044 if (glslangType.isVector())
2045 break;
2046 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
2047 builder.makeUintType(64));
2048 return ret;
2049 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002050 // There are no SPIR-V builtins defined for these and map onto original non-transposed
2051 // builtins. During visitBinary we insert a transpose
2052 case glslang::EbvWorldToObject3x4:
2053 case glslang::EbvObjectToWorld3x4: {
2054 std::pair<spv::Id, spv::Id> ret(builder.makeMatrixType(builder.makeFloatType(32), 4, 3),
2055 builder.makeMatrixType(builder.makeFloatType(32), 3, 4)
2056 );
2057 return ret;
2058 }
John Kessenich9c14f772019-06-17 08:38:35 -06002059 default:
2060 break;
2061 }
2062
2063 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2064 return ret;
2065}
2066
2067// For an object previously identified (see getForcedType() and forceType)
2068// as needing type translations, do the translation needed for a load, turning
2069// an L-value into in R-value.
2070spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2071{
2072 const auto forceIt = forceType.find(object);
2073 if (forceIt == forceType.end())
2074 return object;
2075
2076 spv::Id desiredTypeId = forceIt->second;
2077 spv::Id objectTypeId = builder.getTypeId(object);
2078 assert(builder.isPointerType(objectTypeId));
2079 objectTypeId = builder.getContainedTypeId(objectTypeId);
2080 if (builder.isVectorType(objectTypeId) &&
2081 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2082 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2083 // handle 32-bit v.xy* -> 64-bit
2084 builder.clearAccessChain();
2085 builder.setAccessChainLValue(object);
2086 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2087 std::vector<spv::Id> components;
2088 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2089 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2090
2091 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2092 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2093 builder.createCompositeConstruct(vecType, components));
2094 } else {
2095 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2096 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002097 } else if (builder.isMatrixType(objectTypeId)) {
2098 // There are no SPIR-V builtins defined for 3x4 variants of ObjectToWorld/WorldToObject
2099 // and we insert a transpose after loading the original non-transposed builtins
2100 builder.clearAccessChain();
2101 builder.setAccessChainLValue(object);
2102 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2103 return builder.createUnaryOp(spv::OpTranspose, desiredTypeId, object);
2104
2105 } else {
John Kessenich9c14f772019-06-17 08:38:35 -06002106 logger->missingFunctionality("forcing non 32-bit vector type");
2107 }
2108
2109 return object;
2110}
2111
John Kessenich140f3df2015-06-26 16:58:36 -06002112bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2113{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002114 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002115
qining40887662016-04-03 22:20:42 -04002116 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2117 if (node->getType().getQualifier().isSpecConstant())
2118 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2119
John Kessenichfc51d282015-08-19 13:34:18 -06002120 spv::Id result = spv::NoResult;
2121
2122 // try texturing first
2123 result = createImageTextureFunctionCall(node);
2124 if (result != spv::NoResult) {
2125 builder.clearAccessChain();
2126 builder.setAccessChainRValue(result);
2127
2128 return false; // done with this node
2129 }
2130
2131 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002132
2133 if (node->getOp() == glslang::EOpArrayLength) {
2134 // Quite special; won't want to evaluate the operand.
2135
John Kessenich5611c6d2018-04-05 11:25:02 -06002136 // Currently, the front-end does not allow .length() on an array until it is sized,
2137 // except for the last block membeor of an SSBO.
2138 // TODO: If this changes, link-time sized arrays might show up here, and need their
2139 // size extracted.
2140
John Kessenichc9a80832015-09-12 12:17:44 -06002141 // Normal .length() would have been constant folded by the front-end.
2142 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002143 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002144
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002145 spv::Id length;
2146 if (node->getOperand()->getType().isCoopMat()) {
2147 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2148
2149 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2150 assert(builder.isCooperativeMatrixType(typeId));
2151
2152 length = builder.createCooperativeMatrixLength(typeId);
2153 } else {
2154 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2155 block->traverse(this);
John Kessenich8985fc92020-03-03 10:25:07 -07002156 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()
2157 ->getConstArray()[0].getUConst();
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002158 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2159 }
John Kessenichc9a80832015-09-12 12:17:44 -06002160
John Kessenich8c869672018-11-28 07:01:37 -07002161 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2162 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2163 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002164 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2165 if (builder.isInSpecConstCodeGenMode()) {
2166 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2167 } else {
2168 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2169 }
2170 }
John Kessenich8c869672018-11-28 07:01:37 -07002171
John Kessenichc9a80832015-09-12 12:17:44 -06002172 builder.clearAccessChain();
2173 builder.setAccessChainRValue(length);
2174
2175 return false;
2176 }
2177
John Kessenichfc51d282015-08-19 13:34:18 -06002178 // Start by evaluating the operand
2179
John Kessenich8c8505c2016-07-26 12:50:38 -06002180 // Does it need a swizzle inversion? If so, evaluation is inverted;
2181 // operate first on the swizzle base, then apply the swizzle.
2182 spv::Id invertedType = spv::NoType;
John Kessenich8985fc92020-03-03 10:25:07 -07002183 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2184 invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenich8c8505c2016-07-26 12:50:38 -06002185 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2186 invertedType = getInvertedSwizzleType(*node->getOperand());
2187
John Kessenich140f3df2015-06-26 16:58:36 -06002188 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002189 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002190 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002191 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002192 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002193 operandNode = node->getOperand();
2194
2195 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002196
Rex Xufc618912015-09-09 16:42:49 +08002197 spv::Id operand = spv::NoResult;
2198
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002199 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2200
John Kessenichfb4f2332019-08-09 03:49:15 -06002201#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002202 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2203 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002204 node->getOp() == glslang::EOpAtomicCounter ||
Neslisah Torosdagli7d37a682020-03-26 10:52:33 -04002205 node->getOp() == glslang::EOpInterpolateAtCentroid ||
2206 node->getOp() == glslang::EOpRayQueryProceed ||
2207 node->getOp() == glslang::EOpRayQueryGetRayTMin ||
2208 node->getOp() == glslang::EOpRayQueryGetRayFlags ||
2209 node->getOp() == glslang::EOpRayQueryGetWorldRayOrigin ||
2210 node->getOp() == glslang::EOpRayQueryGetWorldRayDirection ||
2211 node->getOp() == glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque ||
2212 node->getOp() == glslang::EOpRayQueryTerminate ||
2213 node->getOp() == glslang::EOpRayQueryConfirmIntersection) {
Rex Xufc618912015-09-09 16:42:49 +08002214 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002215 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2216 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2217 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002218#endif
2219 {
John Kessenich32cfd492016-02-02 12:37:46 -07002220 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002221 }
John Kessenich140f3df2015-06-26 16:58:36 -06002222
John Kessenichead86222018-03-28 18:01:20 -06002223 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002224 TranslateNoContractionDecoration(node->getType().getQualifier()),
2225 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002226
2227 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002228 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002229 result = createConversion(node->getOp(), decorations, resultType(), operand,
2230 node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002231
2232 // if not, then possibly an operation
2233 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002234 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand,
2235 node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002236
2237 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002238 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002239 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002240 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002241 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002242
John Kessenich140f3df2015-06-26 16:58:36 -06002243 builder.clearAccessChain();
2244 builder.setAccessChainRValue(result);
2245
2246 return false; // done with this node
2247 }
2248
2249 // it must be a special case, check...
2250 switch (node->getOp()) {
2251 case glslang::EOpPostIncrement:
2252 case glslang::EOpPostDecrement:
2253 case glslang::EOpPreIncrement:
2254 case glslang::EOpPreDecrement:
2255 {
2256 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002257 spv::Id one = 0;
2258 if (node->getBasicType() == glslang::EbtFloat)
2259 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002260#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002261 else if (node->getBasicType() == glslang::EbtDouble)
2262 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002263 else if (node->getBasicType() == glslang::EbtFloat16)
2264 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002265 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2266 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002267 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2268 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002269 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2270 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002271#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002272 else
2273 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002274 glslang::TOperator op;
2275 if (node->getOp() == glslang::EOpPreIncrement ||
2276 node->getOp() == glslang::EOpPostIncrement)
2277 op = glslang::EOpAdd;
2278 else
2279 op = glslang::EOpSub;
2280
John Kessenichead86222018-03-28 18:01:20 -06002281 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002282 convertGlslangToSpvType(node->getType()), operand, one,
2283 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002284 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002285
2286 // The result of operation is always stored, but conditionally the
2287 // consumed result. The consumed result is always an r-value.
2288 builder.accessChainStore(result);
2289 builder.clearAccessChain();
2290 if (node->getOp() == glslang::EOpPreIncrement ||
2291 node->getOp() == glslang::EOpPreDecrement)
2292 builder.setAccessChainRValue(result);
2293 else
2294 builder.setAccessChainRValue(operand);
2295 }
2296
2297 return false;
2298
John Kessenich155d3512019-08-08 23:29:20 -06002299#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002300 case glslang::EOpEmitStreamVertex:
2301 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2302 return false;
2303 case glslang::EOpEndStreamPrimitive:
2304 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2305 return false;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002306 case glslang::EOpRayQueryTerminate:
2307 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operand);
2308 return false;
2309 case glslang::EOpRayQueryConfirmIntersection:
2310 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operand);
2311 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002312#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002313
2314 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002315 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002316 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002317 }
John Kessenich140f3df2015-06-26 16:58:36 -06002318}
2319
Jeff Bolz53134492019-06-25 13:31:10 -05002320// Construct a composite object, recursively copying members if their types don't match
2321spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2322{
2323 for (int c = 0; c < (int)constituents.size(); ++c) {
2324 spv::Id& constituent = constituents[c];
2325 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2326 spv::Id rType = builder.getTypeId(constituent);
2327 if (lType != rType) {
2328 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2329 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2330 } else if (builder.isStructType(rType)) {
2331 std::vector<spv::Id> rTypeConstituents;
2332 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2333 for (int i = 0; i < numrTypeConstituents; ++i) {
John Kessenich8985fc92020-03-03 10:25:07 -07002334 rTypeConstituents.push_back(builder.createCompositeExtract(constituent,
2335 builder.getContainedTypeId(rType, i), i));
Jeff Bolz53134492019-06-25 13:31:10 -05002336 }
2337 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2338 } else {
2339 assert(builder.isArrayType(rType));
2340 std::vector<spv::Id> rTypeConstituents;
2341 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2342
2343 spv::Id elementRType = builder.getContainedTypeId(rType);
2344 for (int i = 0; i < numrTypeConstituents; ++i) {
2345 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2346 }
2347 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2348 }
2349 }
2350 }
2351 return builder.createCompositeConstruct(resultTypeId, constituents);
2352}
2353
John Kessenich140f3df2015-06-26 16:58:36 -06002354bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2355{
qining27e04a02016-04-14 16:40:20 -04002356 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2357 if (node->getType().getQualifier().isSpecConstant())
2358 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2359
John Kessenichfc51d282015-08-19 13:34:18 -06002360 spv::Id result = spv::NoResult;
Cody Northrop4d2298b2020-04-13 21:59:49 -06002361 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2362 std::vector<spv::Builder::AccessChain> complexLvalues; // for holding swizzling l-values too complex for
2363 // SPIR-V, for an out parameter
2364 std::vector<spv::Id> temporaryLvalues; // temporaries to pass, as proxies for complexLValues
John Kessenichbbbd9a22020-03-03 07:21:37 -07002365
John Kessenich8985fc92020-03-03 10:25:07 -07002366 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2367 invertedType :
2368 convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002369
2370 // try texturing
2371 result = createImageTextureFunctionCall(node);
2372 if (result != spv::NoResult) {
2373 builder.clearAccessChain();
2374 builder.setAccessChainRValue(result);
2375
2376 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002377 }
2378#ifndef GLSLANG_WEB
2379 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002380 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002381 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002382 // "imageStore" is a special case, which has no result
2383 return false;
2384 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002385#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002386
John Kessenich140f3df2015-06-26 16:58:36 -06002387 glslang::TOperator binOp = glslang::EOpNull;
2388 bool reduceComparison = true;
2389 bool isMatrix = false;
2390 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002391 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002392
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002393 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2394
John Kessenich140f3df2015-06-26 16:58:36 -06002395 assert(node->getOp());
2396
John Kessenichf6640762016-08-01 19:44:00 -06002397 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002398
2399 switch (node->getOp()) {
2400 case glslang::EOpSequence:
2401 {
2402 if (preVisit)
2403 ++sequenceDepth;
2404 else
2405 --sequenceDepth;
2406
2407 if (sequenceDepth == 1) {
2408 // If this is the parent node of all the functions, we want to see them
2409 // early, so all call points have actual SPIR-V functions to reference.
2410 // In all cases, still let the traverser visit the children for us.
2411 makeFunctions(node->getAsAggregate()->getSequence());
2412
John Kessenich6fccb3c2016-09-19 16:01:41 -06002413 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002414 // anything else gets there, so visit out of order, doing them all now.
2415 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2416
John Kessenich6a60c2f2016-12-08 21:01:59 -07002417 // 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 -06002418 // so do them manually.
2419 visitFunctions(node->getAsAggregate()->getSequence());
2420
2421 return false;
2422 }
2423
2424 return true;
2425 }
2426 case glslang::EOpLinkerObjects:
2427 {
2428 if (visit == glslang::EvPreVisit)
2429 linkageOnly = true;
2430 else
2431 linkageOnly = false;
2432
2433 return true;
2434 }
2435 case glslang::EOpComma:
2436 {
2437 // processing from left to right naturally leaves the right-most
2438 // lying around in the access chain
2439 glslang::TIntermSequence& glslangOperands = node->getSequence();
2440 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2441 glslangOperands[i]->traverse(this);
2442
2443 return false;
2444 }
2445 case glslang::EOpFunction:
2446 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002447 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002448 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002449 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002450 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002451 } else {
2452 handleFunctionEntry(node);
2453 }
2454 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002455 if (inEntryPoint)
2456 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002457 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002458 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002459 }
2460
2461 return true;
2462 case glslang::EOpParameters:
2463 // Parameters will have been consumed by EOpFunction processing, but not
2464 // the body, so we still visited the function node's children, making this
2465 // child redundant.
2466 return false;
2467 case glslang::EOpFunctionCall:
2468 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002469 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002470 if (node->isUserDefined())
2471 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07002472 if (result) {
2473 builder.clearAccessChain();
2474 builder.setAccessChainRValue(result);
2475 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002476 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002477
2478 return false;
2479 }
2480 case glslang::EOpConstructMat2x2:
2481 case glslang::EOpConstructMat2x3:
2482 case glslang::EOpConstructMat2x4:
2483 case glslang::EOpConstructMat3x2:
2484 case glslang::EOpConstructMat3x3:
2485 case glslang::EOpConstructMat3x4:
2486 case glslang::EOpConstructMat4x2:
2487 case glslang::EOpConstructMat4x3:
2488 case glslang::EOpConstructMat4x4:
2489 case glslang::EOpConstructDMat2x2:
2490 case glslang::EOpConstructDMat2x3:
2491 case glslang::EOpConstructDMat2x4:
2492 case glslang::EOpConstructDMat3x2:
2493 case glslang::EOpConstructDMat3x3:
2494 case glslang::EOpConstructDMat3x4:
2495 case glslang::EOpConstructDMat4x2:
2496 case glslang::EOpConstructDMat4x3:
2497 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002498 case glslang::EOpConstructIMat2x2:
2499 case glslang::EOpConstructIMat2x3:
2500 case glslang::EOpConstructIMat2x4:
2501 case glslang::EOpConstructIMat3x2:
2502 case glslang::EOpConstructIMat3x3:
2503 case glslang::EOpConstructIMat3x4:
2504 case glslang::EOpConstructIMat4x2:
2505 case glslang::EOpConstructIMat4x3:
2506 case glslang::EOpConstructIMat4x4:
2507 case glslang::EOpConstructUMat2x2:
2508 case glslang::EOpConstructUMat2x3:
2509 case glslang::EOpConstructUMat2x4:
2510 case glslang::EOpConstructUMat3x2:
2511 case glslang::EOpConstructUMat3x3:
2512 case glslang::EOpConstructUMat3x4:
2513 case glslang::EOpConstructUMat4x2:
2514 case glslang::EOpConstructUMat4x3:
2515 case glslang::EOpConstructUMat4x4:
2516 case glslang::EOpConstructBMat2x2:
2517 case glslang::EOpConstructBMat2x3:
2518 case glslang::EOpConstructBMat2x4:
2519 case glslang::EOpConstructBMat3x2:
2520 case glslang::EOpConstructBMat3x3:
2521 case glslang::EOpConstructBMat3x4:
2522 case glslang::EOpConstructBMat4x2:
2523 case glslang::EOpConstructBMat4x3:
2524 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002525 case glslang::EOpConstructF16Mat2x2:
2526 case glslang::EOpConstructF16Mat2x3:
2527 case glslang::EOpConstructF16Mat2x4:
2528 case glslang::EOpConstructF16Mat3x2:
2529 case glslang::EOpConstructF16Mat3x3:
2530 case glslang::EOpConstructF16Mat3x4:
2531 case glslang::EOpConstructF16Mat4x2:
2532 case glslang::EOpConstructF16Mat4x3:
2533 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002534 isMatrix = true;
2535 // fall through
2536 case glslang::EOpConstructFloat:
2537 case glslang::EOpConstructVec2:
2538 case glslang::EOpConstructVec3:
2539 case glslang::EOpConstructVec4:
2540 case glslang::EOpConstructDouble:
2541 case glslang::EOpConstructDVec2:
2542 case glslang::EOpConstructDVec3:
2543 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002544 case glslang::EOpConstructFloat16:
2545 case glslang::EOpConstructF16Vec2:
2546 case glslang::EOpConstructF16Vec3:
2547 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002548 case glslang::EOpConstructBool:
2549 case glslang::EOpConstructBVec2:
2550 case glslang::EOpConstructBVec3:
2551 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002552 case glslang::EOpConstructInt8:
2553 case glslang::EOpConstructI8Vec2:
2554 case glslang::EOpConstructI8Vec3:
2555 case glslang::EOpConstructI8Vec4:
2556 case glslang::EOpConstructUint8:
2557 case glslang::EOpConstructU8Vec2:
2558 case glslang::EOpConstructU8Vec3:
2559 case glslang::EOpConstructU8Vec4:
2560 case glslang::EOpConstructInt16:
2561 case glslang::EOpConstructI16Vec2:
2562 case glslang::EOpConstructI16Vec3:
2563 case glslang::EOpConstructI16Vec4:
2564 case glslang::EOpConstructUint16:
2565 case glslang::EOpConstructU16Vec2:
2566 case glslang::EOpConstructU16Vec3:
2567 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002568 case glslang::EOpConstructInt:
2569 case glslang::EOpConstructIVec2:
2570 case glslang::EOpConstructIVec3:
2571 case glslang::EOpConstructIVec4:
2572 case glslang::EOpConstructUint:
2573 case glslang::EOpConstructUVec2:
2574 case glslang::EOpConstructUVec3:
2575 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002576 case glslang::EOpConstructInt64:
2577 case glslang::EOpConstructI64Vec2:
2578 case glslang::EOpConstructI64Vec3:
2579 case glslang::EOpConstructI64Vec4:
2580 case glslang::EOpConstructUint64:
2581 case glslang::EOpConstructU64Vec2:
2582 case glslang::EOpConstructU64Vec3:
2583 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002584 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002585 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002586 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002587 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002588 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002589 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002590 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002591 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002592 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002593 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002594 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002595 else if (node->getOp() == glslang::EOpConstructStruct ||
2596 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2597 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002598 std::vector<spv::Id> constituents;
2599 for (int c = 0; c < (int)arguments.size(); ++c)
2600 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002601 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002602 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002603 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002604 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002605 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002606
2607 builder.clearAccessChain();
2608 builder.setAccessChainRValue(constructed);
2609
2610 return false;
2611 }
2612
2613 // These six are component-wise compares with component-wise results.
2614 // Forward on to createBinaryOperation(), requesting a vector result.
2615 case glslang::EOpLessThan:
2616 case glslang::EOpGreaterThan:
2617 case glslang::EOpLessThanEqual:
2618 case glslang::EOpGreaterThanEqual:
2619 case glslang::EOpVectorEqual:
2620 case glslang::EOpVectorNotEqual:
2621 {
2622 // Map the operation to a binary
2623 binOp = node->getOp();
2624 reduceComparison = false;
2625 switch (node->getOp()) {
2626 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2627 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2628 default: binOp = node->getOp(); break;
2629 }
2630
2631 break;
2632 }
2633 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002634 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002635 binOp = glslang::EOpMul;
2636 break;
2637 case glslang::EOpOuterProduct:
2638 // two vectors multiplied to make a matrix
2639 binOp = glslang::EOpOuterProduct;
2640 break;
2641 case glslang::EOpDot:
2642 {
qining25262b32016-05-06 17:25:16 -04002643 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002644 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002645 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002646 binOp = glslang::EOpMul;
2647 break;
2648 }
2649 case glslang::EOpMod:
2650 // when an aggregate, this is the floating-point mod built-in function,
2651 // which can be emitted by the one in createBinaryOperation()
2652 binOp = glslang::EOpMod;
2653 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002654
John Kessenich140f3df2015-06-26 16:58:36 -06002655 case glslang::EOpEmitVertex:
2656 case glslang::EOpEndPrimitive:
2657 case glslang::EOpBarrier:
2658 case glslang::EOpMemoryBarrier:
2659 case glslang::EOpMemoryBarrierAtomicCounter:
2660 case glslang::EOpMemoryBarrierBuffer:
2661 case glslang::EOpMemoryBarrierImage:
2662 case glslang::EOpMemoryBarrierShared:
2663 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002664 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002665 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002666 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002667 case glslang::EOpWorkgroupMemoryBarrier:
2668 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002669 case glslang::EOpSubgroupBarrier:
2670 case glslang::EOpSubgroupMemoryBarrier:
2671 case glslang::EOpSubgroupMemoryBarrierBuffer:
2672 case glslang::EOpSubgroupMemoryBarrierImage:
2673 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002674 noReturnValue = true;
2675 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2676 break;
2677
John Kessenich426394d2015-07-23 10:22:48 -06002678 case glslang::EOpAtomicAdd:
2679 case glslang::EOpAtomicMin:
2680 case glslang::EOpAtomicMax:
2681 case glslang::EOpAtomicAnd:
2682 case glslang::EOpAtomicOr:
2683 case glslang::EOpAtomicXor:
2684 case glslang::EOpAtomicExchange:
2685 case glslang::EOpAtomicCompSwap:
2686 atomic = true;
2687 break;
2688
John Kesseniche5eee8f2019-10-18 01:03:11 -06002689#ifndef GLSLANG_WEB
2690 case glslang::EOpAtomicStore:
2691 noReturnValue = true;
2692 // fallthrough
2693 case glslang::EOpAtomicLoad:
2694 atomic = true;
2695 break;
2696
John Kessenich0d0c6d32017-07-23 16:08:26 -06002697 case glslang::EOpAtomicCounterAdd:
2698 case glslang::EOpAtomicCounterSubtract:
2699 case glslang::EOpAtomicCounterMin:
2700 case glslang::EOpAtomicCounterMax:
2701 case glslang::EOpAtomicCounterAnd:
2702 case glslang::EOpAtomicCounterOr:
2703 case glslang::EOpAtomicCounterXor:
2704 case glslang::EOpAtomicCounterExchange:
2705 case glslang::EOpAtomicCounterCompSwap:
2706 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2707 builder.addCapability(spv::CapabilityAtomicStorageOps);
2708 atomic = true;
2709 break;
2710
Ian Romanickb3bd4022019-01-21 08:57:25 -08002711 case glslang::EOpAbsDifference:
2712 case glslang::EOpAddSaturate:
2713 case glslang::EOpSubSaturate:
2714 case glslang::EOpAverage:
2715 case glslang::EOpAverageRounded:
2716 case glslang::EOpMul32x16:
2717 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2718 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2719 binOp = node->getOp();
2720 break;
2721
Daniel Kochdb32b242020-03-17 20:42:47 -04002722 case glslang::EOpIgnoreIntersection:
2723 case glslang::EOpTerminateRay:
2724 case glslang::EOpTrace:
2725 case glslang::EOpExecuteCallable:
Chao Chen3c366992018-09-19 11:41:59 -07002726 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2727 noReturnValue = true;
2728 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04002729 case glslang::EOpRayQueryInitialize:
2730 case glslang::EOpRayQueryTerminate:
2731 case glslang::EOpRayQueryGenerateIntersection:
2732 case glslang::EOpRayQueryConfirmIntersection:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002733 builder.addExtension("SPV_KHR_ray_query");
2734 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
Torosdagli06c2eee2020-03-19 11:09:57 -04002735 noReturnValue = true;
2736 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002737 case glslang::EOpRayQueryProceed:
2738 case glslang::EOpRayQueryGetIntersectionType:
2739 case glslang::EOpRayQueryGetRayTMin:
2740 case glslang::EOpRayQueryGetRayFlags:
2741 case glslang::EOpRayQueryGetIntersectionT:
2742 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2743 case glslang::EOpRayQueryGetIntersectionInstanceId:
2744 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2745 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2746 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2747 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2748 case glslang::EOpRayQueryGetIntersectionFrontFace:
2749 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
2750 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2751 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2752 case glslang::EOpRayQueryGetWorldRayDirection:
2753 case glslang::EOpRayQueryGetWorldRayOrigin:
2754 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2755 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2756 builder.addExtension("SPV_KHR_ray_query");
2757 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
2758 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002759 case glslang::EOpCooperativeMatrixLoad:
2760 case glslang::EOpCooperativeMatrixStore:
2761 noReturnValue = true;
2762 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002763 case glslang::EOpBeginInvocationInterlock:
2764 case glslang::EOpEndInvocationInterlock:
2765 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2766 noReturnValue = true;
2767 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002768#endif
Chao Chen3c366992018-09-19 11:41:59 -07002769
Jeff Bolz04d73732019-05-31 13:06:01 -05002770 case glslang::EOpDebugPrintf:
2771 noReturnValue = true;
2772 break;
2773
John Kessenich140f3df2015-06-26 16:58:36 -06002774 default:
2775 break;
2776 }
2777
2778 //
2779 // See if it maps to a regular operation.
2780 //
John Kessenich140f3df2015-06-26 16:58:36 -06002781 if (binOp != glslang::EOpNull) {
2782 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2783 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2784 assert(left && right);
2785
2786 builder.clearAccessChain();
2787 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002788 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002789
2790 builder.clearAccessChain();
2791 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002792 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002793
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002794 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002795 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002796 TranslateNoContractionDecoration(node->getType().getQualifier()),
2797 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002798 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002799 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002800 left->getType().getBasicType(), reduceComparison);
2801
2802 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002803 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002804 builder.clearAccessChain();
2805 builder.setAccessChainRValue(result);
2806
2807 return false;
2808 }
2809
John Kessenich426394d2015-07-23 10:22:48 -06002810 //
2811 // Create the list of operands.
2812 //
John Kessenich140f3df2015-06-26 16:58:36 -06002813 glslang::TIntermSequence& glslangOperands = node->getSequence();
2814 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002815 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002816 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002817 // special case l-value operands; there are just a few
2818 bool lvalue = false;
2819 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002820 case glslang::EOpModf:
2821 if (arg == 1)
2822 lvalue = true;
2823 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002824
Torosdagli06c2eee2020-03-19 11:09:57 -04002825 case glslang::EOpRayQueryInitialize:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002826 case glslang::EOpRayQueryTerminate:
2827 case glslang::EOpRayQueryConfirmIntersection:
2828 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04002829 case glslang::EOpRayQueryGenerateIntersection:
2830 case glslang::EOpRayQueryGetIntersectionType:
2831 case glslang::EOpRayQueryGetIntersectionT:
2832 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2833 case glslang::EOpRayQueryGetIntersectionInstanceId:
2834 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2835 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2836 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2837 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2838 case glslang::EOpRayQueryGetIntersectionFrontFace:
2839 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2840 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2841 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2842 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2843 if (arg == 0)
2844 lvalue = true;
2845 break;
2846
John Kesseniche5eee8f2019-10-18 01:03:11 -06002847 case glslang::EOpAtomicAdd:
2848 case glslang::EOpAtomicMin:
2849 case glslang::EOpAtomicMax:
2850 case glslang::EOpAtomicAnd:
2851 case glslang::EOpAtomicOr:
2852 case glslang::EOpAtomicXor:
2853 case glslang::EOpAtomicExchange:
2854 case glslang::EOpAtomicCompSwap:
2855 if (arg == 0)
2856 lvalue = true;
2857 break;
2858
John Kessenicha28f7a72019-08-06 07:00:58 -06002859#ifndef GLSLANG_WEB
2860 case glslang::EOpFrexp:
2861 if (arg == 1)
2862 lvalue = true;
2863 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002864 case glslang::EOpInterpolateAtSample:
2865 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002866 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002867 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002868 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002869
2870 // Does it need a swizzle inversion? If so, evaluation is inverted;
2871 // operate first on the swizzle base, then apply the swizzle.
John Kessenichbbbd9a22020-03-03 07:21:37 -07002872 // That is, we transform
2873 //
2874 // interpolate(v.zy) -> interpolate(v).zy
2875 //
John Kessenichecba76f2017-01-06 00:34:48 -07002876 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002877 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
John Kessenich8985fc92020-03-03 10:25:07 -07002878 invertedType = convertGlslangToSpvType(
2879 glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
John Kessenich8c8505c2016-07-26 12:50:38 -06002880 }
Rex Xu7a26c172015-12-08 17:12:09 +08002881 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002882 case glslang::EOpAtomicLoad:
2883 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002884 case glslang::EOpAtomicCounterAdd:
2885 case glslang::EOpAtomicCounterSubtract:
2886 case glslang::EOpAtomicCounterMin:
2887 case glslang::EOpAtomicCounterMax:
2888 case glslang::EOpAtomicCounterAnd:
2889 case glslang::EOpAtomicCounterOr:
2890 case glslang::EOpAtomicCounterXor:
2891 case glslang::EOpAtomicCounterExchange:
2892 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002893 if (arg == 0)
2894 lvalue = true;
2895 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002896 case glslang::EOpAddCarry:
2897 case glslang::EOpSubBorrow:
2898 if (arg == 2)
2899 lvalue = true;
2900 break;
2901 case glslang::EOpUMulExtended:
2902 case glslang::EOpIMulExtended:
2903 if (arg >= 2)
2904 lvalue = true;
2905 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002906 case glslang::EOpCooperativeMatrixLoad:
2907 if (arg == 0 || arg == 1)
2908 lvalue = true;
2909 break;
2910 case glslang::EOpCooperativeMatrixStore:
2911 if (arg == 1)
2912 lvalue = true;
2913 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002914#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002915 default:
2916 break;
2917 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002918 builder.clearAccessChain();
2919 if (invertedType != spv::NoType && arg == 0)
2920 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2921 else
2922 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002923
John Kessenichb9197c82019-08-11 07:41:45 -06002924#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002925 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2926 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2927
2928 if (arg == 1) {
2929 // fold "element" parameter into the access chain
2930 spv::Builder::AccessChain save = builder.getAccessChain();
2931 builder.clearAccessChain();
2932 glslangOperands[2]->traverse(this);
2933
2934 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2935
2936 builder.setAccessChain(save);
2937
2938 // Point to the first element of the array.
John Kessenich8985fc92020-03-03 10:25:07 -07002939 builder.accessChainPush(elementId,
2940 TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
2941 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002942
2943 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2944 unsigned int alignment = builder.getAccessChain().alignment;
2945
2946 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2947 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2948 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2949 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2950 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
John Kessenich8985fc92020-03-03 10:25:07 -07002951 if (builder.getStorageClass(builder.getAccessChain().base) ==
2952 spv::StorageClassPhysicalStorageBufferEXT) {
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002953 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2954 }
2955
2956 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2957
2958 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2959 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2960 }
2961
John Kessenich8985fc92020-03-03 10:25:07 -07002962 if (memoryAccess &
2963 (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2964 memoryAccessOperands.push_back(spv::IdImmediate(true,
2965 builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002966 }
2967 } else if (arg == 2) {
2968 continue;
2969 }
2970 }
John Kessenichb9197c82019-08-11 07:41:45 -06002971#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002972
John Kessenichbbbd9a22020-03-03 07:21:37 -07002973 // for l-values, pass the address, for r-values, pass the value
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002974 if (lvalue) {
John Kessenichbbbd9a22020-03-03 07:21:37 -07002975 if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
2976 // SPIR-V cannot represent an l-value containing a swizzle that doesn't
2977 // reduce to a simple access chain. So, we need a temporary vector to
2978 // receive the result, and must later swizzle that into the original
2979 // l-value.
Cody Northrop4d2298b2020-04-13 21:59:49 -06002980 complexLvalues.push_back(builder.getAccessChain());
2981 temporaryLvalues.push_back(builder.createVariable(spv::StorageClassFunction,
2982 builder.accessChainGetInferredType(), "swizzleTemp"));
2983 operands.push_back(temporaryLvalues.back());
John Kessenichbbbd9a22020-03-03 07:21:37 -07002984 } else {
2985 operands.push_back(builder.accessChainGetLValue());
2986 }
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002987 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2988 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2989 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002990 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Torosdagli06c2eee2020-03-19 11:09:57 -04002991 glslang::TOperator glslangOp = node->getOp();
2992 if (arg == 1 &&
2993 (glslangOp == glslang::EOpRayQueryGetIntersectionType ||
2994 glslangOp == glslang::EOpRayQueryGetIntersectionT ||
2995 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceCustomIndex ||
2996 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceId ||
2997 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset ||
2998 glslangOp == glslang::EOpRayQueryGetIntersectionGeometryIndex ||
2999 glslangOp == glslang::EOpRayQueryGetIntersectionPrimitiveIndex ||
3000 glslangOp == glslang::EOpRayQueryGetIntersectionBarycentrics ||
3001 glslangOp == glslang::EOpRayQueryGetIntersectionFrontFace ||
3002 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayDirection ||
3003 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayOrigin ||
3004 glslangOp == glslang::EOpRayQueryGetIntersectionObjectToWorld ||
3005 glslangOp == glslang::EOpRayQueryGetIntersectionWorldToObject
3006 )) {
3007 bool cond = glslangOperands[arg]->getAsConstantUnion()->getConstArray()[0].getBConst();
3008 operands.push_back(builder.makeIntConstant(cond ? 1 : 0));
3009 }
3010 else {
3011 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
3012 }
3013
John Kesseniche485c7a2017-05-31 18:50:53 -06003014 }
John Kessenich140f3df2015-06-26 16:58:36 -06003015 }
John Kessenich426394d2015-07-23 10:22:48 -06003016
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003017 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06003018#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003019 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
3020 std::vector<spv::IdImmediate> idImmOps;
3021
3022 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3023 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3024 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3025 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3026 // get the pointee type
3027 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
3028 assert(builder.isCooperativeMatrixType(typeId));
3029 // do the op
3030 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
3031 // store the result to the pointer (out param 'm')
3032 builder.createStore(result, operands[0]);
3033 result = 0;
3034 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
3035 std::vector<spv::IdImmediate> idImmOps;
3036
3037 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3038 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
3039 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3040 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3041 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3042
3043 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
3044 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06003045 } else
3046#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06003047 if (atomic) {
3048 // Handle all atomics
John Kessenich8985fc92020-03-03 10:25:07 -07003049 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
3050 lvalueCoherentFlags);
Jeff Bolz04d73732019-05-31 13:06:01 -05003051 } else if (node->getOp() == glslang::EOpDebugPrintf) {
3052 if (!nonSemanticDebugPrintf) {
3053 nonSemanticDebugPrintf = builder.import("NonSemantic.DebugPrintf");
3054 }
3055 result = builder.createBuiltinCall(builder.makeVoidType(), nonSemanticDebugPrintf, spv::NonSemanticDebugPrintfDebugPrintf, operands);
3056 builder.addExtension(spv::E_SPV_KHR_non_semantic_info);
John Kesseniche5eee8f2019-10-18 01:03:11 -06003057 } else {
John Kessenich426394d2015-07-23 10:22:48 -06003058 // Pass through to generic operations.
3059 switch (glslangOperands.size()) {
3060 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06003061 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06003062 break;
3063 case 1:
John Kessenichead86222018-03-28 18:01:20 -06003064 {
3065 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06003066 TranslateNoContractionDecoration(node->getType().getQualifier()),
3067 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06003068 result = createUnaryOperation(
3069 node->getOp(), decorations,
3070 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003071 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06003072 }
John Kessenich426394d2015-07-23 10:22:48 -06003073 break;
3074 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06003075 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06003076 break;
3077 }
Cody Northrop4d2298b2020-04-13 21:59:49 -06003078
John Kessenichbbbd9a22020-03-03 07:21:37 -07003079 if (invertedType != spv::NoResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003080 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
Cody Northrop4d2298b2020-04-13 21:59:49 -06003081
3082 for (unsigned int i = 0; i < temporaryLvalues.size(); ++i) {
3083 builder.setAccessChain(complexLvalues[i]);
3084 builder.accessChainStore(builder.createLoad(temporaryLvalues[i]));
John Kessenichbbbd9a22020-03-03 07:21:37 -07003085 }
John Kessenich140f3df2015-06-26 16:58:36 -06003086 }
3087
3088 if (noReturnValue)
3089 return false;
3090
3091 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04003092 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07003093 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06003094 } else {
3095 builder.clearAccessChain();
3096 builder.setAccessChainRValue(result);
3097 return false;
3098 }
3099}
3100
John Kessenich433e9ff2017-01-26 20:31:11 -07003101// This path handles both if-then-else and ?:
3102// The if-then-else has a node type of void, while
3103// ?: has either a void or a non-void node type
3104//
3105// Leaving the result, when not void:
3106// GLSL only has r-values as the result of a :?, but
3107// if we have an l-value, that can be more efficient if it will
3108// become the base of a complex r-value expression, because the
3109// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06003110bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
3111{
John Kessenich0c1e71a2019-01-10 18:23:06 +07003112 // see if OpSelect can handle it
3113 const auto isOpSelectable = [&]() {
3114 if (node->getBasicType() == glslang::EbtVoid)
3115 return false;
3116 // OpSelect can do all other types starting with SPV 1.4
3117 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
3118 // pre-1.4, only scalars and vectors can be handled
3119 if ((!node->getType().isScalar() && !node->getType().isVector()))
3120 return false;
3121 }
3122 return true;
3123 };
3124
John Kessenich4bee5312018-02-20 21:29:05 -07003125 // See if it simple and safe, or required, to execute both sides.
3126 // Crucially, side effects must be either semantically required or avoided,
3127 // and there are performance trade-offs.
3128 // Return true if required or a good idea (and safe) to execute both sides,
3129 // false otherwise.
3130 const auto bothSidesPolicy = [&]() -> bool {
3131 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07003132 if (node->getTrueBlock() == nullptr ||
3133 node->getFalseBlock() == nullptr)
3134 return false;
3135
John Kessenich4bee5312018-02-20 21:29:05 -07003136 // required? (unless we write additional code to look for side effects
3137 // and make performance trade-offs if none are present)
3138 if (!node->getShortCircuit())
3139 return true;
3140
3141 // if not required to execute both, decide based on performance/practicality...
3142
John Kessenich0c1e71a2019-01-10 18:23:06 +07003143 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07003144 return false;
3145
John Kessenich433e9ff2017-01-26 20:31:11 -07003146 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
3147 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
3148
3149 // return true if a single operand to ? : is okay for OpSelect
3150 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003151 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07003152 };
3153
3154 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
3155 operandOkay(node->getFalseBlock()->getAsTyped());
3156 };
3157
John Kessenich4bee5312018-02-20 21:29:05 -07003158 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
3159 // emit the condition before doing anything with selection
3160 node->getCondition()->traverse(this);
3161 spv::Id condition = accessChainLoad(node->getCondition()->getType());
3162
3163 // Find a way of executing both sides and selecting the right result.
3164 const auto executeBothSides = [&]() -> void {
3165 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07003166 node->getTrueBlock()->traverse(this);
3167 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3168 node->getFalseBlock()->traverse(this);
3169 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3170
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003171 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003172
John Kessenich4bee5312018-02-20 21:29:05 -07003173 // done if void
3174 if (node->getBasicType() == glslang::EbtVoid)
3175 return;
John Kesseniche434ad92017-03-30 10:09:28 -06003176
John Kessenich4bee5312018-02-20 21:29:05 -07003177 // emit code to select between trueValue and falseValue
3178
3179 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07003180 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07003181 // Emit OpSelect for this selection.
3182
3183 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07003184 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
3185 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07003186 condition = builder.smearScalar(spv::NoPrecision, condition,
3187 builder.makeVectorType(builder.makeBoolType(),
3188 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07003189 }
John Kessenich4bee5312018-02-20 21:29:05 -07003190
3191 // OpSelect
3192 result = builder.createTriOp(spv::OpSelect,
3193 convertGlslangToSpvType(node->getType()), condition,
3194 trueValue, falseValue);
3195
3196 builder.clearAccessChain();
3197 builder.setAccessChainRValue(result);
3198 } else {
3199 // We need control flow to select the result.
3200 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
3201 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
3202
3203 // Selection control:
3204 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3205
3206 // make an "if" based on the value created by the condition
3207 spv::Builder::If ifBuilder(condition, control, builder);
3208
3209 // emit the "then" statement
3210 builder.createStore(trueValue, result);
3211 ifBuilder.makeBeginElse();
3212 // emit the "else" statement
3213 builder.createStore(falseValue, result);
3214
3215 // finish off the control flow
3216 ifBuilder.makeEndIf();
3217
3218 builder.clearAccessChain();
3219 builder.setAccessChainLValue(result);
3220 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003221 };
3222
John Kessenich4bee5312018-02-20 21:29:05 -07003223 // Execute the one side needed, as per the condition
3224 const auto executeOneSide = [&]() {
3225 // Always emit control flow.
3226 if (node->getBasicType() != glslang::EbtVoid)
3227 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07003228
John Kessenich4bee5312018-02-20 21:29:05 -07003229 // Selection control:
3230 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3231
3232 // make an "if" based on the value created by the condition
3233 spv::Builder::If ifBuilder(condition, control, builder);
3234
3235 // emit the "then" statement
3236 if (node->getTrueBlock() != nullptr) {
3237 node->getTrueBlock()->traverse(this);
3238 if (result != spv::NoResult)
3239 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3240 }
3241
3242 if (node->getFalseBlock() != nullptr) {
3243 ifBuilder.makeBeginElse();
3244 // emit the "else" statement
3245 node->getFalseBlock()->traverse(this);
3246 if (result != spv::NoResult)
3247 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3248 }
3249
3250 // finish off the control flow
3251 ifBuilder.makeEndIf();
3252
3253 if (result != spv::NoResult) {
3254 builder.clearAccessChain();
3255 builder.setAccessChainLValue(result);
3256 }
3257 };
3258
3259 // Try for OpSelect (or a requirement to execute both sides)
3260 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003261 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3262 if (node->getType().getQualifier().isSpecConstant())
3263 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003264 executeBothSides();
3265 } else
3266 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003267
3268 return false;
3269}
3270
3271bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3272{
3273 // emit and get the condition before doing anything with switch
3274 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003275 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003276
Rex Xu57e65922017-07-04 23:23:40 +08003277 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003278 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003279
John Kessenich140f3df2015-06-26 16:58:36 -06003280 // browse the children to sort out code segments
3281 int defaultSegment = -1;
3282 std::vector<TIntermNode*> codeSegments;
3283 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3284 std::vector<int> caseValues;
3285 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3286 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3287 TIntermNode* child = *c;
3288 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003289 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003290 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003291 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich8985fc92020-03-03 10:25:07 -07003292 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()
3293 ->getConstArray()[0].getIConst());
John Kessenich140f3df2015-06-26 16:58:36 -06003294 } else
3295 codeSegments.push_back(child);
3296 }
3297
qining25262b32016-05-06 17:25:16 -04003298 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003299 // statements between the last case and the end of the switch statement
3300 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3301 (int)codeSegments.size() == defaultSegment)
3302 codeSegments.push_back(nullptr);
3303
3304 // make the switch statement
3305 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
John Kessenich8985fc92020-03-03 10:25:07 -07003306 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment,
3307 segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003308
3309 // emit all the code in the segments
3310 breakForLoop.push(false);
3311 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3312 builder.nextSwitchSegment(segmentBlocks, s);
3313 if (codeSegments[s])
3314 codeSegments[s]->traverse(this);
3315 else
3316 builder.addSwitchBreak();
3317 }
3318 breakForLoop.pop();
3319
3320 builder.endSwitch(segmentBlocks);
3321
3322 return false;
3323}
3324
3325void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3326{
3327 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003328 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003329
3330 builder.clearAccessChain();
3331 builder.setAccessChainRValue(constant);
3332}
3333
3334bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3335{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003336 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003337 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003338
3339 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003340 std::vector<unsigned int> operands;
3341 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003342
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003343 // Spec requires back edges to target header blocks, and every header block
3344 // must dominate its merge block. Make a header block first to ensure these
3345 // conditions are met. By definition, it will contain OpLoopMerge, followed
3346 // by a block-ending branch. But we don't want to put any other body/test
3347 // instructions in it, since the body/test may have arbitrary instructions,
3348 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003349 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003350 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003351 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003352 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003353 spv::Block& test = builder.makeNewBlock();
3354 builder.createBranch(&test);
3355
3356 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003357 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003358 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003359 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3360
3361 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003362 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003363 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003364 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003365 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003366 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003367
3368 builder.setBuildPoint(&blocks.continue_target);
3369 if (node->getTerminal())
3370 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003371 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003372 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003373 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003374 builder.createBranch(&blocks.body);
3375
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003376 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003377 builder.setBuildPoint(&blocks.body);
3378 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003379 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003380 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003381 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003382
3383 builder.setBuildPoint(&blocks.continue_target);
3384 if (node->getTerminal())
3385 node->getTerminal()->traverse(this);
3386 if (node->getTest()) {
3387 node->getTest()->traverse(this);
3388 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003389 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003390 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003391 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003392 // TODO: unless there was a break/return/discard instruction
3393 // somewhere in the body, this is an infinite loop, so we should
3394 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003395 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003396 }
John Kessenich140f3df2015-06-26 16:58:36 -06003397 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003398 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003399 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003400 return false;
3401}
3402
3403bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3404{
3405 if (node->getExpression())
3406 node->getExpression()->traverse(this);
3407
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003408 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003409
John Kessenich140f3df2015-06-26 16:58:36 -06003410 switch (node->getFlowOp()) {
3411 case glslang::EOpKill:
3412 builder.makeDiscard();
3413 break;
3414 case glslang::EOpBreak:
3415 if (breakForLoop.top())
3416 builder.createLoopExit();
3417 else
3418 builder.addSwitchBreak();
3419 break;
3420 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003421 builder.createLoopContinue();
3422 break;
3423 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003424 if (node->getExpression()) {
3425 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3426 spv::Id returnId = accessChainLoad(glslangReturnType);
3427 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3428 builder.clearAccessChain();
3429 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3430 builder.setAccessChainLValue(copyId);
3431 multiTypeStore(glslangReturnType, returnId);
3432 returnId = builder.createLoad(copyId);
3433 }
3434 builder.makeReturn(false, returnId);
3435 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003436 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003437
3438 builder.clearAccessChain();
3439 break;
3440
John Kessenichb9197c82019-08-11 07:41:45 -06003441#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003442 case glslang::EOpDemote:
3443 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3444 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3445 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3446 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003447#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003448
John Kessenich140f3df2015-06-26 16:58:36 -06003449 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003450 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003451 break;
3452 }
3453
3454 return false;
3455}
3456
John Kessenich9c14f772019-06-17 08:38:35 -06003457spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003458{
qining25262b32016-05-06 17:25:16 -04003459 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003460 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003461 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003462 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003463 spv::Id result = createSpvConstant(*node);
3464 if (result != spv::NoResult)
3465 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003466 }
3467
3468 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003469 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003470 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3471 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003472
John Kessenichb9197c82019-08-11 07:41:45 -06003473 const bool contains16BitType = node->getType().contains16BitFloat() ||
3474 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003475 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003476 switch (storageClass) {
3477 case spv::StorageClassInput:
3478 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003479 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003480 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003481 break;
John Kessenich18310872018-05-14 22:08:53 -06003482 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003483 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003484 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3485 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003486 else
3487 builder.addCapability(spv::CapabilityStorageUniform16);
3488 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003489#ifndef GLSLANG_WEB
3490 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003491 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003492 builder.addCapability(spv::CapabilityStoragePushConstant16);
3493 break;
John Kessenich18310872018-05-14 22:08:53 -06003494 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003495 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003496 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003497 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3498 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003499#endif
John Kessenich18310872018-05-14 22:08:53 -06003500 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003501 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003502 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003503 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003504 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003505 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003506 }
3507 }
Rex Xuf89ad982017-04-07 23:22:33 +08003508
John Kessenichb9197c82019-08-11 07:41:45 -06003509 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003510 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003511 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003512 builder.addCapability(spv::CapabilityStoragePushConstant8);
3513 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003514 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003515 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003516 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003517 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003518 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003519 } else {
3520 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003521 }
3522 }
3523
John Kessenich140f3df2015-06-26 16:58:36 -06003524 const char* name = node->getName().c_str();
3525 if (glslang::IsAnonymous(name))
3526 name = "";
3527
3528 return builder.createVariable(storageClass, spvType, name);
3529}
3530
3531// Return type Id of the sampled type.
3532spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3533{
3534 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003535 case glslang::EbtInt: return builder.makeIntType(32);
3536 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003537 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003538#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003539 case glslang::EbtFloat16:
3540 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3541 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3542 return builder.makeFloatType(16);
3543#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003544 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003545 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003546 return builder.makeFloatType(32);
3547 }
3548}
3549
John Kessenich8c8505c2016-07-26 12:50:38 -06003550// If node is a swizzle operation, return the type that should be used if
3551// the swizzle base is first consumed by another operation, before the swizzle
3552// is applied.
3553spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3554{
John Kessenichecba76f2017-01-06 00:34:48 -07003555 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003556 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3557 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3558 else
3559 return spv::NoType;
3560}
3561
3562// When inverting a swizzle with a parent op, this function
3563// will apply the swizzle operation to a completed parent operation.
John Kessenich8985fc92020-03-03 10:25:07 -07003564spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
3565 spv::Id parentResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003566{
3567 std::vector<unsigned> swizzle;
3568 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3569 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3570}
3571
John Kessenich8c8505c2016-07-26 12:50:38 -06003572// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3573void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3574{
3575 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3576 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3577 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3578}
3579
John Kessenich3ac051e2015-12-20 11:29:16 -07003580// Convert from a glslang type to an SPV type, by calling into a
3581// recursive version of this function. This establishes the inherited
3582// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003583spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003584{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003585 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003586}
3587
3588// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003589// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003590// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003591spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003592 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3593 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003594{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003595 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003596
3597 switch (type.getBasicType()) {
3598 case glslang::EbtVoid:
3599 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003600 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003601 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003602 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003603 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3604 // a 32-bit int where non-0 means true.
3605 if (explicitLayout != glslang::ElpNone)
3606 spvType = builder.makeUintType(32);
3607 else
3608 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003609 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003610 case glslang::EbtInt:
3611 spvType = builder.makeIntType(32);
3612 break;
3613 case glslang::EbtUint:
3614 spvType = builder.makeUintType(32);
3615 break;
3616 case glslang::EbtFloat:
3617 spvType = builder.makeFloatType(32);
3618 break;
3619#ifndef GLSLANG_WEB
3620 case glslang::EbtDouble:
3621 spvType = builder.makeFloatType(64);
3622 break;
3623 case glslang::EbtFloat16:
3624 spvType = builder.makeFloatType(16);
3625 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003626 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003627 spvType = builder.makeIntType(8);
3628 break;
3629 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003630 spvType = builder.makeUintType(8);
3631 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003632 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003633 spvType = builder.makeIntType(16);
3634 break;
3635 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003636 spvType = builder.makeUintType(16);
3637 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003638 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003639 spvType = builder.makeIntType(64);
3640 break;
3641 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003642 spvType = builder.makeUintType(64);
3643 break;
John Kessenich426394d2015-07-23 10:22:48 -06003644 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003645 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003646 spvType = builder.makeUintType(32);
3647 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04003648 case glslang::EbtAccStruct:
3649 spvType = builder.makeAccelerationStructureType();
Chao Chenb50c02e2018-09-19 11:42:24 -07003650 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04003651 case glslang::EbtRayQuery:
3652 spvType = builder.makeRayQueryType();
3653 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003654 case glslang::EbtReference:
3655 {
3656 // Make the forward pointer, then recurse to convert the structure type, then
3657 // patch up the forward pointer with a real pointer type.
3658 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3659 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3660 forwardPointers[type.getReferentType()] = forwardId;
3661 }
3662 spvType = forwardPointers[type.getReferentType()];
3663 if (!forwardReferenceOnly) {
3664 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3665 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3666 forwardPointers[type.getReferentType()],
3667 referentType);
3668 }
3669 }
3670 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003671#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003672 case glslang::EbtSampler:
3673 {
3674 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003675 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003676 spvType = builder.makeSamplerType();
3677 } else {
3678 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003679 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3680 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3681 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3682 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003683 // already has both image and sampler, make the combined type
3684 spvType = builder.makeSampledImageType(spvType);
3685 }
John Kessenich55e7d112015-11-15 21:33:39 -07003686 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003687 }
John Kessenich140f3df2015-06-26 16:58:36 -06003688 break;
3689 case glslang::EbtStruct:
3690 case glslang::EbtBlock:
3691 {
3692 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003693 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003694
3695 // Try to share structs for different layouts, but not yet for other
3696 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003697 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003698 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003699 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003700 break;
3701
3702 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003703 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003704 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003705 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003706 }
3707 break;
Jeff Bolz04d73732019-05-31 13:06:01 -05003708 case glslang::EbtString:
3709 // no type used for OpString
3710 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003711 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003712 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003713 break;
3714 }
3715
3716 if (type.isMatrix())
3717 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3718 else {
3719 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3720 if (type.getVectorSize() > 1)
3721 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3722 }
3723
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003724 if (type.isCoopMat()) {
3725 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3726 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3727 if (type.getBasicType() == glslang::EbtFloat16)
3728 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003729 if (type.getBasicType() == glslang::EbtUint8 ||
3730 type.getBasicType() == glslang::EbtInt8) {
3731 builder.addCapability(spv::CapabilityInt8);
3732 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003733
3734 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3735 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3736 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3737
3738 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3739 }
3740
John Kessenich140f3df2015-06-26 16:58:36 -06003741 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003742 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3743
John Kessenichc9a80832015-09-12 12:17:44 -06003744 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003745 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003746 // We need to decorate array strides for types needing explicit layout, except blocks.
3747 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003748 // Use a dummy glslang type for querying internal strides of
3749 // arrays of arrays, but using just a one-dimensional array.
3750 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003751 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3752 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003753
3754 // Will compute the higher-order strides here, rather than making a whole
3755 // pile of types and doing repetitive recursion on their contents.
3756 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3757 }
John Kessenichf8842e52016-01-04 19:22:56 -07003758
3759 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003760 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003761 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003762 if (stride > 0)
3763 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003764 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003765 }
3766 } else {
3767 // single-dimensional array, and don't yet have stride
3768
John Kessenichf8842e52016-01-04 19:22:56 -07003769 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003770 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3771 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003772 }
John Kessenich31ed4832015-09-09 17:51:38 -06003773
John Kessenichead86222018-03-28 18:01:20 -06003774 // Do the outer dimension, which might not be known for a runtime-sized array.
3775 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3776 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003777 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003778 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003779#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003780 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003781 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003782 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3783 }
John Kessenichb9197c82019-08-11 07:41:45 -06003784#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003785 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003786 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003787 if (stride > 0)
3788 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003789 }
3790
3791 return spvType;
3792}
3793
John Kessenich0e737842017-03-24 18:38:16 -06003794// TODO: this functionality should exist at a higher level, in creating the AST
3795//
3796// Identify interface members that don't have their required extension turned on.
3797//
3798bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3799{
John Kessenicha28f7a72019-08-06 07:00:58 -06003800#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003801 auto& extensions = glslangIntermediate->getRequestedExtensions();
3802
Rex Xubcf291a2017-03-29 23:01:36 +08003803 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3804 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3805 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003806 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3807 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3808 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003809
3810 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3811 if (member.getFieldName() == "gl_ViewportMask" &&
3812 extensions.find("GL_NV_viewport_array2") == extensions.end())
3813 return true;
3814 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3815 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3816 return true;
3817 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3818 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3819 return true;
3820 }
3821#endif
John Kessenich0e737842017-03-24 18:38:16 -06003822
3823 return false;
3824};
3825
John Kessenich6090df02016-06-30 21:18:02 -06003826// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3827// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3828// Mutually recursive with convertGlslangToSpvType().
3829spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3830 const glslang::TTypeList* glslangMembers,
3831 glslang::TLayoutPacking explicitLayout,
3832 const glslang::TQualifier& qualifier)
3833{
3834 // Create a vector of struct types for SPIR-V to consume
3835 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07003836 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
3837 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003838 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003839 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3840 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3841 if (glslangMember.hiddenMember()) {
3842 ++memberDelta;
3843 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003844 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06003845 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003846 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003847 if (filterMember(glslangMember)) {
3848 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08003849 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003850 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003851 }
Roy05a5b532020-01-03 16:21:34 +08003852 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003853 }
John Kessenich6090df02016-06-30 21:18:02 -06003854 // modify just this child's view of the qualifier
3855 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3856 InheritQualifiers(memberQualifier, qualifier);
3857
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003858 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003859 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003860 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003861
3862 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003863 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3864 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003865
3866 // Make forward pointers for any pointer members, and create a list of members to
3867 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003868 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003869 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3870 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3871 }
3872 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003873 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3874 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003875 } else {
3876 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003877 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3878 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003879 }
John Kessenich6090df02016-06-30 21:18:02 -06003880 }
3881 }
3882
3883 // Make the SPIR-V type
3884 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003885 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003886 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3887
3888 // Decorate it
3889 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3890
John Kessenichd72f4882019-01-16 14:55:37 +07003891 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003892 auto it = deferredForwardPointers[i];
3893 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3894 }
3895
John Kessenich6090df02016-06-30 21:18:02 -06003896 return spvType;
3897}
3898
3899void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3900 const glslang::TTypeList* glslangMembers,
3901 glslang::TLayoutPacking explicitLayout,
3902 const glslang::TQualifier& qualifier,
3903 spv::Id spvType)
3904{
3905 // Name and decorate the non-hidden members
3906 int offset = -1;
3907 int locationOffset = 0; // for use within the members of this struct
3908 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3909 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3910 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003911 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08003912 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06003913 if (filterMember(glslangMember))
3914 continue;
3915 }
John Kessenich6090df02016-06-30 21:18:02 -06003916
3917 // modify just this child's view of the qualifier
3918 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3919 InheritQualifiers(memberQualifier, qualifier);
3920
3921 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003922 if (member < 0)
3923 continue;
3924
3925 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3926 builder.addMemberDecoration(spvType, member,
3927 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3928 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3929 // Add interpolation and auxiliary storage decorations only to
3930 // top-level members of Input and Output storage classes
3931 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3932 type.getQualifier().storage == glslang::EvqVaryingOut) {
3933 if (type.getBasicType() == glslang::EbtBlock ||
3934 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3935 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3936 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003937#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003938 addMeshNVDecoration(spvType, member, memberQualifier);
3939#endif
John Kessenich6090df02016-06-30 21:18:02 -06003940 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003941 }
3942 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003943
John Kessenichb9197c82019-08-11 07:41:45 -06003944#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003945 if (type.getBasicType() == glslang::EbtBlock &&
3946 qualifier.storage == glslang::EvqBuffer) {
3947 // Add memory decorations only to top-level members of shader storage block
3948 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003949 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003950 for (unsigned int i = 0; i < memory.size(); ++i)
3951 builder.addMemberDecoration(spvType, member, memory[i]);
3952 }
John Kessenichf8d1d742019-10-21 06:55:11 -06003953
John Kessenichb9197c82019-08-11 07:41:45 -06003954#endif
John Kessenich6090df02016-06-30 21:18:02 -06003955
John Kessenich5d610ee2018-03-07 18:05:55 -07003956 // Location assignment was already completed correctly by the front end,
3957 // just track whether a member needs to be decorated.
3958 // Ignore member locations if the container is an array, as that's
3959 // ill-specified and decisions have been made to not allow this.
3960 if (! type.isArray() && memberQualifier.hasLocation())
3961 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003962
John Kessenich5d610ee2018-03-07 18:05:55 -07003963 if (qualifier.hasLocation()) // track for upcoming inheritance
3964 locationOffset += glslangIntermediate->computeTypeLocationSize(
3965 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003966
John Kessenich5d610ee2018-03-07 18:05:55 -07003967 // component, XFB, others
3968 if (glslangMember.getQualifier().hasComponent())
3969 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3970 glslangMember.getQualifier().layoutComponent);
3971 if (glslangMember.getQualifier().hasXfbOffset())
3972 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3973 glslangMember.getQualifier().layoutXfbOffset);
3974 else if (explicitLayout != glslang::ElpNone) {
3975 // figure out what to do with offset, which is accumulating
3976 int nextOffset;
3977 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3978 if (offset >= 0)
3979 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3980 offset = nextOffset;
3981 }
John Kessenich6090df02016-06-30 21:18:02 -06003982
John Kessenich5d610ee2018-03-07 18:05:55 -07003983 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3984 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3985 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003986
John Kessenich5d610ee2018-03-07 18:05:55 -07003987 // built-in variable decorations
3988 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3989 if (builtIn != spv::BuiltInMax)
3990 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003991
John Kessenichb9197c82019-08-11 07:41:45 -06003992#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003993 // nonuniform
3994 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3995
John Kessenichead86222018-03-28 18:01:20 -06003996 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3997 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3998 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3999 memberQualifier.semanticName);
4000 }
4001
John Kessenich5d610ee2018-03-07 18:05:55 -07004002 if (builtIn == spv::BuiltInLayer) {
4003 // SPV_NV_viewport_array2 extension
4004 if (glslangMember.getQualifier().layoutViewportRelative){
4005 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
4006 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4007 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08004008 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004009 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
4010 builder.addMemberDecoration(spvType, member,
4011 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
4012 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
4013 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4014 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08004015 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004016 }
4017 if (glslangMember.getQualifier().layoutPassthrough) {
4018 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
4019 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
4020 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4021 }
chaoc771d89f2017-01-13 01:10:53 -08004022#endif
John Kessenich6090df02016-06-30 21:18:02 -06004023 }
4024
4025 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07004026 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
4027 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06004028}
4029
John Kessenich6c292d32016-02-15 20:58:50 -07004030// Turn the expression forming the array size into an id.
4031// This is not quite trivial, because of specialization constants.
4032// Sometimes, a raw constant is turned into an Id, and sometimes
4033// a specialization constant expression is.
4034spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
4035{
4036 // First, see if this is sized with a node, meaning a specialization constant:
4037 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
4038 if (specNode != nullptr) {
4039 builder.clearAccessChain();
4040 specNode->traverse(this);
4041 return accessChainLoad(specNode->getAsTyped()->getType());
4042 }
qining25262b32016-05-06 17:25:16 -04004043
John Kessenich6c292d32016-02-15 20:58:50 -07004044 // Otherwise, need a compile-time (front end) size, get it:
4045 int size = arraySizes.getDimSize(dim);
4046 assert(size > 0);
4047 return builder.makeUintConstant(size);
4048}
4049
John Kessenich103bef92016-02-08 21:38:15 -07004050// Wrap the builder's accessChainLoad to:
4051// - localize handling of RelaxedPrecision
4052// - use the SPIR-V inferred type instead of another conversion of the glslang type
4053// (avoids unnecessary work and possible type punning for structures)
4054// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07004055spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
4056{
John Kessenich103bef92016-02-08 21:38:15 -07004057 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004058
4059 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4060 coherentFlags |= TranslateCoherent(type);
4061
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004062 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004063 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004064
John Kessenich5611c6d2018-04-05 11:25:02 -06004065 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
John Kessenich8985fc92020-03-03 10:25:07 -07004066 TranslateNonUniformDecoration(type.getQualifier()),
4067 nominalTypeId,
4068 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
4069 TranslateMemoryScope(coherentFlags),
4070 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07004071
4072 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08004073 if (type.getBasicType() == glslang::EbtBool) {
4074 if (builder.isScalarType(nominalTypeId)) {
4075 // Conversion for bool
4076 spv::Id boolType = builder.makeBoolType();
4077 if (nominalTypeId != boolType)
4078 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
4079 } else if (builder.isVectorType(nominalTypeId)) {
4080 // Conversion for bvec
4081 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4082 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
4083 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07004084 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
4085 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004086 }
4087 }
John Kessenich103bef92016-02-08 21:38:15 -07004088
4089 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07004090}
4091
Rex Xu27253232016-02-23 17:51:09 +08004092// Wrap the builder's accessChainStore to:
4093// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06004094//
4095// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08004096void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
4097{
4098 // Need to convert to abstract types when necessary
4099 if (type.getBasicType() == glslang::EbtBool) {
4100 spv::Id nominalTypeId = builder.accessChainGetInferredType();
4101
4102 if (builder.isScalarType(nominalTypeId)) {
4103 // Conversion for bool
4104 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06004105 if (nominalTypeId != boolType) {
4106 // keep these outside arguments, for determinant order-of-evaluation
4107 spv::Id one = builder.makeUintConstant(1);
4108 spv::Id zero = builder.makeUintConstant(0);
4109 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
4110 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06004111 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08004112 } else if (builder.isVectorType(nominalTypeId)) {
4113 // Conversion for bvec
4114 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4115 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06004116 if (nominalTypeId != bvecType) {
4117 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06004118 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
4119 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
4120 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06004121 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06004122 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
4123 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004124 }
4125 }
4126
Jeff Bolz36831c92018-09-05 10:11:41 -05004127 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4128 coherentFlags |= TranslateCoherent(type);
4129
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004130 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004131 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004132
Jeff Bolz36831c92018-09-05 10:11:41 -05004133 builder.accessChainStore(rvalue,
John Kessenich8985fc92020-03-03 10:25:07 -07004134 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
4135 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004136 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08004137}
4138
John Kessenich4bf71552016-09-02 11:20:21 -06004139// For storing when types match at the glslang level, but not might match at the
4140// SPIR-V level.
4141//
4142// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004143// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004144// as in a member-decorated way.
4145//
4146// NOTE: This function can handle any store request; if it's not special it
4147// simplifies to a simple OpStore.
4148//
4149// Implicitly uses the existing builder.accessChain as the storage target.
4150void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4151{
John Kessenichb3e24e42016-09-11 12:33:43 -06004152 // we only do the complex path here if it's an aggregate
4153 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004154 accessChainStore(type, rValue);
4155 return;
4156 }
4157
John Kessenichb3e24e42016-09-11 12:33:43 -06004158 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004159 spv::Id rType = builder.getTypeId(rValue);
4160 spv::Id lValue = builder.accessChainGetLValue();
4161 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4162 if (lType == rType) {
4163 accessChainStore(type, rValue);
4164 return;
4165 }
4166
John Kessenichb3e24e42016-09-11 12:33:43 -06004167 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004168 // where the two types were the same type in GLSL. This requires member
4169 // by member copy, recursively.
4170
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004171 // SPIR-V 1.4 added an instruction to do help do this.
4172 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4173 // However, bool in uniform space is changed to int, so
4174 // OpCopyLogical does not work for that.
4175 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4176 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4177 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4178 if (lBool == rBool) {
4179 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4180 accessChainStore(type, logicalCopy);
4181 return;
4182 }
4183 }
4184
John Kessenichb3e24e42016-09-11 12:33:43 -06004185 // If an array, copy element by element.
4186 if (type.isArray()) {
4187 glslang::TType glslangElementType(type, 0);
4188 spv::Id elementRType = builder.getContainedTypeId(rType);
4189 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4190 // get the source member
4191 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004192
John Kessenichb3e24e42016-09-11 12:33:43 -06004193 // set up the target storage
4194 builder.clearAccessChain();
4195 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004196 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4197 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004198
John Kessenichb3e24e42016-09-11 12:33:43 -06004199 // store the member
4200 multiTypeStore(glslangElementType, elementRValue);
4201 }
4202 } else {
4203 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004204
John Kessenichb3e24e42016-09-11 12:33:43 -06004205 // loop over structure members
4206 const glslang::TTypeList& members = *type.getStruct();
4207 for (int m = 0; m < (int)members.size(); ++m) {
4208 const glslang::TType& glslangMemberType = *members[m].type;
4209
4210 // get the source member
4211 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4212 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4213
4214 // set up the target storage
4215 builder.clearAccessChain();
4216 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004217 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4218 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004219
4220 // store the member
4221 multiTypeStore(glslangMemberType, memberRValue);
4222 }
John Kessenich4bf71552016-09-02 11:20:21 -06004223 }
4224}
4225
John Kessenichf85e8062015-12-19 13:57:10 -07004226// Decide whether or not this type should be
4227// decorated with offsets and strides, and if so
4228// whether std140 or std430 rules should be applied.
4229glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004230{
John Kessenichf85e8062015-12-19 13:57:10 -07004231 // has to be a block
4232 if (type.getBasicType() != glslang::EbtBlock)
4233 return glslang::ElpNone;
4234
Chao Chen3c366992018-09-19 11:41:59 -07004235 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004236 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004237 type.getQualifier().storage != glslang::EvqBuffer &&
4238 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004239 return glslang::ElpNone;
4240
4241 // return the layout to use
4242 switch (type.getQualifier().layoutPacking) {
4243 case glslang::ElpStd140:
4244 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004245 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004246 return type.getQualifier().layoutPacking;
4247 default:
4248 return glslang::ElpNone;
4249 }
John Kessenich31ed4832015-09-09 17:51:38 -06004250}
4251
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004252// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004253int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4254 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004255{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004256 int size;
John Kessenich49987892015-12-29 17:11:44 -07004257 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004258 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4259 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004260
4261 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004262}
4263
John Kessenich49987892015-12-29 17:11:44 -07004264// 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 -07004265// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004266int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4267 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004268{
John Kessenich49987892015-12-29 17:11:44 -07004269 glslang::TType elementType;
4270 elementType.shallowCopy(matrixType);
4271 elementType.clearArraySizes();
4272
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004273 int size;
John Kessenich49987892015-12-29 17:11:44 -07004274 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004275 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4276 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004277
4278 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004279}
4280
John Kessenich5e4b1242015-08-06 22:53:06 -06004281// Given a member type of a struct, realign the current offset for it, and compute
4282// the next (not yet aligned) offset for the next member, which will get aligned
4283// on the next call.
4284// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4285// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4286// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004287void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4288 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004289{
4290 // this will get a positive value when deemed necessary
4291 nextOffset = -1;
4292
John Kessenich5e4b1242015-08-06 22:53:06 -06004293 // override anything in currentOffset with user-set offset
4294 if (memberType.getQualifier().hasOffset())
4295 currentOffset = memberType.getQualifier().layoutOffset;
4296
4297 // It could be that current linker usage in glslang updated all the layoutOffset,
4298 // in which case the following code does not matter. But, that's not quite right
4299 // once cross-compilation unit GLSL validation is done, as the original user
4300 // settings are needed in layoutOffset, and then the following will come into play.
4301
John Kessenichf85e8062015-12-19 13:57:10 -07004302 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004303 if (! memberType.getQualifier().hasOffset())
4304 currentOffset = -1;
4305
4306 return;
4307 }
4308
John Kessenichf85e8062015-12-19 13:57:10 -07004309 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004310 if (currentOffset < 0)
4311 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004312
John Kessenich5e4b1242015-08-06 22:53:06 -06004313 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4314 // but possibly not yet correctly aligned.
4315
4316 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004317 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004318 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4319 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004320
4321 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004322 // TODO: make this consistent in early phases of code:
4323 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4324 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4325 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004326 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004327 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004328 int dummySize;
4329 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4330 if (componentAlignment <= 4)
4331 memberAlignment = componentAlignment;
4332 }
4333
4334 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004335 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004336
4337 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004338 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4339 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004340 glslang::RoundToPow2(currentOffset, 16);
4341
John Kessenich5e4b1242015-08-06 22:53:06 -06004342 nextOffset = currentOffset + memberSize;
4343}
4344
David Netoa901ffe2016-06-08 14:11:40 +01004345void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004346{
David Netoa901ffe2016-06-08 14:11:40 +01004347 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4348 switch (glslangBuiltIn)
4349 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004350 case glslang::EbvPointSize:
4351#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004352 case glslang::EbvClipDistance:
4353 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004354 case glslang::EbvViewportMaskNV:
4355 case glslang::EbvSecondaryPositionNV:
4356 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004357 case glslang::EbvPositionPerViewNV:
4358 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004359 case glslang::EbvTaskCountNV:
4360 case glslang::EbvPrimitiveCountNV:
4361 case glslang::EbvPrimitiveIndicesNV:
4362 case glslang::EbvClipDistancePerViewNV:
4363 case glslang::EbvCullDistancePerViewNV:
4364 case glslang::EbvLayerPerViewNV:
4365 case glslang::EbvMeshViewCountNV:
4366 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004367#endif
David Netoa901ffe2016-06-08 14:11:40 +01004368 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4369 // Alternately, we could just call this for any glslang built-in, since the
4370 // capability already guards against duplicates.
4371 TranslateBuiltInDecoration(glslangBuiltIn, false);
4372 break;
4373 default:
4374 // Capabilities were already generated when the struct was declared.
4375 break;
4376 }
John Kessenichebb50532016-05-16 19:22:05 -06004377}
4378
John Kessenich6fccb3c2016-09-19 16:01:41 -06004379bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004380{
John Kessenicheee9d532016-09-19 18:09:30 -06004381 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004382}
4383
John Kessenichd41993d2017-09-10 15:21:05 -06004384// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004385// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4386// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004387bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004388{
John Kessenich6a14f782017-12-04 02:48:10 -07004389 assert(qualifier == glslang::EvqIn ||
4390 qualifier == glslang::EvqOut ||
4391 qualifier == glslang::EvqInOut ||
rdbd8edfd82020-06-02 08:30:07 +02004392 qualifier == glslang::EvqUniform ||
John Kessenich6a14f782017-12-04 02:48:10 -07004393 qualifier == glslang::EvqConstReadOnly);
rdbd8edfd82020-06-02 08:30:07 +02004394 return qualifier != glslang::EvqConstReadOnly &&
4395 qualifier != glslang::EvqUniform;
John Kessenichd41993d2017-09-10 15:21:05 -06004396}
4397
4398// Is parameter pass-by-original?
4399bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4400 bool implicitThisParam)
4401{
4402 if (implicitThisParam) // implicit this
4403 return true;
4404 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004405 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004406 return paramType.containsOpaque() || // sampler, etc.
4407 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4408}
4409
John Kessenich140f3df2015-06-26 16:58:36 -06004410// Make all the functions, skeletally, without actually visiting their bodies.
4411void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4412{
John Kessenich8985fc92020-03-03 10:25:07 -07004413 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4414 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004415 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4416 if (paramPrecision != spv::NoPrecision)
4417 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004418 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004419 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004420 // Original and non-writable params pass the pointer directly and
4421 // use restrict/aliased, others are stored to a pointer in Function
4422 // memory and use RestrictPointer/AliasedPointer.
4423 if (originalParam(type.getQualifier().storage, type, false) ||
4424 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004425 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4426 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004427 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004428 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4429 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004430 }
4431 }
John Kessenichfad62972017-07-18 02:35:46 -06004432 };
4433
John Kessenich140f3df2015-06-26 16:58:36 -06004434 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4435 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004436 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004437 continue;
4438
4439 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004440 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004441 //
qining25262b32016-05-06 17:25:16 -04004442 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004443 // function. What it is an address of varies:
4444 //
John Kessenich4bf71552016-09-02 11:20:21 -06004445 // - "in" parameters not marked as "const" can be written to without modifying the calling
4446 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004447 //
4448 // - "const in" parameters can just be the r-value, as no writes need occur.
4449 //
John Kessenich4bf71552016-09-02 11:20:21 -06004450 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4451 // 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 -06004452
4453 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004454 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004455 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4456
John Kessenich155d3512019-08-08 23:29:20 -06004457#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004458 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4459 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004460#else
4461 bool implicitThis = false;
4462#endif
John Kessenich37789792017-03-21 23:56:40 -06004463
John Kessenichfad62972017-07-18 02:35:46 -06004464 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004465 for (int p = 0; p < (int)parameters.size(); ++p) {
4466 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4467 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004468 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004469 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004470 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004471 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4472 else
John Kessenich4bf71552016-09-02 11:20:21 -06004473 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004474 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004475 paramTypes.push_back(typeId);
4476 }
4477
4478 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004479 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4480 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004481 glslFunction->getName().c_str(), paramTypes,
4482 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004483 if (implicitThis)
4484 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004485
4486 // Track function to emit/call later
4487 functionMap[glslFunction->getName().c_str()] = function;
4488
4489 // Set the parameter id's
4490 for (int p = 0; p < (int)parameters.size(); ++p) {
4491 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4492 // give a name too
4493 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004494
4495 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004496 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004497 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004498 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004499 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004500 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004501 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004502 }
4503 }
4504}
4505
4506// Process all the initializers, while skipping the functions and link objects
4507void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4508{
4509 builder.setBuildPoint(shaderEntry->getLastBlock());
4510 for (int i = 0; i < (int)initializers.size(); ++i) {
4511 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004512 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4513 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004514
4515 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004516 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004517 initializer->traverse(this);
4518 }
4519 }
4520}
4521
4522// Process all the functions, while skipping initializers.
4523void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4524{
4525 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4526 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004527 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004528 node->traverse(this);
4529 }
4530}
4531
4532void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4533{
qining25262b32016-05-06 17:25:16 -04004534 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004535 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004536 currentFunction = functionMap[node->getName().c_str()];
4537 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004538 builder.setBuildPoint(functionBlock);
4539}
4540
John Kessenich8985fc92020-03-03 10:25:07 -07004541void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4542 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004543{
Rex Xufc618912015-09-09 16:42:49 +08004544 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004545
4546 glslang::TSampler sampler = {};
4547 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004548#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004549 bool f16ShadowCompare = false;
4550#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004551 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004552 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4553 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004554#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004555 f16ShadowCompare = sampler.shadow &&
4556 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004557#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004558 }
4559
John Kessenich140f3df2015-06-26 16:58:36 -06004560 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4561 builder.clearAccessChain();
4562 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004563
John Kessenicha28f7a72019-08-06 07:00:58 -06004564#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004565 // Special case l-value operands
4566 bool lvalue = false;
4567 switch (node.getOp()) {
4568 case glslang::EOpImageAtomicAdd:
4569 case glslang::EOpImageAtomicMin:
4570 case glslang::EOpImageAtomicMax:
4571 case glslang::EOpImageAtomicAnd:
4572 case glslang::EOpImageAtomicOr:
4573 case glslang::EOpImageAtomicXor:
4574 case glslang::EOpImageAtomicExchange:
4575 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004576 case glslang::EOpImageAtomicLoad:
4577 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004578 if (i == 0)
4579 lvalue = true;
4580 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004581 case glslang::EOpSparseImageLoad:
4582 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4583 lvalue = true;
4584 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004585 case glslang::EOpSparseTexture:
4586 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4587 lvalue = true;
4588 break;
4589 case glslang::EOpSparseTextureClamp:
4590 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4591 lvalue = true;
4592 break;
4593 case glslang::EOpSparseTextureLod:
4594 case glslang::EOpSparseTextureOffset:
4595 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4596 lvalue = true;
4597 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004598 case glslang::EOpSparseTextureFetch:
4599 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4600 lvalue = true;
4601 break;
4602 case glslang::EOpSparseTextureFetchOffset:
4603 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4604 lvalue = true;
4605 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004606 case glslang::EOpSparseTextureLodOffset:
4607 case glslang::EOpSparseTextureGrad:
4608 case glslang::EOpSparseTextureOffsetClamp:
4609 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4610 lvalue = true;
4611 break;
4612 case glslang::EOpSparseTextureGradOffset:
4613 case glslang::EOpSparseTextureGradClamp:
4614 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4615 lvalue = true;
4616 break;
4617 case glslang::EOpSparseTextureGradOffsetClamp:
4618 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4619 lvalue = true;
4620 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004621 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004622 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4623 lvalue = true;
4624 break;
4625 case glslang::EOpSparseTextureGatherOffset:
4626 case glslang::EOpSparseTextureGatherOffsets:
4627 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4628 lvalue = true;
4629 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004630 case glslang::EOpSparseTextureGatherLod:
4631 if (i == 3)
4632 lvalue = true;
4633 break;
4634 case glslang::EOpSparseTextureGatherLodOffset:
4635 case glslang::EOpSparseTextureGatherLodOffsets:
4636 if (i == 4)
4637 lvalue = true;
4638 break;
Rex Xu129799a2017-07-05 17:23:28 +08004639 case glslang::EOpSparseImageLoadLod:
4640 if (i == 3)
4641 lvalue = true;
4642 break;
Chao Chen3a137962018-09-19 11:41:27 -07004643 case glslang::EOpImageSampleFootprintNV:
4644 if (i == 4)
4645 lvalue = true;
4646 break;
4647 case glslang::EOpImageSampleFootprintClampNV:
4648 case glslang::EOpImageSampleFootprintLodNV:
4649 if (i == 5)
4650 lvalue = true;
4651 break;
4652 case glslang::EOpImageSampleFootprintGradNV:
4653 if (i == 6)
4654 lvalue = true;
4655 break;
4656 case glslang::EOpImageSampleFootprintGradClampNV:
4657 if (i == 7)
4658 lvalue = true;
4659 break;
Rex Xufc618912015-09-09 16:42:49 +08004660 default:
4661 break;
4662 }
4663
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004664 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004665 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004666 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4667 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4668 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004669#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004670 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004671 }
4672}
4673
John Kessenichfc51d282015-08-19 13:34:18 -06004674void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004675{
John Kessenichfc51d282015-08-19 13:34:18 -06004676 builder.clearAccessChain();
4677 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004678 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004679}
John Kessenich140f3df2015-06-26 16:58:36 -06004680
John Kessenichfc51d282015-08-19 13:34:18 -06004681spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4682{
John Kesseniche485c7a2017-05-31 18:50:53 -06004683 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004684 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004685
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004686 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004687
John Kessenichfc51d282015-08-19 13:34:18 -06004688 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004689
John Kessenichf43c7392019-03-31 10:51:57 -06004690 const glslang::TType &imageType = node->getAsAggregate()
4691 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4692 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004693 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004694#ifdef GLSLANG_WEB
4695 const bool f16ShadowCompare = false;
4696#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004697 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004698 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4699 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004700#endif
4701
John Kessenichf43c7392019-03-31 10:51:57 -06004702 const auto signExtensionMask = [&]() {
4703 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4704 if (sampler.type == glslang::EbtUint)
4705 return spv::ImageOperandsZeroExtendMask;
4706 else if (sampler.type == glslang::EbtInt)
4707 return spv::ImageOperandsSignExtendMask;
4708 }
4709 return spv::ImageOperandsMaskNone;
4710 };
4711
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004712 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4713
John Kessenichfc51d282015-08-19 13:34:18 -06004714 std::vector<spv::Id> arguments;
4715 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004716 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004717 else
4718 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004719 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004720
4721 spv::Builder::TextureParameters params = { };
4722 params.sampler = arguments[0];
4723
Rex Xu04db3f52015-09-16 11:44:02 +08004724 glslang::TCrackedTextureOp cracked;
4725 node->crackTexture(sampler, cracked);
4726
amhagan05506bb2017-06-13 16:53:02 -04004727 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004728
John Kessenichfc51d282015-08-19 13:34:18 -06004729 // Check for queries
4730 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004731 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4732 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004733 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004734
John Kessenichfc51d282015-08-19 13:34:18 -06004735 switch (node->getOp()) {
4736 case glslang::EOpImageQuerySize:
4737 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004738 if (arguments.size() > 1) {
4739 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004740 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004741 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004742 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004743#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004744 case glslang::EOpImageQuerySamples:
4745 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004746 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004747 case glslang::EOpTextureQueryLod:
4748 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004749 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004750 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004751 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004752 case glslang::EOpSparseTexelsResident:
4753 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004754#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004755 default:
4756 assert(0);
4757 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004758 }
John Kessenich140f3df2015-06-26 16:58:36 -06004759 }
4760
LoopDawg4425f242018-02-18 11:40:01 -07004761 int components = node->getType().getVectorSize();
4762
4763 if (node->getOp() == glslang::EOpTextureFetch) {
4764 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4765 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4766 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4767 // here around e.g. which ones return scalars or other types.
4768 components = 4;
4769 }
4770
4771 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4772
4773 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4774
Rex Xufc618912015-09-09 16:42:49 +08004775 // Check for image functions other than queries
4776 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004777 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004778 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004779 spv::IdImmediate image = { true, *(opIt++) };
4780 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004781
4782 // Handle subpass operations
4783 // TODO: GLSL should change to have the "MS" only on the type rather than the
4784 // built-in function.
4785 if (cracked.subpass) {
4786 // add on the (0,0) coordinate
4787 spv::Id zero = builder.makeIntConstant(0);
4788 std::vector<spv::Id> comps;
4789 comps.push_back(zero);
4790 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004791 spv::IdImmediate coord = { true,
4792 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4793 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004794 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4795 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004796 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004797 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4798 }
4799 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004800 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004801 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004802 spv::IdImmediate imageOperand = { true, *(opIt++) };
4803 operands.push_back(imageOperand);
4804 }
John Kessenich6c292d32016-02-15 20:58:50 -07004805 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004806 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4807 builder.setPrecision(result, precision);
4808 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004809 }
4810
John Kessenich149afc32018-08-14 13:31:43 -06004811 spv::IdImmediate coord = { true, *(opIt++) };
4812 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004813 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004814 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004815 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004816 mask = mask | spv::ImageOperandsSampleMask;
4817 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004818 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004819 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4820 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004821 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004822 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004823 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4824 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004825 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004826 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004827 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4828 operands.push_back(imageOperands);
4829 }
4830 if (mask & spv::ImageOperandsSampleMask) {
4831 spv::IdImmediate imageOperand = { true, *opIt++ };
4832 operands.push_back(imageOperand);
4833 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004834 if (mask & spv::ImageOperandsLodMask) {
4835 spv::IdImmediate imageOperand = { true, *opIt++ };
4836 operands.push_back(imageOperand);
4837 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004838 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004839 spv::IdImmediate imageOperand = { true,
4840 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004841 operands.push_back(imageOperand);
4842 }
4843
John Kessenich149afc32018-08-14 13:31:43 -06004844 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004845 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004846
John Kessenich149afc32018-08-14 13:31:43 -06004847 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004848 builder.setPrecision(result[0], precision);
4849
4850 // If needed, add a conversion constructor to the proper size.
4851 if (components != node->getType().getVectorSize())
4852 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4853
4854 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004855 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004856
Jeff Bolz36831c92018-09-05 10:11:41 -05004857 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004858 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004859 spv::IdImmediate texel = { true, *(opIt + 1) };
4860 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004861 } else {
4862 spv::IdImmediate texel = { true, *opIt };
4863 operands.push_back(texel);
4864 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004865
4866 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004867 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004868 mask = mask | spv::ImageOperandsSampleMask;
4869 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004870 if (cracked.lod) {
4871 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4872 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4873 mask = mask | spv::ImageOperandsLodMask;
4874 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004875 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4876 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004877 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004878 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004879 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4880 operands.push_back(imageOperands);
4881 }
4882 if (mask & spv::ImageOperandsSampleMask) {
4883 spv::IdImmediate imageOperand = { true, *opIt++ };
4884 operands.push_back(imageOperand);
4885 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004886 if (mask & spv::ImageOperandsLodMask) {
4887 spv::IdImmediate imageOperand = { true, *opIt++ };
4888 operands.push_back(imageOperand);
4889 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004890 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004891 spv::IdImmediate imageOperand = { true,
4892 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004893 operands.push_back(imageOperand);
4894 }
4895
John Kessenich56bab042015-09-16 10:54:31 -06004896 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004897 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004898 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004899 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004900 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4901 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004902 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004903 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004904 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4905
Jeff Bolz36831c92018-09-05 10:11:41 -05004906 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004907 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004908 mask = mask | spv::ImageOperandsSampleMask;
4909 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004910 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004911 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4912 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4913
Jeff Bolz36831c92018-09-05 10:11:41 -05004914 mask = mask | spv::ImageOperandsLodMask;
4915 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004916 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4917 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004918 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004919 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004920 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004921 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004922 }
4923 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004924 spv::IdImmediate imageOperand = { true, *opIt++ };
4925 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004926 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004927 if (mask & spv::ImageOperandsLodMask) {
4928 spv::IdImmediate imageOperand = { true, *opIt++ };
4929 operands.push_back(imageOperand);
4930 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004931 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07004932 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
4933 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004934 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004935 }
4936
4937 // Create the return type that was a special structure
4938 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004939 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004940 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4941 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4942
4943 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4944
4945 // Decode the return type
4946 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4947 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004948 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004949 // Process image atomic operations
4950
4951 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4952 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004953 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004954 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004955 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004956
Jeff Bolz36831c92018-09-05 10:11:41 -05004957 spv::Id resultTypeId;
4958 // imageAtomicStore has a void return type so base the pointer type on
4959 // the type of the value operand.
4960 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08004961 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05004962 } else {
4963 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4964 }
John Kessenich56bab042015-09-16 10:54:31 -06004965 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Jeff Bolz39ffdaf2020-03-09 10:48:12 -05004966 if (imageType.getQualifier().nonUniform) {
4967 builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
4968 }
Rex Xufc618912015-09-09 16:42:49 +08004969
4970 std::vector<spv::Id> operands;
4971 operands.push_back(pointer);
4972 for (; opIt != arguments.end(); ++opIt)
4973 operands.push_back(*opIt);
4974
John Kessenich8985fc92020-03-03 10:25:07 -07004975 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
4976 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004977 }
4978 }
4979
John Kessenicha28f7a72019-08-06 07:00:58 -06004980#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004981 // Check for fragment mask functions other than queries
4982 if (cracked.fragMask) {
4983 assert(sampler.ms);
4984
4985 auto opIt = arguments.begin();
4986 std::vector<spv::Id> operands;
4987
4988 // Extract the image if necessary
4989 if (builder.isSampledImage(params.sampler))
4990 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4991
4992 operands.push_back(params.sampler);
4993 ++opIt;
4994
4995 if (sampler.isSubpass()) {
4996 // add on the (0,0) coordinate
4997 spv::Id zero = builder.makeIntConstant(0);
4998 std::vector<spv::Id> comps;
4999 comps.push_back(zero);
5000 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07005001 operands.push_back(builder.makeCompositeConstant(
5002 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04005003 }
5004
5005 for (; opIt != arguments.end(); ++opIt)
5006 operands.push_back(*opIt);
5007
5008 spv::Op fragMaskOp = spv::OpNop;
5009 if (node->getOp() == glslang::EOpFragmentMaskFetch)
5010 fragMaskOp = spv::OpFragmentMaskFetchAMD;
5011 else if (node->getOp() == glslang::EOpFragmentFetch)
5012 fragMaskOp = spv::OpFragmentFetchAMD;
5013
5014 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
5015 builder.addCapability(spv::CapabilityFragmentMaskAMD);
5016 return builder.createOp(fragMaskOp, resultType(), operands);
5017 }
5018#endif
5019
Rex Xufc618912015-09-09 16:42:49 +08005020 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08005021 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07005022 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005023 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08005024
John Kessenichfc51d282015-08-19 13:34:18 -06005025 // check for bias argument
5026 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08005027 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005028 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08005029 if (cracked.gather)
5030 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08005031
5032 if (f16ShadowCompare)
5033 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005034 if (cracked.offset)
5035 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08005036 else if (cracked.offsets)
5037 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005038 if (cracked.grad)
5039 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08005040 if (cracked.lodClamp)
5041 ++nonBiasArgCount;
5042 if (sparse)
5043 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07005044 if (imageFootprint)
5045 //Following three extra arguments
5046 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5047 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06005048 if ((int)arguments.size() > nonBiasArgCount)
5049 bias = true;
5050 }
5051
John Kessenicha5c33d62016-06-02 23:45:21 -06005052 // See if the sampler param should really be just the SPV image part
5053 if (cracked.fetch) {
5054 // a fetch needs to have the image extracted first
5055 if (builder.isSampledImage(params.sampler))
5056 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
5057 }
5058
John Kessenicha28f7a72019-08-06 07:00:58 -06005059#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08005060 if (cracked.gather) {
5061 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
5062 if (bias || cracked.lod ||
5063 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
5064 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08005065 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08005066 }
5067 }
5068#endif
5069
John Kessenichfc51d282015-08-19 13:34:18 -06005070 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07005071
John Kessenichfc51d282015-08-19 13:34:18 -06005072 params.coords = arguments[1];
5073 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07005074 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07005075
5076 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08005077 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005078 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08005079 ++extraArgs;
5080 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07005081 params.Dref = arguments[2];
5082 ++extraArgs;
5083 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06005084 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06005085 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06005086 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06005087 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06005088 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005089 dRefComp = builder.getNumComponents(params.coords) - 1;
5090 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07005091 params.Dref = builder.createCompositeExtract(params.coords,
5092 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06005093 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005094
5095 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06005096 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005097 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06005098 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06005099 } else if (glslangIntermediate->getStage() != EShLangFragment &&
5100 !(glslangIntermediate->getStage() == EShLangCompute &&
5101 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07005102 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
5103 noImplicitLod = true;
5104 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005105
5106 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005107 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005108 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08005109 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005110 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005111
5112 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06005113 if (cracked.grad) {
5114 params.gradX = arguments[2 + extraArgs];
5115 params.gradY = arguments[3 + extraArgs];
5116 extraArgs += 2;
5117 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005118
5119 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07005120 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06005121 params.offset = arguments[2 + extraArgs];
5122 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005123 } else if (cracked.offsets) {
5124 params.offsets = arguments[2 + extraArgs];
5125 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005126 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005127
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005128#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005129 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005130 if (cracked.lodClamp) {
5131 params.lodClamp = arguments[2 + extraArgs];
5132 ++extraArgs;
5133 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005134 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005135 if (sparse) {
5136 params.texelOut = arguments[2 + extraArgs];
5137 ++extraArgs;
5138 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005139 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005140 if (cracked.gather && ! sampler.shadow) {
5141 // default component is 0, if missing, otherwise an argument
5142 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005143 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005144 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005145 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005146 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005147 }
Chao Chen3a137962018-09-19 11:41:27 -07005148 spv::Id resultStruct = spv::NoResult;
5149 if (imageFootprint) {
5150 //Following three extra arguments
5151 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5152 params.granularity = arguments[2 + extraArgs];
5153 params.coarse = arguments[3 + extraArgs];
5154 resultStruct = arguments[4 + extraArgs];
5155 extraArgs += 3;
5156 }
5157#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005158 // bias
5159 if (bias) {
5160 params.bias = arguments[2 + extraArgs];
5161 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005162 }
John Kessenichfc51d282015-08-19 13:34:18 -06005163
John Kessenicha28f7a72019-08-06 07:00:58 -06005164#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005165 if (imageFootprint) {
5166 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5167 builder.addCapability(spv::CapabilityImageFootprintNV);
5168
5169
5170 //resultStructType(OpenGL type) contains 5 elements:
5171 //struct gl_TextureFootprint2DNV {
5172 // uvec2 anchor;
5173 // uvec2 offset;
5174 // uvec2 mask;
5175 // uint lod;
5176 // uint granularity;
5177 //};
5178 //or
5179 //struct gl_TextureFootprint3DNV {
5180 // uvec3 anchor;
5181 // uvec3 offset;
5182 // uvec2 mask;
5183 // uint lod;
5184 // uint granularity;
5185 //};
5186 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5187 assert(builder.isStructType(resultStructType));
5188
5189 //resType (SPIR-V type) contains 6 elements:
5190 //Member 0 must be a Boolean type scalar(LOD),
5191 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5192 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5193 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5194 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5195 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5196 std::vector<spv::Id> members;
5197 members.push_back(resultType());
5198 for (int i = 0; i < 5; i++) {
5199 members.push_back(builder.getContainedTypeId(resultStructType, i));
5200 }
5201 spv::Id resType = builder.makeStructType(members, "ResType");
5202
5203 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005204 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5205 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005206
5207 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5208 for (int i = 0; i < 5; i++) {
5209 builder.clearAccessChain();
5210 builder.setAccessChainLValue(resultStruct);
5211
5212 //Accessing to a struct we created, no coherent flag is set
5213 spv::Builder::AccessChain::CoherentFlags flags;
5214 flags.clear();
5215
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005216 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005217 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
5218 i+1));
Chao Chen3a137962018-09-19 11:41:27 -07005219 }
5220 return builder.createCompositeExtract(res, resultType(), 0);
5221 }
5222#endif
5223
John Kessenich65336482016-06-16 14:06:26 -06005224 // projective component (might not to move)
5225 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5226 // are divided by the last component of P."
5227 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5228 // unused components will appear after all used components."
5229 if (cracked.proj) {
5230 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5231 int projTargetComp;
5232 switch (sampler.dim) {
5233 case glslang::Esd1D: projTargetComp = 1; break;
5234 case glslang::Esd2D: projTargetComp = 2; break;
5235 case glslang::EsdRect: projTargetComp = 2; break;
5236 default: projTargetComp = projSourceComp; break;
5237 }
5238 // copy the projective coordinate if we have to
5239 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005240 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005241 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005242 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005243 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005244 }
5245 }
5246
John Kessenichf8d1d742019-10-21 06:55:11 -06005247#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005248 // nonprivate
5249 if (imageType.getQualifier().nonprivate) {
5250 params.nonprivate = true;
5251 }
5252
5253 // volatile
5254 if (imageType.getQualifier().volatil) {
5255 params.volatil = true;
5256 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005257#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005258
St0fFa1184dd2018-04-09 21:08:14 +02005259 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005260 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5261 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005262 );
LoopDawg4425f242018-02-18 11:40:01 -07005263
5264 if (components != node->getType().getVectorSize())
5265 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5266
5267 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005268}
5269
5270spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5271{
5272 // Grab the function's pointer from the previously created function
5273 spv::Function* function = functionMap[node->getName().c_str()];
5274 if (! function)
5275 return 0;
5276
5277 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5278 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5279
5280 // See comments in makeFunctions() for details about the semantics for parameter passing.
5281 //
5282 // These imply we need a four step process:
5283 // 1. Evaluate the arguments
5284 // 2. Allocate and make copies of in, out, and inout arguments
5285 // 3. Make the call
5286 // 4. Copy back the results
5287
John Kessenichd3ed90b2018-05-04 11:43:03 -06005288 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005289 std::vector<spv::Builder::AccessChain> lValues;
5290 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005291 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005292 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005293 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005294 // build l-value
5295 builder.clearAccessChain();
5296 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005297 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005298 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005299 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005300 // save l-value
5301 lValues.push_back(builder.getAccessChain());
5302 } else {
5303 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005304 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005305 }
5306 }
5307
5308 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5309 // copy the original into that space.
5310 //
5311 // Also, build up the list of actual arguments to pass in for the call
5312 int lValueCount = 0;
5313 int rValueCount = 0;
5314 std::vector<spv::Id> spvArgs;
5315 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5316 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005317 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005318 builder.setAccessChain(lValues[lValueCount]);
5319 arg = builder.accessChainGetLValue();
5320 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005321 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005322 // need space to hold the copy
John Kessenich8985fc92020-03-03 10:25:07 -07005323 arg = builder.createVariable(spv::StorageClassFunction,
5324 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005325 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5326 // need to copy the input into output space
5327 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005328 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005329 builder.clearAccessChain();
5330 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005331 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005332 }
5333 ++lValueCount;
5334 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005335 // process r-value, which involves a copy for a type mismatch
5336 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5337 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5338 builder.clearAccessChain();
5339 builder.setAccessChainLValue(argCopy);
5340 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5341 arg = builder.createLoad(argCopy);
5342 } else
5343 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005344 ++rValueCount;
5345 }
5346 spvArgs.push_back(arg);
5347 }
5348
5349 // 3. Make the call.
5350 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005351 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005352
5353 // 4. Copy back out an "out" arguments.
5354 lValueCount = 0;
5355 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005356 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005357 ++lValueCount;
5358 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005359 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5360 spv::Id copy = builder.createLoad(spvArgs[a]);
5361 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005362 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005363 }
5364 ++lValueCount;
5365 }
5366 }
5367
5368 return result;
5369}
5370
5371// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005372spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005373 spv::Id typeId, spv::Id left, spv::Id right,
5374 glslang::TBasicType typeProxy, bool reduceComparison)
5375{
John Kessenich66011cb2018-03-06 16:12:04 -07005376 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5377 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005378 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005379
5380 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005381 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005382 bool comparison = false;
5383
5384 switch (op) {
5385 case glslang::EOpAdd:
5386 case glslang::EOpAddAssign:
5387 if (isFloat)
5388 binOp = spv::OpFAdd;
5389 else
5390 binOp = spv::OpIAdd;
5391 break;
5392 case glslang::EOpSub:
5393 case glslang::EOpSubAssign:
5394 if (isFloat)
5395 binOp = spv::OpFSub;
5396 else
5397 binOp = spv::OpISub;
5398 break;
5399 case glslang::EOpMul:
5400 case glslang::EOpMulAssign:
5401 if (isFloat)
5402 binOp = spv::OpFMul;
5403 else
5404 binOp = spv::OpIMul;
5405 break;
5406 case glslang::EOpVectorTimesScalar:
5407 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005408 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005409 if (builder.isVector(right))
5410 std::swap(left, right);
5411 assert(builder.isScalar(right));
5412 needMatchingVectors = false;
5413 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005414 } else if (isFloat)
5415 binOp = spv::OpFMul;
5416 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005417 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005418 break;
5419 case glslang::EOpVectorTimesMatrix:
5420 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005421 binOp = spv::OpVectorTimesMatrix;
5422 break;
5423 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005424 binOp = spv::OpMatrixTimesVector;
5425 break;
5426 case glslang::EOpMatrixTimesScalar:
5427 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005428 binOp = spv::OpMatrixTimesScalar;
5429 break;
5430 case glslang::EOpMatrixTimesMatrix:
5431 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005432 binOp = spv::OpMatrixTimesMatrix;
5433 break;
5434 case glslang::EOpOuterProduct:
5435 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005436 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005437 break;
5438
5439 case glslang::EOpDiv:
5440 case glslang::EOpDivAssign:
5441 if (isFloat)
5442 binOp = spv::OpFDiv;
5443 else if (isUnsigned)
5444 binOp = spv::OpUDiv;
5445 else
5446 binOp = spv::OpSDiv;
5447 break;
5448 case glslang::EOpMod:
5449 case glslang::EOpModAssign:
5450 if (isFloat)
5451 binOp = spv::OpFMod;
5452 else if (isUnsigned)
5453 binOp = spv::OpUMod;
5454 else
5455 binOp = spv::OpSMod;
5456 break;
5457 case glslang::EOpRightShift:
5458 case glslang::EOpRightShiftAssign:
5459 if (isUnsigned)
5460 binOp = spv::OpShiftRightLogical;
5461 else
5462 binOp = spv::OpShiftRightArithmetic;
5463 break;
5464 case glslang::EOpLeftShift:
5465 case glslang::EOpLeftShiftAssign:
5466 binOp = spv::OpShiftLeftLogical;
5467 break;
5468 case glslang::EOpAnd:
5469 case glslang::EOpAndAssign:
5470 binOp = spv::OpBitwiseAnd;
5471 break;
5472 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005473 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005474 binOp = spv::OpLogicalAnd;
5475 break;
5476 case glslang::EOpInclusiveOr:
5477 case glslang::EOpInclusiveOrAssign:
5478 binOp = spv::OpBitwiseOr;
5479 break;
5480 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005481 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005482 binOp = spv::OpLogicalOr;
5483 break;
5484 case glslang::EOpExclusiveOr:
5485 case glslang::EOpExclusiveOrAssign:
5486 binOp = spv::OpBitwiseXor;
5487 break;
5488 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005489 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005490 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005491 break;
5492
Ian Romanickb3bd4022019-01-21 08:57:25 -08005493 case glslang::EOpAbsDifference:
5494 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5495 break;
5496
5497 case glslang::EOpAddSaturate:
5498 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5499 break;
5500
5501 case glslang::EOpSubSaturate:
5502 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5503 break;
5504
5505 case glslang::EOpAverage:
5506 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5507 break;
5508
5509 case glslang::EOpAverageRounded:
5510 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5511 break;
5512
5513 case glslang::EOpMul32x16:
5514 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5515 break;
5516
John Kessenich140f3df2015-06-26 16:58:36 -06005517 case glslang::EOpLessThan:
5518 case glslang::EOpGreaterThan:
5519 case glslang::EOpLessThanEqual:
5520 case glslang::EOpGreaterThanEqual:
5521 case glslang::EOpEqual:
5522 case glslang::EOpNotEqual:
5523 case glslang::EOpVectorEqual:
5524 case glslang::EOpVectorNotEqual:
5525 comparison = true;
5526 break;
5527 default:
5528 break;
5529 }
5530
John Kessenich7c1aa102015-10-15 13:29:11 -06005531 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005532 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005533 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005534 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5535 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005536 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005537
5538 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005539 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005540 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005541
qining25262b32016-05-06 17:25:16 -04005542 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005543 decorations.addNoContraction(builder, result);
5544 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005545 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005546 }
5547
5548 if (! comparison)
5549 return 0;
5550
John Kessenich7c1aa102015-10-15 13:29:11 -06005551 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005552
John Kessenich4583b612016-08-07 19:14:22 -06005553 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005554 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5555 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005556 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005557 return result;
5558 }
John Kessenich140f3df2015-06-26 16:58:36 -06005559
5560 switch (op) {
5561 case glslang::EOpLessThan:
5562 if (isFloat)
5563 binOp = spv::OpFOrdLessThan;
5564 else if (isUnsigned)
5565 binOp = spv::OpULessThan;
5566 else
5567 binOp = spv::OpSLessThan;
5568 break;
5569 case glslang::EOpGreaterThan:
5570 if (isFloat)
5571 binOp = spv::OpFOrdGreaterThan;
5572 else if (isUnsigned)
5573 binOp = spv::OpUGreaterThan;
5574 else
5575 binOp = spv::OpSGreaterThan;
5576 break;
5577 case glslang::EOpLessThanEqual:
5578 if (isFloat)
5579 binOp = spv::OpFOrdLessThanEqual;
5580 else if (isUnsigned)
5581 binOp = spv::OpULessThanEqual;
5582 else
5583 binOp = spv::OpSLessThanEqual;
5584 break;
5585 case glslang::EOpGreaterThanEqual:
5586 if (isFloat)
5587 binOp = spv::OpFOrdGreaterThanEqual;
5588 else if (isUnsigned)
5589 binOp = spv::OpUGreaterThanEqual;
5590 else
5591 binOp = spv::OpSGreaterThanEqual;
5592 break;
5593 case glslang::EOpEqual:
5594 case glslang::EOpVectorEqual:
5595 if (isFloat)
5596 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005597 else if (isBool)
5598 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005599 else
5600 binOp = spv::OpIEqual;
5601 break;
5602 case glslang::EOpNotEqual:
5603 case glslang::EOpVectorNotEqual:
5604 if (isFloat)
5605 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005606 else if (isBool)
5607 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005608 else
5609 binOp = spv::OpINotEqual;
5610 break;
5611 default:
5612 break;
5613 }
5614
qining25262b32016-05-06 17:25:16 -04005615 if (binOp != spv::OpNop) {
5616 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005617 decorations.addNoContraction(builder, result);
5618 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005619 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005620 }
John Kessenich140f3df2015-06-26 16:58:36 -06005621
5622 return 0;
5623}
5624
John Kessenich04bb8a02015-12-12 12:28:14 -07005625//
5626// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5627// These can be any of:
5628//
5629// matrix * scalar
5630// scalar * matrix
5631// matrix * matrix linear algebraic
5632// matrix * vector
5633// vector * matrix
5634// matrix * matrix componentwise
5635// matrix op matrix op in {+, -, /}
5636// matrix op scalar op in {+, -, /}
5637// scalar op matrix op in {+, -, /}
5638//
John Kessenichead86222018-03-28 18:01:20 -06005639spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5640 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005641{
5642 bool firstClass = true;
5643
5644 // First, handle first-class matrix operations (* and matrix/scalar)
5645 switch (op) {
5646 case spv::OpFDiv:
5647 if (builder.isMatrix(left) && builder.isScalar(right)) {
5648 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005649 spv::Id resultType = builder.getTypeId(right);
5650 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005651 op = spv::OpMatrixTimesScalar;
5652 } else
5653 firstClass = false;
5654 break;
5655 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005656 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005657 std::swap(left, right);
5658 assert(builder.isScalar(right));
5659 break;
5660 case spv::OpVectorTimesMatrix:
5661 assert(builder.isVector(left));
5662 assert(builder.isMatrix(right));
5663 break;
5664 case spv::OpMatrixTimesVector:
5665 assert(builder.isMatrix(left));
5666 assert(builder.isVector(right));
5667 break;
5668 case spv::OpMatrixTimesMatrix:
5669 assert(builder.isMatrix(left));
5670 assert(builder.isMatrix(right));
5671 break;
5672 default:
5673 firstClass = false;
5674 break;
5675 }
5676
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005677 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5678 firstClass = true;
5679
qining25262b32016-05-06 17:25:16 -04005680 if (firstClass) {
5681 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005682 decorations.addNoContraction(builder, result);
5683 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005684 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005685 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005686
LoopDawg592860c2016-06-09 08:57:35 -06005687 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005688 // The result type of all of them is the same type as the (a) matrix operand.
5689 // The algorithm is to:
5690 // - break the matrix(es) into vectors
5691 // - smear any scalar to a vector
5692 // - do vector operations
5693 // - make a matrix out the vector results
5694 switch (op) {
5695 case spv::OpFAdd:
5696 case spv::OpFSub:
5697 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005698 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005699 case spv::OpFMul:
5700 {
5701 // one time set up...
5702 bool leftMat = builder.isMatrix(left);
5703 bool rightMat = builder.isMatrix(right);
5704 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5705 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5706 spv::Id scalarType = builder.getScalarTypeId(typeId);
5707 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5708 std::vector<spv::Id> results;
5709 spv::Id smearVec = spv::NoResult;
5710 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005711 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005712 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005713 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005714
5715 // do each vector op
5716 for (unsigned int c = 0; c < numCols; ++c) {
5717 std::vector<unsigned int> indexes;
5718 indexes.push_back(c);
5719 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5720 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005721 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005722 decorations.addNoContraction(builder, result);
5723 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005724 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005725 }
5726
5727 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005728 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005729 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005730 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005731 }
5732 default:
5733 assert(0);
5734 return spv::NoResult;
5735 }
5736}
5737
John Kessenichead86222018-03-28 18:01:20 -06005738spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005739 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005740{
5741 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005742 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005743 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005744 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5745 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005746
5747 switch (op) {
5748 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005749 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005750 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005751 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005752 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005753 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005754 unaryOp = spv::OpSNegate;
5755 break;
5756
5757 case glslang::EOpLogicalNot:
5758 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005759 unaryOp = spv::OpLogicalNot;
5760 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005761 case glslang::EOpBitwiseNot:
5762 unaryOp = spv::OpNot;
5763 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005764
John Kessenich140f3df2015-06-26 16:58:36 -06005765 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005766 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005767 break;
5768 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005769 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005770 break;
5771 case glslang::EOpTranspose:
5772 unaryOp = spv::OpTranspose;
5773 break;
5774
5775 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005776 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005777 break;
5778 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005779 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005780 break;
5781 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005782 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005783 break;
5784 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005785 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005786 break;
5787 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005788 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005789 break;
5790 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005791 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005792 break;
5793 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005794 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005795 break;
5796 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005797 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005798 break;
5799
5800 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005801 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005802 break;
5803 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005804 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005805 break;
5806 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005807 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005808 break;
5809 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005810 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005811 break;
5812 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005813 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005814 break;
5815 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005816 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005817 break;
5818
5819 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005820 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005821 break;
5822 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005823 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005824 break;
5825
5826 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005827 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005828 break;
5829 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005830 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005831 break;
5832 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005833 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005834 break;
5835 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005836 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005837 break;
5838 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005839 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005840 break;
5841 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005842 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005843 break;
5844
5845 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005846 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005847 break;
5848 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005849 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005850 break;
5851 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005852 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005853 break;
5854 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005855 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005856 break;
5857 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005858 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005859 break;
5860 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005861 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005862 break;
5863
5864 case glslang::EOpIsNan:
5865 unaryOp = spv::OpIsNan;
5866 break;
5867 case glslang::EOpIsInf:
5868 unaryOp = spv::OpIsInf;
5869 break;
LoopDawg592860c2016-06-09 08:57:35 -06005870 case glslang::EOpIsFinite:
5871 unaryOp = spv::OpIsFinite;
5872 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005873
Rex Xucbc426e2015-12-15 16:03:10 +08005874 case glslang::EOpFloatBitsToInt:
5875 case glslang::EOpFloatBitsToUint:
5876 case glslang::EOpIntBitsToFloat:
5877 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005878 case glslang::EOpDoubleBitsToInt64:
5879 case glslang::EOpDoubleBitsToUint64:
5880 case glslang::EOpInt64BitsToDouble:
5881 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005882 case glslang::EOpFloat16BitsToInt16:
5883 case glslang::EOpFloat16BitsToUint16:
5884 case glslang::EOpInt16BitsToFloat16:
5885 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005886 unaryOp = spv::OpBitcast;
5887 break;
5888
John Kessenich140f3df2015-06-26 16:58:36 -06005889 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005890 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005891 break;
5892 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005893 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005894 break;
5895 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005896 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005897 break;
5898 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005899 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005900 break;
5901 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005902 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005903 break;
5904 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005905 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005906 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005907#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005908 case glslang::EOpPackSnorm4x8:
5909 libCall = spv::GLSLstd450PackSnorm4x8;
5910 break;
5911 case glslang::EOpUnpackSnorm4x8:
5912 libCall = spv::GLSLstd450UnpackSnorm4x8;
5913 break;
5914 case glslang::EOpPackUnorm4x8:
5915 libCall = spv::GLSLstd450PackUnorm4x8;
5916 break;
5917 case glslang::EOpUnpackUnorm4x8:
5918 libCall = spv::GLSLstd450UnpackUnorm4x8;
5919 break;
5920 case glslang::EOpPackDouble2x32:
5921 libCall = spv::GLSLstd450PackDouble2x32;
5922 break;
5923 case glslang::EOpUnpackDouble2x32:
5924 libCall = spv::GLSLstd450UnpackDouble2x32;
5925 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005926#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005927
Rex Xu8ff43de2016-04-22 16:51:45 +08005928 case glslang::EOpPackInt2x32:
5929 case glslang::EOpUnpackInt2x32:
5930 case glslang::EOpPackUint2x32:
5931 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005932 case glslang::EOpPack16:
5933 case glslang::EOpPack32:
5934 case glslang::EOpPack64:
5935 case glslang::EOpUnpack32:
5936 case glslang::EOpUnpack16:
5937 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005938 case glslang::EOpPackInt2x16:
5939 case glslang::EOpUnpackInt2x16:
5940 case glslang::EOpPackUint2x16:
5941 case glslang::EOpUnpackUint2x16:
5942 case glslang::EOpPackInt4x16:
5943 case glslang::EOpUnpackInt4x16:
5944 case glslang::EOpPackUint4x16:
5945 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005946 case glslang::EOpPackFloat2x16:
5947 case glslang::EOpUnpackFloat2x16:
5948 unaryOp = spv::OpBitcast;
5949 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005950
John Kessenich140f3df2015-06-26 16:58:36 -06005951 case glslang::EOpDPdx:
5952 unaryOp = spv::OpDPdx;
5953 break;
5954 case glslang::EOpDPdy:
5955 unaryOp = spv::OpDPdy;
5956 break;
5957 case glslang::EOpFwidth:
5958 unaryOp = spv::OpFwidth;
5959 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005960
John Kessenich140f3df2015-06-26 16:58:36 -06005961 case glslang::EOpAny:
5962 unaryOp = spv::OpAny;
5963 break;
5964 case glslang::EOpAll:
5965 unaryOp = spv::OpAll;
5966 break;
5967
5968 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005969 if (isFloat)
5970 libCall = spv::GLSLstd450FAbs;
5971 else
5972 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005973 break;
5974 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005975 if (isFloat)
5976 libCall = spv::GLSLstd450FSign;
5977 else
5978 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005979 break;
5980
John Kessenicha28f7a72019-08-06 07:00:58 -06005981#ifndef GLSLANG_WEB
5982 case glslang::EOpDPdxFine:
5983 unaryOp = spv::OpDPdxFine;
5984 break;
5985 case glslang::EOpDPdyFine:
5986 unaryOp = spv::OpDPdyFine;
5987 break;
5988 case glslang::EOpFwidthFine:
5989 unaryOp = spv::OpFwidthFine;
5990 break;
5991 case glslang::EOpDPdxCoarse:
5992 unaryOp = spv::OpDPdxCoarse;
5993 break;
5994 case glslang::EOpDPdyCoarse:
5995 unaryOp = spv::OpDPdyCoarse;
5996 break;
5997 case glslang::EOpFwidthCoarse:
5998 unaryOp = spv::OpFwidthCoarse;
5999 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04006000 case glslang::EOpRayQueryProceed:
6001 unaryOp = spv::OpRayQueryProceedKHR;
6002 break;
6003 case glslang::EOpRayQueryGetRayTMin:
6004 unaryOp = spv::OpRayQueryGetRayTMinKHR;
6005 break;
6006 case glslang::EOpRayQueryGetRayFlags:
6007 unaryOp = spv::OpRayQueryGetRayFlagsKHR;
6008 break;
6009 case glslang::EOpRayQueryGetWorldRayOrigin:
6010 unaryOp = spv::OpRayQueryGetWorldRayOriginKHR;
6011 break;
6012 case glslang::EOpRayQueryGetWorldRayDirection:
6013 unaryOp = spv::OpRayQueryGetWorldRayDirectionKHR;
6014 break;
6015 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
6016 unaryOp = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
6017 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006018 case glslang::EOpInterpolateAtCentroid:
6019 if (typeProxy == glslang::EbtFloat16)
6020 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6021 libCall = spv::GLSLstd450InterpolateAtCentroid;
6022 break;
John Kessenichfc51d282015-08-19 13:34:18 -06006023 case glslang::EOpAtomicCounterIncrement:
6024 case glslang::EOpAtomicCounterDecrement:
6025 case glslang::EOpAtomicCounter:
6026 {
6027 // Handle all of the atomics in one place, in createAtomicOperation()
6028 std::vector<spv::Id> operands;
6029 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006030 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06006031 }
6032
John Kessenichfc51d282015-08-19 13:34:18 -06006033 case glslang::EOpBitFieldReverse:
6034 unaryOp = spv::OpBitReverse;
6035 break;
6036 case glslang::EOpBitCount:
6037 unaryOp = spv::OpBitCount;
6038 break;
6039 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006040 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006041 break;
6042 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006043 if (isUnsigned)
6044 libCall = spv::GLSLstd450FindUMsb;
6045 else
6046 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006047 break;
6048
Ian Romanickb3bd4022019-01-21 08:57:25 -08006049 case glslang::EOpCountLeadingZeros:
6050 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6051 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6052 unaryOp = spv::OpUCountLeadingZerosINTEL;
6053 break;
6054
6055 case glslang::EOpCountTrailingZeros:
6056 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6057 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6058 unaryOp = spv::OpUCountTrailingZerosINTEL;
6059 break;
6060
Rex Xu574ab042016-04-14 16:53:07 +08006061 case glslang::EOpBallot:
6062 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006063 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006064 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08006065 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08006066 case glslang::EOpMinInvocations:
6067 case glslang::EOpMaxInvocations:
6068 case glslang::EOpAddInvocations:
6069 case glslang::EOpMinInvocationsNonUniform:
6070 case glslang::EOpMaxInvocationsNonUniform:
6071 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006072 case glslang::EOpMinInvocationsInclusiveScan:
6073 case glslang::EOpMaxInvocationsInclusiveScan:
6074 case glslang::EOpAddInvocationsInclusiveScan:
6075 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6076 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6077 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6078 case glslang::EOpMinInvocationsExclusiveScan:
6079 case glslang::EOpMaxInvocationsExclusiveScan:
6080 case glslang::EOpAddInvocationsExclusiveScan:
6081 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6082 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6083 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08006084 {
6085 std::vector<spv::Id> operands;
6086 operands.push_back(operand);
6087 return createInvocationsOperation(op, typeId, operands, typeProxy);
6088 }
John Kessenich66011cb2018-03-06 16:12:04 -07006089 case glslang::EOpSubgroupAll:
6090 case glslang::EOpSubgroupAny:
6091 case glslang::EOpSubgroupAllEqual:
6092 case glslang::EOpSubgroupBroadcastFirst:
6093 case glslang::EOpSubgroupBallot:
6094 case glslang::EOpSubgroupInverseBallot:
6095 case glslang::EOpSubgroupBallotBitCount:
6096 case glslang::EOpSubgroupBallotInclusiveBitCount:
6097 case glslang::EOpSubgroupBallotExclusiveBitCount:
6098 case glslang::EOpSubgroupBallotFindLSB:
6099 case glslang::EOpSubgroupBallotFindMSB:
6100 case glslang::EOpSubgroupAdd:
6101 case glslang::EOpSubgroupMul:
6102 case glslang::EOpSubgroupMin:
6103 case glslang::EOpSubgroupMax:
6104 case glslang::EOpSubgroupAnd:
6105 case glslang::EOpSubgroupOr:
6106 case glslang::EOpSubgroupXor:
6107 case glslang::EOpSubgroupInclusiveAdd:
6108 case glslang::EOpSubgroupInclusiveMul:
6109 case glslang::EOpSubgroupInclusiveMin:
6110 case glslang::EOpSubgroupInclusiveMax:
6111 case glslang::EOpSubgroupInclusiveAnd:
6112 case glslang::EOpSubgroupInclusiveOr:
6113 case glslang::EOpSubgroupInclusiveXor:
6114 case glslang::EOpSubgroupExclusiveAdd:
6115 case glslang::EOpSubgroupExclusiveMul:
6116 case glslang::EOpSubgroupExclusiveMin:
6117 case glslang::EOpSubgroupExclusiveMax:
6118 case glslang::EOpSubgroupExclusiveAnd:
6119 case glslang::EOpSubgroupExclusiveOr:
6120 case glslang::EOpSubgroupExclusiveXor:
6121 case glslang::EOpSubgroupQuadSwapHorizontal:
6122 case glslang::EOpSubgroupQuadSwapVertical:
6123 case glslang::EOpSubgroupQuadSwapDiagonal: {
6124 std::vector<spv::Id> operands;
6125 operands.push_back(operand);
6126 return createSubgroupOperation(op, typeId, operands, typeProxy);
6127 }
Rex Xu9d93a232016-05-05 12:30:44 +08006128 case glslang::EOpMbcnt:
6129 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6130 libCall = spv::MbcntAMD;
6131 break;
6132
6133 case glslang::EOpCubeFaceIndex:
6134 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6135 libCall = spv::CubeFaceIndexAMD;
6136 break;
6137
6138 case glslang::EOpCubeFaceCoord:
6139 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6140 libCall = spv::CubeFaceCoordAMD;
6141 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006142 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006143 unaryOp = spv::OpGroupNonUniformPartitionNV;
6144 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006145 case glslang::EOpConstructReference:
6146 unaryOp = spv::OpBitcast;
6147 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006148#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006149
6150 case glslang::EOpCopyObject:
6151 unaryOp = spv::OpCopyObject;
6152 break;
6153
John Kessenich140f3df2015-06-26 16:58:36 -06006154 default:
6155 return 0;
6156 }
6157
6158 spv::Id id;
6159 if (libCall >= 0) {
6160 std::vector<spv::Id> args;
6161 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006162 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006163 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006164 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006165 }
John Kessenich140f3df2015-06-26 16:58:36 -06006166
John Kessenichb9197c82019-08-11 07:41:45 -06006167 decorations.addNoContraction(builder, id);
6168 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006169 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006170}
6171
John Kessenich7a53f762016-01-20 11:19:27 -07006172// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006173spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6174 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006175{
6176 // Handle unary operations vector by vector.
6177 // The result type is the same type as the original type.
6178 // The algorithm is to:
6179 // - break the matrix into vectors
6180 // - apply the operation to each vector
6181 // - make a matrix out the vector results
6182
6183 // get the types sorted out
6184 int numCols = builder.getNumColumns(operand);
6185 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006186 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6187 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006188 std::vector<spv::Id> results;
6189
6190 // do each vector op
6191 for (int c = 0; c < numCols; ++c) {
6192 std::vector<unsigned int> indexes;
6193 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006194 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6195 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006196 decorations.addNoContraction(builder, destVec);
6197 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006198 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006199 }
6200
6201 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006202 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006203 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006204 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006205}
6206
John Kessenichad7645f2018-06-04 19:11:25 -06006207// For converting integers where both the bitwidth and the signedness could
6208// change, but only do the width change here. The caller is still responsible
6209// for the signedness conversion.
6210spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006211{
John Kessenichad7645f2018-06-04 19:11:25 -06006212 // Get the result type width, based on the type to convert to.
6213 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006214 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006215 case glslang::EOpConvInt16ToUint8:
6216 case glslang::EOpConvIntToUint8:
6217 case glslang::EOpConvInt64ToUint8:
6218 case glslang::EOpConvUint16ToInt8:
6219 case glslang::EOpConvUintToInt8:
6220 case glslang::EOpConvUint64ToInt8:
6221 width = 8;
6222 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006223 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006224 case glslang::EOpConvIntToUint16:
6225 case glslang::EOpConvInt64ToUint16:
6226 case glslang::EOpConvUint8ToInt16:
6227 case glslang::EOpConvUintToInt16:
6228 case glslang::EOpConvUint64ToInt16:
6229 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006230 break;
6231 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006232 case glslang::EOpConvInt16ToUint:
6233 case glslang::EOpConvInt64ToUint:
6234 case glslang::EOpConvUint8ToInt:
6235 case glslang::EOpConvUint16ToInt:
6236 case glslang::EOpConvUint64ToInt:
6237 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006238 break;
6239 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006240 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006241 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006242 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006243 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006244 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006245 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006246 break;
6247
6248 default:
6249 assert(false && "Default missing");
6250 break;
6251 }
6252
John Kessenichad7645f2018-06-04 19:11:25 -06006253 // Get the conversion operation and result type,
6254 // based on the target width, but the source type.
6255 spv::Id type = spv::NoType;
6256 spv::Op convOp = spv::OpNop;
6257 switch(op) {
6258 case glslang::EOpConvInt8ToUint16:
6259 case glslang::EOpConvInt8ToUint:
6260 case glslang::EOpConvInt8ToUint64:
6261 case glslang::EOpConvInt16ToUint8:
6262 case glslang::EOpConvInt16ToUint:
6263 case glslang::EOpConvInt16ToUint64:
6264 case glslang::EOpConvIntToUint8:
6265 case glslang::EOpConvIntToUint16:
6266 case glslang::EOpConvIntToUint64:
6267 case glslang::EOpConvInt64ToUint8:
6268 case glslang::EOpConvInt64ToUint16:
6269 case glslang::EOpConvInt64ToUint:
6270 convOp = spv::OpSConvert;
6271 type = builder.makeIntType(width);
6272 break;
6273 default:
6274 convOp = spv::OpUConvert;
6275 type = builder.makeUintType(width);
6276 break;
6277 }
6278
John Kessenich66011cb2018-03-06 16:12:04 -07006279 if (vectorSize > 0)
6280 type = builder.makeVectorType(type, vectorSize);
6281
John Kessenichad7645f2018-06-04 19:11:25 -06006282 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006283}
6284
John Kessenichead86222018-03-28 18:01:20 -06006285spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6286 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006287{
6288 spv::Op convOp = spv::OpNop;
6289 spv::Id zero = 0;
6290 spv::Id one = 0;
6291
6292 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6293
6294 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006295 case glslang::EOpConvIntToBool:
6296 case glslang::EOpConvUintToBool:
6297 zero = builder.makeUintConstant(0);
6298 zero = makeSmearedConstant(zero, vectorSize);
6299 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006300 case glslang::EOpConvFloatToBool:
6301 zero = builder.makeFloatConstant(0.0F);
6302 zero = makeSmearedConstant(zero, vectorSize);
6303 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006304 case glslang::EOpConvBoolToFloat:
6305 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006306 zero = builder.makeFloatConstant(0.0F);
6307 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006308 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006309
John Kessenich140f3df2015-06-26 16:58:36 -06006310 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006311 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006312#ifndef GLSLANG_WEB
6313 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006314 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006315 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006316 } else
6317#endif
6318 {
6319 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006320 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006321 }
Rex Xucabbb782017-03-24 13:41:14 +08006322
John Kessenich140f3df2015-06-26 16:58:36 -06006323 convOp = spv::OpSelect;
6324 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006325
John Kessenich140f3df2015-06-26 16:58:36 -06006326 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006327 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006328#ifndef GLSLANG_WEB
6329 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006330 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006331 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006332 } else
6333#endif
6334 {
6335 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006336 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006337 }
Rex Xucabbb782017-03-24 13:41:14 +08006338
John Kessenich140f3df2015-06-26 16:58:36 -06006339 convOp = spv::OpSelect;
6340 break;
6341
John Kessenich66011cb2018-03-06 16:12:04 -07006342 case glslang::EOpConvInt8ToFloat16:
6343 case glslang::EOpConvInt8ToFloat:
6344 case glslang::EOpConvInt8ToDouble:
6345 case glslang::EOpConvInt16ToFloat16:
6346 case glslang::EOpConvInt16ToFloat:
6347 case glslang::EOpConvInt16ToDouble:
6348 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006349 case glslang::EOpConvIntToFloat:
6350 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006351 case glslang::EOpConvInt64ToFloat:
6352 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006353 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006354 convOp = spv::OpConvertSToF;
6355 break;
6356
John Kessenich66011cb2018-03-06 16:12:04 -07006357 case glslang::EOpConvUint8ToFloat16:
6358 case glslang::EOpConvUint8ToFloat:
6359 case glslang::EOpConvUint8ToDouble:
6360 case glslang::EOpConvUint16ToFloat16:
6361 case glslang::EOpConvUint16ToFloat:
6362 case glslang::EOpConvUint16ToDouble:
6363 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006364 case glslang::EOpConvUintToFloat:
6365 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006366 case glslang::EOpConvUint64ToFloat:
6367 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006368 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006369 convOp = spv::OpConvertUToF;
6370 break;
6371
John Kessenich66011cb2018-03-06 16:12:04 -07006372 case glslang::EOpConvFloat16ToInt8:
6373 case glslang::EOpConvFloatToInt8:
6374 case glslang::EOpConvDoubleToInt8:
6375 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006376 case glslang::EOpConvFloatToInt16:
6377 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006378 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006379 case glslang::EOpConvFloatToInt:
6380 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006381 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006382 case glslang::EOpConvFloatToInt64:
6383 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006384 convOp = spv::OpConvertFToS;
6385 break;
6386
John Kessenich66011cb2018-03-06 16:12:04 -07006387 case glslang::EOpConvUint8ToInt8:
6388 case glslang::EOpConvInt8ToUint8:
6389 case glslang::EOpConvUint16ToInt16:
6390 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006391 case glslang::EOpConvUintToInt:
6392 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006393 case glslang::EOpConvUint64ToInt64:
6394 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006395 if (builder.isInSpecConstCodeGenMode()) {
6396 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006397#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006398 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6399 zero = builder.makeUint8Constant(0);
6400 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006401 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006402 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6403 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006404 } else
6405#endif
6406 {
Rex Xucabbb782017-03-24 13:41:14 +08006407 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006408 }
qining189b2032016-04-12 23:16:20 -04006409 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006410 // Use OpIAdd, instead of OpBitcast to do the conversion when
6411 // generating for OpSpecConstantOp instruction.
6412 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6413 }
6414 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006415 convOp = spv::OpBitcast;
6416 break;
6417
John Kessenich66011cb2018-03-06 16:12:04 -07006418 case glslang::EOpConvFloat16ToUint8:
6419 case glslang::EOpConvFloatToUint8:
6420 case glslang::EOpConvDoubleToUint8:
6421 case glslang::EOpConvFloat16ToUint16:
6422 case glslang::EOpConvFloatToUint16:
6423 case glslang::EOpConvDoubleToUint16:
6424 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006425 case glslang::EOpConvFloatToUint:
6426 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006427 case glslang::EOpConvFloatToUint64:
6428 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006429 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006430 convOp = spv::OpConvertFToU;
6431 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006432
John Kessenich39697cd2019-08-08 10:35:51 -06006433#ifndef GLSLANG_WEB
6434 case glslang::EOpConvInt8ToBool:
6435 case glslang::EOpConvUint8ToBool:
6436 zero = builder.makeUint8Constant(0);
6437 zero = makeSmearedConstant(zero, vectorSize);
6438 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6439 case glslang::EOpConvInt16ToBool:
6440 case glslang::EOpConvUint16ToBool:
6441 zero = builder.makeUint16Constant(0);
6442 zero = makeSmearedConstant(zero, vectorSize);
6443 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6444 case glslang::EOpConvInt64ToBool:
6445 case glslang::EOpConvUint64ToBool:
6446 zero = builder.makeUint64Constant(0);
6447 zero = makeSmearedConstant(zero, vectorSize);
6448 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6449 case glslang::EOpConvDoubleToBool:
6450 zero = builder.makeDoubleConstant(0.0);
6451 zero = makeSmearedConstant(zero, vectorSize);
6452 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6453 case glslang::EOpConvFloat16ToBool:
6454 zero = builder.makeFloat16Constant(0.0F);
6455 zero = makeSmearedConstant(zero, vectorSize);
6456 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6457 case glslang::EOpConvBoolToDouble:
6458 convOp = spv::OpSelect;
6459 zero = builder.makeDoubleConstant(0.0);
6460 one = builder.makeDoubleConstant(1.0);
6461 break;
6462 case glslang::EOpConvBoolToFloat16:
6463 convOp = spv::OpSelect;
6464 zero = builder.makeFloat16Constant(0.0F);
6465 one = builder.makeFloat16Constant(1.0F);
6466 break;
6467 case glslang::EOpConvBoolToInt8:
6468 zero = builder.makeInt8Constant(0);
6469 one = builder.makeInt8Constant(1);
6470 convOp = spv::OpSelect;
6471 break;
6472 case glslang::EOpConvBoolToUint8:
6473 zero = builder.makeUint8Constant(0);
6474 one = builder.makeUint8Constant(1);
6475 convOp = spv::OpSelect;
6476 break;
6477 case glslang::EOpConvBoolToInt16:
6478 zero = builder.makeInt16Constant(0);
6479 one = builder.makeInt16Constant(1);
6480 convOp = spv::OpSelect;
6481 break;
6482 case glslang::EOpConvBoolToUint16:
6483 zero = builder.makeUint16Constant(0);
6484 one = builder.makeUint16Constant(1);
6485 convOp = spv::OpSelect;
6486 break;
6487 case glslang::EOpConvDoubleToFloat:
6488 case glslang::EOpConvFloatToDouble:
6489 case glslang::EOpConvDoubleToFloat16:
6490 case glslang::EOpConvFloat16ToDouble:
6491 case glslang::EOpConvFloatToFloat16:
6492 case glslang::EOpConvFloat16ToFloat:
6493 convOp = spv::OpFConvert;
6494 if (builder.isMatrixType(destType))
6495 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6496 break;
6497
John Kessenich66011cb2018-03-06 16:12:04 -07006498 case glslang::EOpConvInt8ToInt16:
6499 case glslang::EOpConvInt8ToInt:
6500 case glslang::EOpConvInt8ToInt64:
6501 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006502 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006503 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006504 case glslang::EOpConvIntToInt8:
6505 case glslang::EOpConvIntToInt16:
6506 case glslang::EOpConvIntToInt64:
6507 case glslang::EOpConvInt64ToInt8:
6508 case glslang::EOpConvInt64ToInt16:
6509 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006510 convOp = spv::OpSConvert;
6511 break;
6512
John Kessenich66011cb2018-03-06 16:12:04 -07006513 case glslang::EOpConvUint8ToUint16:
6514 case glslang::EOpConvUint8ToUint:
6515 case glslang::EOpConvUint8ToUint64:
6516 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006517 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006518 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006519 case glslang::EOpConvUintToUint8:
6520 case glslang::EOpConvUintToUint16:
6521 case glslang::EOpConvUintToUint64:
6522 case glslang::EOpConvUint64ToUint8:
6523 case glslang::EOpConvUint64ToUint16:
6524 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006525 convOp = spv::OpUConvert;
6526 break;
6527
John Kessenich66011cb2018-03-06 16:12:04 -07006528 case glslang::EOpConvInt8ToUint16:
6529 case glslang::EOpConvInt8ToUint:
6530 case glslang::EOpConvInt8ToUint64:
6531 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006532 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006533 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006534 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006535 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006536 case glslang::EOpConvIntToUint64:
6537 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006538 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006539 case glslang::EOpConvInt64ToUint:
6540 case glslang::EOpConvUint8ToInt16:
6541 case glslang::EOpConvUint8ToInt:
6542 case glslang::EOpConvUint8ToInt64:
6543 case glslang::EOpConvUint16ToInt8:
6544 case glslang::EOpConvUint16ToInt:
6545 case glslang::EOpConvUint16ToInt64:
6546 case glslang::EOpConvUintToInt8:
6547 case glslang::EOpConvUintToInt16:
6548 case glslang::EOpConvUintToInt64:
6549 case glslang::EOpConvUint64ToInt8:
6550 case glslang::EOpConvUint64ToInt16:
6551 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006552 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006553 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006554
6555 if (builder.isInSpecConstCodeGenMode()) {
6556 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006557 switch(op) {
6558 case glslang::EOpConvInt16ToUint8:
6559 case glslang::EOpConvIntToUint8:
6560 case glslang::EOpConvInt64ToUint8:
6561 case glslang::EOpConvUint16ToInt8:
6562 case glslang::EOpConvUintToInt8:
6563 case glslang::EOpConvUint64ToInt8:
6564 zero = builder.makeUint8Constant(0);
6565 break;
6566 case glslang::EOpConvInt8ToUint16:
6567 case glslang::EOpConvIntToUint16:
6568 case glslang::EOpConvInt64ToUint16:
6569 case glslang::EOpConvUint8ToInt16:
6570 case glslang::EOpConvUintToInt16:
6571 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006572 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006573 break;
6574 case glslang::EOpConvInt8ToUint:
6575 case glslang::EOpConvInt16ToUint:
6576 case glslang::EOpConvInt64ToUint:
6577 case glslang::EOpConvUint8ToInt:
6578 case glslang::EOpConvUint16ToInt:
6579 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006580 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006581 break;
6582 case glslang::EOpConvInt8ToUint64:
6583 case glslang::EOpConvInt16ToUint64:
6584 case glslang::EOpConvIntToUint64:
6585 case glslang::EOpConvUint8ToInt64:
6586 case glslang::EOpConvUint16ToInt64:
6587 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006588 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006589 break;
6590 default:
6591 assert(false && "Default missing");
6592 break;
6593 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006594 zero = makeSmearedConstant(zero, vectorSize);
6595 // Use OpIAdd, instead of OpBitcast to do the conversion when
6596 // generating for OpSpecConstantOp instruction.
6597 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6598 }
6599 // For normal run-time conversion instruction, use OpBitcast.
6600 convOp = spv::OpBitcast;
6601 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006602 case glslang::EOpConvUint64ToPtr:
6603 convOp = spv::OpConvertUToPtr;
6604 break;
6605 case glslang::EOpConvPtrToUint64:
6606 convOp = spv::OpConvertPtrToU;
6607 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006608 case glslang::EOpConvPtrToUvec2:
6609 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006610 if (builder.isVector(operand))
6611 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6612 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006613 convOp = spv::OpBitcast;
6614 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006615#endif
6616
John Kessenich140f3df2015-06-26 16:58:36 -06006617 default:
6618 break;
6619 }
6620
6621 spv::Id result = 0;
6622 if (convOp == spv::OpNop)
6623 return result;
6624
6625 if (convOp == spv::OpSelect) {
6626 zero = makeSmearedConstant(zero, vectorSize);
6627 one = makeSmearedConstant(one, vectorSize);
6628 result = builder.createTriOp(convOp, destType, operand, one, zero);
6629 } else
6630 result = builder.createUnaryOp(convOp, destType, operand);
6631
John Kessenichead86222018-03-28 18:01:20 -06006632 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006633 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006634 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006635}
6636
6637spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6638{
6639 if (vectorSize == 0)
6640 return constant;
6641
6642 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6643 std::vector<spv::Id> components;
6644 for (int c = 0; c < vectorSize; ++c)
6645 components.push_back(constant);
6646 return builder.makeCompositeConstant(vectorTypeId, components);
6647}
6648
John Kessenich426394d2015-07-23 10:22:48 -06006649// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006650spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6651 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6652 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006653{
6654 spv::Op opCode = spv::OpNop;
6655
6656 switch (op) {
6657 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006658 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006659 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006660 opCode = spv::OpAtomicIAdd;
6661 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006662 case glslang::EOpAtomicCounterSubtract:
6663 opCode = spv::OpAtomicISub;
6664 break;
John Kessenich426394d2015-07-23 10:22:48 -06006665 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006666 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006667 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006668 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6669 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006670 break;
6671 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006672 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006673 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006674 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6675 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006676 break;
6677 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006678 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006679 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006680 opCode = spv::OpAtomicAnd;
6681 break;
6682 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006683 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006684 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006685 opCode = spv::OpAtomicOr;
6686 break;
6687 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006688 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006689 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006690 opCode = spv::OpAtomicXor;
6691 break;
6692 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006693 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006694 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006695 opCode = spv::OpAtomicExchange;
6696 break;
6697 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006698 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006699 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006700 opCode = spv::OpAtomicCompareExchange;
6701 break;
6702 case glslang::EOpAtomicCounterIncrement:
6703 opCode = spv::OpAtomicIIncrement;
6704 break;
6705 case glslang::EOpAtomicCounterDecrement:
6706 opCode = spv::OpAtomicIDecrement;
6707 break;
6708 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006709 case glslang::EOpImageAtomicLoad:
6710 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006711 opCode = spv::OpAtomicLoad;
6712 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006713 case glslang::EOpAtomicStore:
6714 case glslang::EOpImageAtomicStore:
6715 opCode = spv::OpAtomicStore;
6716 break;
John Kessenich426394d2015-07-23 10:22:48 -06006717 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006718 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006719 break;
6720 }
6721
Rex Xue8fe8b02017-09-26 15:42:56 +08006722 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6723 builder.addCapability(spv::CapabilityInt64Atomics);
6724
John Kessenich426394d2015-07-23 10:22:48 -06006725 // Sort out the operands
6726 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006727 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006728 // - compare-exchange swaps the value and comparator
6729 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006730 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006731 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6732 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6733 spv::Id scopeId;
6734 if (glslangIntermediate->usingVulkanMemoryModel()) {
6735 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6736 } else {
6737 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6738 }
6739 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006740 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6741 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006742 spv::MemorySemanticsVolatileMask :
6743 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006744 spv::Id semanticsId2 = semanticsId;
6745
6746 pointerId = operands[0];
6747 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6748 // no additional operands
6749 } else if (opCode == spv::OpAtomicCompareExchange) {
6750 compareId = operands[1];
6751 valueId = operands[2];
6752 if (operands.size() > 3) {
6753 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006754 semanticsId = builder.makeUintConstant(
6755 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6756 semanticsId2 = builder.makeUintConstant(
6757 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006758 }
6759 } else if (opCode == spv::OpAtomicLoad) {
6760 if (operands.size() > 1) {
6761 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006762 semanticsId = builder.makeUintConstant(
6763 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006764 }
6765 } else {
6766 // atomic store or RMW
6767 valueId = operands[1];
6768 if (operands.size() > 2) {
6769 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006770 semanticsId = builder.makeUintConstant
6771 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006772 }
Rex Xu04db3f52015-09-16 11:44:02 +08006773 }
John Kessenich426394d2015-07-23 10:22:48 -06006774
Jeff Bolz36831c92018-09-05 10:11:41 -05006775 // Check for capabilities
6776 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006777 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6778 spv::MemorySemanticsMakeVisibleKHRMask |
6779 spv::MemorySemanticsOutputMemoryKHRMask |
6780 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006781 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6782 }
John Kessenich426394d2015-07-23 10:22:48 -06006783
Jeff Bolz36831c92018-09-05 10:11:41 -05006784 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6785 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6786 }
John Kessenich48d6e792017-10-06 21:21:48 -06006787
Jeff Bolz36831c92018-09-05 10:11:41 -05006788 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6789 spvAtomicOperands.push_back(pointerId);
6790 spvAtomicOperands.push_back(scopeId);
6791 spvAtomicOperands.push_back(semanticsId);
6792 if (opCode == spv::OpAtomicCompareExchange) {
6793 spvAtomicOperands.push_back(semanticsId2);
6794 spvAtomicOperands.push_back(valueId);
6795 spvAtomicOperands.push_back(compareId);
6796 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6797 spvAtomicOperands.push_back(valueId);
6798 }
John Kessenich48d6e792017-10-06 21:21:48 -06006799
Jeff Bolz36831c92018-09-05 10:11:41 -05006800 if (opCode == spv::OpAtomicStore) {
6801 builder.createNoResultOp(opCode, spvAtomicOperands);
6802 return 0;
6803 } else {
6804 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6805
6806 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6807 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6808 if (op == glslang::EOpAtomicCounterDecrement)
6809 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6810
6811 return resultId;
6812 }
John Kessenich426394d2015-07-23 10:22:48 -06006813}
6814
John Kessenich91cef522016-05-05 16:45:40 -06006815// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07006816spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
6817 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006818{
John Kessenich66011cb2018-03-06 16:12:04 -07006819 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6820 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006821
Rex Xu51596642016-09-21 18:56:12 +08006822 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006823 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006824 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6825
chaocf200da82016-12-20 12:44:35 -08006826 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6827 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006828 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6829 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006830 } else if (op == glslang::EOpAnyInvocation ||
6831 op == glslang::EOpAllInvocations ||
6832 op == glslang::EOpAllInvocationsEqual) {
6833 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6834 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006835 } else {
6836 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006837 if (op == glslang::EOpMinInvocationsNonUniform ||
6838 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006839 op == glslang::EOpAddInvocationsNonUniform ||
6840 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6841 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6842 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6843 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6844 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6845 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006846 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006847
Rex Xu430ef402016-10-14 17:22:23 +08006848 switch (op) {
6849 case glslang::EOpMinInvocations:
6850 case glslang::EOpMaxInvocations:
6851 case glslang::EOpAddInvocations:
6852 case glslang::EOpMinInvocationsNonUniform:
6853 case glslang::EOpMaxInvocationsNonUniform:
6854 case glslang::EOpAddInvocationsNonUniform:
6855 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006856 break;
6857 case glslang::EOpMinInvocationsInclusiveScan:
6858 case glslang::EOpMaxInvocationsInclusiveScan:
6859 case glslang::EOpAddInvocationsInclusiveScan:
6860 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6861 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6862 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6863 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006864 break;
6865 case glslang::EOpMinInvocationsExclusiveScan:
6866 case glslang::EOpMaxInvocationsExclusiveScan:
6867 case glslang::EOpAddInvocationsExclusiveScan:
6868 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6869 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6870 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6871 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006872 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006873 default:
6874 break;
Rex Xu430ef402016-10-14 17:22:23 +08006875 }
John Kessenich149afc32018-08-14 13:31:43 -06006876 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6877 spvGroupOperands.push_back(scope);
6878 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006879 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006880 spvGroupOperands.push_back(groupOp);
6881 }
Rex Xu51596642016-09-21 18:56:12 +08006882 }
6883
John Kessenich149afc32018-08-14 13:31:43 -06006884 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6885 spv::IdImmediate op = { true, *opIt };
6886 spvGroupOperands.push_back(op);
6887 }
John Kessenich91cef522016-05-05 16:45:40 -06006888
6889 switch (op) {
6890 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006891 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006892 break;
John Kessenich91cef522016-05-05 16:45:40 -06006893 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006894 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006895 break;
John Kessenich91cef522016-05-05 16:45:40 -06006896 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006897 opCode = spv::OpSubgroupAllEqualKHR;
6898 break;
Rex Xu51596642016-09-21 18:56:12 +08006899 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006900 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006901 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006902 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006903 break;
6904 case glslang::EOpReadFirstInvocation:
6905 opCode = spv::OpSubgroupFirstInvocationKHR;
6906 break;
6907 case glslang::EOpBallot:
6908 {
6909 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6910 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6911 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6912 //
6913 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6914 //
6915 spv::Id uintType = builder.makeUintType(32);
6916 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6917 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6918
6919 std::vector<spv::Id> components;
6920 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6921 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6922
6923 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6924 return builder.createUnaryOp(spv::OpBitcast, typeId,
6925 builder.createCompositeConstruct(uvec2Type, components));
6926 }
6927
Rex Xu9d93a232016-05-05 12:30:44 +08006928 case glslang::EOpMinInvocations:
6929 case glslang::EOpMaxInvocations:
6930 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006931 case glslang::EOpMinInvocationsInclusiveScan:
6932 case glslang::EOpMaxInvocationsInclusiveScan:
6933 case glslang::EOpAddInvocationsInclusiveScan:
6934 case glslang::EOpMinInvocationsExclusiveScan:
6935 case glslang::EOpMaxInvocationsExclusiveScan:
6936 case glslang::EOpAddInvocationsExclusiveScan:
6937 if (op == glslang::EOpMinInvocations ||
6938 op == glslang::EOpMinInvocationsInclusiveScan ||
6939 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006940 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006941 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006942 else {
6943 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006944 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006945 else
Rex Xu51596642016-09-21 18:56:12 +08006946 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006947 }
Rex Xu430ef402016-10-14 17:22:23 +08006948 } else if (op == glslang::EOpMaxInvocations ||
6949 op == glslang::EOpMaxInvocationsInclusiveScan ||
6950 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006951 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006952 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006953 else {
6954 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006955 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006956 else
Rex Xu51596642016-09-21 18:56:12 +08006957 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006958 }
6959 } else {
6960 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006961 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006962 else
Rex Xu51596642016-09-21 18:56:12 +08006963 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006964 }
6965
Rex Xu2bbbe062016-08-23 15:41:05 +08006966 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006967 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006968
6969 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006970 case glslang::EOpMinInvocationsNonUniform:
6971 case glslang::EOpMaxInvocationsNonUniform:
6972 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006973 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6974 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6975 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6976 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6977 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6978 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6979 if (op == glslang::EOpMinInvocationsNonUniform ||
6980 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6981 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006982 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006983 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006984 else {
6985 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006986 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006987 else
Rex Xu51596642016-09-21 18:56:12 +08006988 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006989 }
6990 }
Rex Xu430ef402016-10-14 17:22:23 +08006991 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6992 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6993 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006994 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006995 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006996 else {
6997 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006998 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006999 else
Rex Xu51596642016-09-21 18:56:12 +08007000 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007001 }
7002 }
7003 else {
7004 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007005 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007006 else
Rex Xu51596642016-09-21 18:56:12 +08007007 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007008 }
7009
Rex Xu2bbbe062016-08-23 15:41:05 +08007010 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007011 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007012
7013 break;
John Kessenich91cef522016-05-05 16:45:40 -06007014 default:
7015 logger->missingFunctionality("invocation operation");
7016 return spv::NoResult;
7017 }
Rex Xu51596642016-09-21 18:56:12 +08007018
7019 assert(opCode != spv::OpNop);
7020 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06007021}
7022
Rex Xu2bbbe062016-08-23 15:41:05 +08007023// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06007024spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
7025 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08007026{
7027 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
7028 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08007029 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08007030 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07007031 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
7032 op == spv::OpGroupSMinNonUniformAMD ||
7033 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
7034 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08007035 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
7036
7037 // Handle group invocation operations scalar by scalar.
7038 // The result type is the same type as the original type.
7039 // The algorithm is to:
7040 // - break the vector into scalars
7041 // - apply the operation to each scalar
7042 // - make a vector out the scalar results
7043
7044 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08007045 int numComponents = builder.getNumComponents(operands[0]);
7046 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08007047 std::vector<spv::Id> results;
7048
7049 // do each scalar op
7050 for (int comp = 0; comp < numComponents; ++comp) {
7051 std::vector<unsigned int> indexes;
7052 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06007053 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
7054 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08007055 if (op == spv::OpSubgroupReadInvocationKHR) {
7056 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007057 spv::IdImmediate operand = { true, operands[1] };
7058 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08007059 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06007060 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7061 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08007062 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007063 spv::IdImmediate operand = { true, operands[1] };
7064 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08007065 } else {
John Kessenich149afc32018-08-14 13:31:43 -06007066 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7067 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06007068 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007069 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08007070 spvGroupOperands.push_back(scalar);
7071 }
Rex Xu2bbbe062016-08-23 15:41:05 +08007072
Rex Xub7072052016-09-26 15:53:40 +08007073 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08007074 }
7075
7076 // put the pieces together
7077 return builder.createCompositeConstruct(typeId, results);
7078}
Rex Xu2bbbe062016-08-23 15:41:05 +08007079
John Kessenich66011cb2018-03-06 16:12:04 -07007080// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06007081spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
7082 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07007083{
7084 // Add the required capabilities.
7085 switch (op) {
7086 case glslang::EOpSubgroupElect:
7087 builder.addCapability(spv::CapabilityGroupNonUniform);
7088 break;
7089 case glslang::EOpSubgroupAll:
7090 case glslang::EOpSubgroupAny:
7091 case glslang::EOpSubgroupAllEqual:
7092 builder.addCapability(spv::CapabilityGroupNonUniform);
7093 builder.addCapability(spv::CapabilityGroupNonUniformVote);
7094 break;
7095 case glslang::EOpSubgroupBroadcast:
7096 case glslang::EOpSubgroupBroadcastFirst:
7097 case glslang::EOpSubgroupBallot:
7098 case glslang::EOpSubgroupInverseBallot:
7099 case glslang::EOpSubgroupBallotBitExtract:
7100 case glslang::EOpSubgroupBallotBitCount:
7101 case glslang::EOpSubgroupBallotInclusiveBitCount:
7102 case glslang::EOpSubgroupBallotExclusiveBitCount:
7103 case glslang::EOpSubgroupBallotFindLSB:
7104 case glslang::EOpSubgroupBallotFindMSB:
7105 builder.addCapability(spv::CapabilityGroupNonUniform);
7106 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
7107 break;
7108 case glslang::EOpSubgroupShuffle:
7109 case glslang::EOpSubgroupShuffleXor:
7110 builder.addCapability(spv::CapabilityGroupNonUniform);
7111 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
7112 break;
7113 case glslang::EOpSubgroupShuffleUp:
7114 case glslang::EOpSubgroupShuffleDown:
7115 builder.addCapability(spv::CapabilityGroupNonUniform);
7116 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
7117 break;
7118 case glslang::EOpSubgroupAdd:
7119 case glslang::EOpSubgroupMul:
7120 case glslang::EOpSubgroupMin:
7121 case glslang::EOpSubgroupMax:
7122 case glslang::EOpSubgroupAnd:
7123 case glslang::EOpSubgroupOr:
7124 case glslang::EOpSubgroupXor:
7125 case glslang::EOpSubgroupInclusiveAdd:
7126 case glslang::EOpSubgroupInclusiveMul:
7127 case glslang::EOpSubgroupInclusiveMin:
7128 case glslang::EOpSubgroupInclusiveMax:
7129 case glslang::EOpSubgroupInclusiveAnd:
7130 case glslang::EOpSubgroupInclusiveOr:
7131 case glslang::EOpSubgroupInclusiveXor:
7132 case glslang::EOpSubgroupExclusiveAdd:
7133 case glslang::EOpSubgroupExclusiveMul:
7134 case glslang::EOpSubgroupExclusiveMin:
7135 case glslang::EOpSubgroupExclusiveMax:
7136 case glslang::EOpSubgroupExclusiveAnd:
7137 case glslang::EOpSubgroupExclusiveOr:
7138 case glslang::EOpSubgroupExclusiveXor:
7139 builder.addCapability(spv::CapabilityGroupNonUniform);
7140 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
7141 break;
7142 case glslang::EOpSubgroupClusteredAdd:
7143 case glslang::EOpSubgroupClusteredMul:
7144 case glslang::EOpSubgroupClusteredMin:
7145 case glslang::EOpSubgroupClusteredMax:
7146 case glslang::EOpSubgroupClusteredAnd:
7147 case glslang::EOpSubgroupClusteredOr:
7148 case glslang::EOpSubgroupClusteredXor:
7149 builder.addCapability(spv::CapabilityGroupNonUniform);
7150 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7151 break;
7152 case glslang::EOpSubgroupQuadBroadcast:
7153 case glslang::EOpSubgroupQuadSwapHorizontal:
7154 case glslang::EOpSubgroupQuadSwapVertical:
7155 case glslang::EOpSubgroupQuadSwapDiagonal:
7156 builder.addCapability(spv::CapabilityGroupNonUniform);
7157 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7158 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007159 case glslang::EOpSubgroupPartitionedAdd:
7160 case glslang::EOpSubgroupPartitionedMul:
7161 case glslang::EOpSubgroupPartitionedMin:
7162 case glslang::EOpSubgroupPartitionedMax:
7163 case glslang::EOpSubgroupPartitionedAnd:
7164 case glslang::EOpSubgroupPartitionedOr:
7165 case glslang::EOpSubgroupPartitionedXor:
7166 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7167 case glslang::EOpSubgroupPartitionedInclusiveMul:
7168 case glslang::EOpSubgroupPartitionedInclusiveMin:
7169 case glslang::EOpSubgroupPartitionedInclusiveMax:
7170 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7171 case glslang::EOpSubgroupPartitionedInclusiveOr:
7172 case glslang::EOpSubgroupPartitionedInclusiveXor:
7173 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7174 case glslang::EOpSubgroupPartitionedExclusiveMul:
7175 case glslang::EOpSubgroupPartitionedExclusiveMin:
7176 case glslang::EOpSubgroupPartitionedExclusiveMax:
7177 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7178 case glslang::EOpSubgroupPartitionedExclusiveOr:
7179 case glslang::EOpSubgroupPartitionedExclusiveXor:
7180 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7181 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7182 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007183 default: assert(0 && "Unhandled subgroup operation!");
7184 }
7185
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007186
7187 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7188 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007189 const bool isBool = typeProxy == glslang::EbtBool;
7190
7191 spv::Op opCode = spv::OpNop;
7192
7193 // Figure out which opcode to use.
7194 switch (op) {
7195 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7196 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7197 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7198 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7199 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7200 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7201 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7202 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7203 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7204 case glslang::EOpSubgroupBallotBitCount:
7205 case glslang::EOpSubgroupBallotInclusiveBitCount:
7206 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7207 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7208 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7209 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7210 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7211 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7212 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7213 case glslang::EOpSubgroupAdd:
7214 case glslang::EOpSubgroupInclusiveAdd:
7215 case glslang::EOpSubgroupExclusiveAdd:
7216 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007217 case glslang::EOpSubgroupPartitionedAdd:
7218 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7219 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007220 if (isFloat) {
7221 opCode = spv::OpGroupNonUniformFAdd;
7222 } else {
7223 opCode = spv::OpGroupNonUniformIAdd;
7224 }
7225 break;
7226 case glslang::EOpSubgroupMul:
7227 case glslang::EOpSubgroupInclusiveMul:
7228 case glslang::EOpSubgroupExclusiveMul:
7229 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007230 case glslang::EOpSubgroupPartitionedMul:
7231 case glslang::EOpSubgroupPartitionedInclusiveMul:
7232 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007233 if (isFloat) {
7234 opCode = spv::OpGroupNonUniformFMul;
7235 } else {
7236 opCode = spv::OpGroupNonUniformIMul;
7237 }
7238 break;
7239 case glslang::EOpSubgroupMin:
7240 case glslang::EOpSubgroupInclusiveMin:
7241 case glslang::EOpSubgroupExclusiveMin:
7242 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007243 case glslang::EOpSubgroupPartitionedMin:
7244 case glslang::EOpSubgroupPartitionedInclusiveMin:
7245 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007246 if (isFloat) {
7247 opCode = spv::OpGroupNonUniformFMin;
7248 } else if (isUnsigned) {
7249 opCode = spv::OpGroupNonUniformUMin;
7250 } else {
7251 opCode = spv::OpGroupNonUniformSMin;
7252 }
7253 break;
7254 case glslang::EOpSubgroupMax:
7255 case glslang::EOpSubgroupInclusiveMax:
7256 case glslang::EOpSubgroupExclusiveMax:
7257 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007258 case glslang::EOpSubgroupPartitionedMax:
7259 case glslang::EOpSubgroupPartitionedInclusiveMax:
7260 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007261 if (isFloat) {
7262 opCode = spv::OpGroupNonUniformFMax;
7263 } else if (isUnsigned) {
7264 opCode = spv::OpGroupNonUniformUMax;
7265 } else {
7266 opCode = spv::OpGroupNonUniformSMax;
7267 }
7268 break;
7269 case glslang::EOpSubgroupAnd:
7270 case glslang::EOpSubgroupInclusiveAnd:
7271 case glslang::EOpSubgroupExclusiveAnd:
7272 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007273 case glslang::EOpSubgroupPartitionedAnd:
7274 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7275 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007276 if (isBool) {
7277 opCode = spv::OpGroupNonUniformLogicalAnd;
7278 } else {
7279 opCode = spv::OpGroupNonUniformBitwiseAnd;
7280 }
7281 break;
7282 case glslang::EOpSubgroupOr:
7283 case glslang::EOpSubgroupInclusiveOr:
7284 case glslang::EOpSubgroupExclusiveOr:
7285 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007286 case glslang::EOpSubgroupPartitionedOr:
7287 case glslang::EOpSubgroupPartitionedInclusiveOr:
7288 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007289 if (isBool) {
7290 opCode = spv::OpGroupNonUniformLogicalOr;
7291 } else {
7292 opCode = spv::OpGroupNonUniformBitwiseOr;
7293 }
7294 break;
7295 case glslang::EOpSubgroupXor:
7296 case glslang::EOpSubgroupInclusiveXor:
7297 case glslang::EOpSubgroupExclusiveXor:
7298 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007299 case glslang::EOpSubgroupPartitionedXor:
7300 case glslang::EOpSubgroupPartitionedInclusiveXor:
7301 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007302 if (isBool) {
7303 opCode = spv::OpGroupNonUniformLogicalXor;
7304 } else {
7305 opCode = spv::OpGroupNonUniformBitwiseXor;
7306 }
7307 break;
7308 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7309 case glslang::EOpSubgroupQuadSwapHorizontal:
7310 case glslang::EOpSubgroupQuadSwapVertical:
7311 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7312 default: assert(0 && "Unhandled subgroup operation!");
7313 }
7314
John Kessenich149afc32018-08-14 13:31:43 -06007315 // get the right Group Operation
7316 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007317 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007318 default:
7319 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007320 case glslang::EOpSubgroupBallotBitCount:
7321 case glslang::EOpSubgroupAdd:
7322 case glslang::EOpSubgroupMul:
7323 case glslang::EOpSubgroupMin:
7324 case glslang::EOpSubgroupMax:
7325 case glslang::EOpSubgroupAnd:
7326 case glslang::EOpSubgroupOr:
7327 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007328 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007329 break;
7330 case glslang::EOpSubgroupBallotInclusiveBitCount:
7331 case glslang::EOpSubgroupInclusiveAdd:
7332 case glslang::EOpSubgroupInclusiveMul:
7333 case glslang::EOpSubgroupInclusiveMin:
7334 case glslang::EOpSubgroupInclusiveMax:
7335 case glslang::EOpSubgroupInclusiveAnd:
7336 case glslang::EOpSubgroupInclusiveOr:
7337 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007338 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007339 break;
7340 case glslang::EOpSubgroupBallotExclusiveBitCount:
7341 case glslang::EOpSubgroupExclusiveAdd:
7342 case glslang::EOpSubgroupExclusiveMul:
7343 case glslang::EOpSubgroupExclusiveMin:
7344 case glslang::EOpSubgroupExclusiveMax:
7345 case glslang::EOpSubgroupExclusiveAnd:
7346 case glslang::EOpSubgroupExclusiveOr:
7347 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007348 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007349 break;
7350 case glslang::EOpSubgroupClusteredAdd:
7351 case glslang::EOpSubgroupClusteredMul:
7352 case glslang::EOpSubgroupClusteredMin:
7353 case glslang::EOpSubgroupClusteredMax:
7354 case glslang::EOpSubgroupClusteredAnd:
7355 case glslang::EOpSubgroupClusteredOr:
7356 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007357 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007358 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007359 case glslang::EOpSubgroupPartitionedAdd:
7360 case glslang::EOpSubgroupPartitionedMul:
7361 case glslang::EOpSubgroupPartitionedMin:
7362 case glslang::EOpSubgroupPartitionedMax:
7363 case glslang::EOpSubgroupPartitionedAnd:
7364 case glslang::EOpSubgroupPartitionedOr:
7365 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007366 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007367 break;
7368 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7369 case glslang::EOpSubgroupPartitionedInclusiveMul:
7370 case glslang::EOpSubgroupPartitionedInclusiveMin:
7371 case glslang::EOpSubgroupPartitionedInclusiveMax:
7372 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7373 case glslang::EOpSubgroupPartitionedInclusiveOr:
7374 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007375 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007376 break;
7377 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7378 case glslang::EOpSubgroupPartitionedExclusiveMul:
7379 case glslang::EOpSubgroupPartitionedExclusiveMin:
7380 case glslang::EOpSubgroupPartitionedExclusiveMax:
7381 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7382 case glslang::EOpSubgroupPartitionedExclusiveOr:
7383 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007384 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007385 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007386 }
7387
John Kessenich149afc32018-08-14 13:31:43 -06007388 // build the instruction
7389 std::vector<spv::IdImmediate> spvGroupOperands;
7390
7391 // Every operation begins with the Execution Scope operand.
7392 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7393 spvGroupOperands.push_back(executionScope);
7394
7395 // Next, for all operations that use a Group Operation, push that as an operand.
7396 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007397 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007398 spvGroupOperands.push_back(groupOperand);
7399 }
7400
John Kessenich66011cb2018-03-06 16:12:04 -07007401 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007402 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7403 spv::IdImmediate operand = { true, *opIt };
7404 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007405 }
7406
7407 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007408 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007409 switch (op) {
7410 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007411 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7412 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7413 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7414 }
7415 if (directionId != spv::NoResult) {
7416 spv::IdImmediate direction = { true, directionId };
7417 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007418 }
7419
7420 return builder.createOp(opCode, typeId, spvGroupOperands);
7421}
7422
John Kessenich8985fc92020-03-03 10:25:07 -07007423spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7424 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007425{
John Kessenich66011cb2018-03-06 16:12:04 -07007426 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7427 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007428
John Kessenich140f3df2015-06-26 16:58:36 -06007429 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007430 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007431 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007432 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007433 spv::Id typeId0 = 0;
7434 if (consumedOperands > 0)
7435 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007436 spv::Id typeId1 = 0;
7437 if (consumedOperands > 1)
7438 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007439 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007440
7441 switch (op) {
7442 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007443 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007444 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007445 else if (isUnsigned)
7446 libCall = spv::GLSLstd450UMin;
7447 else
7448 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007449 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007450 break;
7451 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007452 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007453 break;
7454 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007455 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007456 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007457 else if (isUnsigned)
7458 libCall = spv::GLSLstd450UMax;
7459 else
7460 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007461 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007462 break;
7463 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007464 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007465 break;
7466 case glslang::EOpDot:
7467 opCode = spv::OpDot;
7468 break;
7469 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007470 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007471 break;
7472
7473 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007474 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007475 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007476 else if (isUnsigned)
7477 libCall = spv::GLSLstd450UClamp;
7478 else
7479 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007480 builder.promoteScalar(precision, operands.front(), operands[1]);
7481 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007482 break;
7483 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007484 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7485 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007486 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007487 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007488 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007489 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007490 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007491 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007492 break;
7493 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007494 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007495 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007496 break;
7497 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007498 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007499 builder.promoteScalar(precision, operands[0], operands[2]);
7500 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007501 break;
7502
7503 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007504 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007505 break;
7506 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007507 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007508 break;
7509 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007510 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007511 break;
7512 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007513 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007514 break;
7515 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007516 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007517 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007518 case glslang::EOpBarrier:
7519 {
7520 // This is for the extended controlBarrier function, with four operands.
7521 // The unextended barrier() goes through createNoArgOperation.
7522 assert(operands.size() == 4);
7523 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7524 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7525 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007526 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7527 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007528 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7529 spv::MemorySemanticsMakeVisibleKHRMask |
7530 spv::MemorySemanticsOutputMemoryKHRMask |
7531 spv::MemorySemanticsVolatileMask)) {
7532 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7533 }
John Kessenich8985fc92020-03-03 10:25:07 -07007534 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7535 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007536 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7537 }
7538 return 0;
7539 }
7540 break;
7541 case glslang::EOpMemoryBarrier:
7542 {
7543 // This is for the extended memoryBarrier function, with three operands.
7544 // The unextended memoryBarrier() goes through createNoArgOperation.
7545 assert(operands.size() == 3);
7546 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7547 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7548 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7549 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7550 spv::MemorySemanticsMakeVisibleKHRMask |
7551 spv::MemorySemanticsOutputMemoryKHRMask |
7552 spv::MemorySemanticsVolatileMask)) {
7553 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7554 }
7555 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7556 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7557 }
7558 return 0;
7559 }
7560 break;
7561
John Kessenicha28f7a72019-08-06 07:00:58 -06007562#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007563 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007564 if (typeProxy == glslang::EbtFloat16)
7565 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007566 libCall = spv::GLSLstd450InterpolateAtSample;
7567 break;
7568 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007569 if (typeProxy == glslang::EbtFloat16)
7570 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007571 libCall = spv::GLSLstd450InterpolateAtOffset;
7572 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007573 case glslang::EOpAddCarry:
7574 opCode = spv::OpIAddCarry;
7575 typeId = builder.makeStructResultType(typeId0, typeId0);
7576 consumedOperands = 2;
7577 break;
7578 case glslang::EOpSubBorrow:
7579 opCode = spv::OpISubBorrow;
7580 typeId = builder.makeStructResultType(typeId0, typeId0);
7581 consumedOperands = 2;
7582 break;
7583 case glslang::EOpUMulExtended:
7584 opCode = spv::OpUMulExtended;
7585 typeId = builder.makeStructResultType(typeId0, typeId0);
7586 consumedOperands = 2;
7587 break;
7588 case glslang::EOpIMulExtended:
7589 opCode = spv::OpSMulExtended;
7590 typeId = builder.makeStructResultType(typeId0, typeId0);
7591 consumedOperands = 2;
7592 break;
7593 case glslang::EOpBitfieldExtract:
7594 if (isUnsigned)
7595 opCode = spv::OpBitFieldUExtract;
7596 else
7597 opCode = spv::OpBitFieldSExtract;
7598 break;
7599 case glslang::EOpBitfieldInsert:
7600 opCode = spv::OpBitFieldInsert;
7601 break;
7602
7603 case glslang::EOpFma:
7604 libCall = spv::GLSLstd450Fma;
7605 break;
7606 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007607 {
7608 libCall = spv::GLSLstd450FrexpStruct;
7609 assert(builder.isPointerType(typeId1));
7610 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007611 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007612 if (width == 16)
7613 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7614 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007615 if (builder.getNumComponents(operands[0]) == 1)
7616 frexpIntType = builder.makeIntegerType(width, true);
7617 else
John Kessenich8985fc92020-03-03 10:25:07 -07007618 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7619 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007620 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7621 consumedOperands = 1;
7622 }
John Kessenich55e7d112015-11-15 21:33:39 -07007623 break;
7624 case glslang::EOpLdexp:
7625 libCall = spv::GLSLstd450Ldexp;
7626 break;
7627
Rex Xu574ab042016-04-14 16:53:07 +08007628 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007629 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007630
John Kessenich66011cb2018-03-06 16:12:04 -07007631 case glslang::EOpSubgroupBroadcast:
7632 case glslang::EOpSubgroupBallotBitExtract:
7633 case glslang::EOpSubgroupShuffle:
7634 case glslang::EOpSubgroupShuffleXor:
7635 case glslang::EOpSubgroupShuffleUp:
7636 case glslang::EOpSubgroupShuffleDown:
7637 case glslang::EOpSubgroupClusteredAdd:
7638 case glslang::EOpSubgroupClusteredMul:
7639 case glslang::EOpSubgroupClusteredMin:
7640 case glslang::EOpSubgroupClusteredMax:
7641 case glslang::EOpSubgroupClusteredAnd:
7642 case glslang::EOpSubgroupClusteredOr:
7643 case glslang::EOpSubgroupClusteredXor:
7644 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007645 case glslang::EOpSubgroupPartitionedAdd:
7646 case glslang::EOpSubgroupPartitionedMul:
7647 case glslang::EOpSubgroupPartitionedMin:
7648 case glslang::EOpSubgroupPartitionedMax:
7649 case glslang::EOpSubgroupPartitionedAnd:
7650 case glslang::EOpSubgroupPartitionedOr:
7651 case glslang::EOpSubgroupPartitionedXor:
7652 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7653 case glslang::EOpSubgroupPartitionedInclusiveMul:
7654 case glslang::EOpSubgroupPartitionedInclusiveMin:
7655 case glslang::EOpSubgroupPartitionedInclusiveMax:
7656 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7657 case glslang::EOpSubgroupPartitionedInclusiveOr:
7658 case glslang::EOpSubgroupPartitionedInclusiveXor:
7659 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7660 case glslang::EOpSubgroupPartitionedExclusiveMul:
7661 case glslang::EOpSubgroupPartitionedExclusiveMin:
7662 case glslang::EOpSubgroupPartitionedExclusiveMax:
7663 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7664 case glslang::EOpSubgroupPartitionedExclusiveOr:
7665 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007666 return createSubgroupOperation(op, typeId, operands, typeProxy);
7667
Rex Xu9d93a232016-05-05 12:30:44 +08007668 case glslang::EOpSwizzleInvocations:
7669 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7670 libCall = spv::SwizzleInvocationsAMD;
7671 break;
7672 case glslang::EOpSwizzleInvocationsMasked:
7673 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7674 libCall = spv::SwizzleInvocationsMaskedAMD;
7675 break;
7676 case glslang::EOpWriteInvocation:
7677 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7678 libCall = spv::WriteInvocationAMD;
7679 break;
7680
7681 case glslang::EOpMin3:
7682 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7683 if (isFloat)
7684 libCall = spv::FMin3AMD;
7685 else {
7686 if (isUnsigned)
7687 libCall = spv::UMin3AMD;
7688 else
7689 libCall = spv::SMin3AMD;
7690 }
7691 break;
7692 case glslang::EOpMax3:
7693 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7694 if (isFloat)
7695 libCall = spv::FMax3AMD;
7696 else {
7697 if (isUnsigned)
7698 libCall = spv::UMax3AMD;
7699 else
7700 libCall = spv::SMax3AMD;
7701 }
7702 break;
7703 case glslang::EOpMid3:
7704 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7705 if (isFloat)
7706 libCall = spv::FMid3AMD;
7707 else {
7708 if (isUnsigned)
7709 libCall = spv::UMid3AMD;
7710 else
7711 libCall = spv::SMid3AMD;
7712 }
7713 break;
7714
7715 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007716 if (typeProxy == glslang::EbtFloat16)
7717 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007718 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7719 libCall = spv::InterpolateAtVertexAMD;
7720 break;
Chao Chen3c366992018-09-19 11:41:59 -07007721
Daniel Kochdb32b242020-03-17 20:42:47 -04007722 case glslang::EOpReportIntersection:
Chao Chenb50c02e2018-09-19 11:42:24 -07007723 typeId = builder.makeBoolType();
Daniel Kochdb32b242020-03-17 20:42:47 -04007724 opCode = spv::OpReportIntersectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007725 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04007726 case glslang::EOpTrace:
Daniel Kochdb32b242020-03-17 20:42:47 -04007727 builder.createNoResultOp(spv::OpTraceRayKHR, operands);
Ashwin Leleff1783d2018-10-22 16:41:44 -07007728 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04007729 case glslang::EOpExecuteCallable:
Daniel Kochdb32b242020-03-17 20:42:47 -04007730 builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007731 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007732
7733 case glslang::EOpRayQueryInitialize:
Torosdagli06c2eee2020-03-19 11:09:57 -04007734 builder.createNoResultOp(spv::OpRayQueryInitializeKHR, operands);
7735 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007736 case glslang::EOpRayQueryTerminate:
Torosdagli06c2eee2020-03-19 11:09:57 -04007737 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operands);
7738 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007739 case glslang::EOpRayQueryGenerateIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007740 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR, operands);
7741 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007742 case glslang::EOpRayQueryConfirmIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007743 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operands);
7744 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007745 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04007746 typeId = builder.makeBoolType();
7747 opCode = spv::OpRayQueryProceedKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007748 break;
7749 case glslang::EOpRayQueryGetIntersectionType:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007750 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007751 opCode = spv::OpRayQueryGetIntersectionTypeKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007752 break;
7753 case glslang::EOpRayQueryGetRayTMin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007754 typeId = builder.makeFloatType(32);
7755 opCode = spv::OpRayQueryGetRayTMinKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007756 break;
7757 case glslang::EOpRayQueryGetRayFlags:
Torosdagli06c2eee2020-03-19 11:09:57 -04007758 typeId = builder.makeIntType(32);
7759 opCode = spv::OpRayQueryGetRayFlagsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007760 break;
7761 case glslang::EOpRayQueryGetIntersectionT:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007762 typeId = builder.makeFloatType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007763 opCode = spv::OpRayQueryGetIntersectionTKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007764 break;
7765 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007766 typeId = builder.makeIntType(32);
7767 opCode = spv::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007768 break;
7769 case glslang::EOpRayQueryGetIntersectionInstanceId:
Torosdagli06c2eee2020-03-19 11:09:57 -04007770 typeId = builder.makeIntType(32);
7771 opCode = spv::OpRayQueryGetIntersectionInstanceIdKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007772 break;
7773 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
Torosdagli06c2eee2020-03-19 11:09:57 -04007774 typeId = builder.makeIntType(32);
7775 opCode = spv::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007776 break;
7777 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007778 typeId = builder.makeIntType(32);
7779 opCode = spv::OpRayQueryGetIntersectionGeometryIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007780 break;
7781 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007782 typeId = builder.makeIntType(32);
7783 opCode = spv::OpRayQueryGetIntersectionPrimitiveIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007784 break;
7785 case glslang::EOpRayQueryGetIntersectionBarycentrics:
Torosdagli06c2eee2020-03-19 11:09:57 -04007786 typeId = builder.makeVectorType(builder.makeFloatType(32), 2);
7787 opCode = spv::OpRayQueryGetIntersectionBarycentricsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007788 break;
7789 case glslang::EOpRayQueryGetIntersectionFrontFace:
Torosdagli06c2eee2020-03-19 11:09:57 -04007790 typeId = builder.makeBoolType();
7791 opCode = spv::OpRayQueryGetIntersectionFrontFaceKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007792 break;
7793 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
Torosdagli06c2eee2020-03-19 11:09:57 -04007794 typeId = builder.makeBoolType();
7795 opCode = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007796 break;
7797 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007798 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7799 opCode = spv::OpRayQueryGetIntersectionObjectRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007800 break;
7801 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007802 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7803 opCode = spv::OpRayQueryGetIntersectionObjectRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007804 break;
7805 case glslang::EOpRayQueryGetWorldRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007806 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7807 opCode = spv::OpRayQueryGetWorldRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007808 break;
7809 case glslang::EOpRayQueryGetWorldRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007810 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7811 opCode = spv::OpRayQueryGetWorldRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007812 break;
7813 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
Torosdagli06c2eee2020-03-19 11:09:57 -04007814 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007815 opCode = spv::OpRayQueryGetIntersectionObjectToWorldKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007816 break;
7817 case glslang::EOpRayQueryGetIntersectionWorldToObject:
Torosdagli06c2eee2020-03-19 11:09:57 -04007818 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007819 opCode = spv::OpRayQueryGetIntersectionWorldToObjectKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007820 break;
Chao Chen3c366992018-09-19 11:41:59 -07007821 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7822 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7823 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007824 case glslang::EOpCooperativeMatrixMulAdd:
7825 opCode = spv::OpCooperativeMatrixMulAddNV;
7826 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007827#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007828 default:
7829 return 0;
7830 }
7831
7832 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007833 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007834 // Use an extended instruction from the standard library.
7835 // Construct the call arguments, without modifying the original operands vector.
7836 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7837 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007838 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007839 } else if (opCode == spv::OpDot && !isFloat) {
7840 // int dot(int, int)
7841 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7842 const int componentCount = builder.getNumComponents(operands[0]);
7843 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7844 builder.setPrecision(mulOp, precision);
7845 id = builder.createCompositeExtract(mulOp, typeId, 0);
7846 for (int i = 1; i < componentCount; ++i) {
7847 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07007848 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01007849 }
John Kessenich2359bd02015-12-06 19:29:11 -07007850 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007851 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007852 case 0:
7853 // should all be handled by visitAggregate and createNoArgOperation
7854 assert(0);
7855 return 0;
7856 case 1:
7857 // should all be handled by createUnaryOperation
7858 assert(0);
7859 return 0;
7860 case 2:
7861 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7862 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007863 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007864 // anything 3 or over doesn't have l-value operands, so all should be consumed
7865 assert(consumedOperands == operands.size());
7866 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007867 break;
7868 }
7869 }
7870
John Kessenichb9197c82019-08-11 07:41:45 -06007871#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007872 // Decode the return types that were structures
7873 switch (op) {
7874 case glslang::EOpAddCarry:
7875 case glslang::EOpSubBorrow:
7876 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7877 id = builder.createCompositeExtract(id, typeId0, 0);
7878 break;
7879 case glslang::EOpUMulExtended:
7880 case glslang::EOpIMulExtended:
7881 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7882 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7883 break;
7884 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007885 {
7886 assert(operands.size() == 2);
7887 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7888 // "exp" is floating-point type (from HLSL intrinsic)
7889 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7890 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7891 builder.createStore(member1, operands[1]);
7892 } else
7893 // "exp" is integer type (from GLSL built-in function)
7894 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7895 id = builder.createCompositeExtract(id, typeId0, 0);
7896 }
John Kessenich55e7d112015-11-15 21:33:39 -07007897 break;
7898 default:
7899 break;
7900 }
John Kessenichb9197c82019-08-11 07:41:45 -06007901#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007902
John Kessenich32cfd492016-02-02 12:37:46 -07007903 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007904}
7905
Rex Xu9d93a232016-05-05 12:30:44 +08007906// Intrinsics with no arguments (or no return value, and no precision).
7907spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007908{
Jeff Bolz36831c92018-09-05 10:11:41 -05007909 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07007910 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
7911 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007912
7913 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007914 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007915 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007916 if (glslangIntermediate->usingVulkanMemoryModel()) {
7917 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7918 spv::MemorySemanticsOutputMemoryKHRMask |
7919 spv::MemorySemanticsAcquireReleaseMask);
7920 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7921 } else {
7922 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7923 }
John Kessenich82979362017-12-11 04:02:24 -07007924 } else {
7925 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7926 spv::MemorySemanticsWorkgroupMemoryMask |
7927 spv::MemorySemanticsAcquireReleaseMask);
7928 }
John Kessenich140f3df2015-06-26 16:58:36 -06007929 return 0;
7930 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007931 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7932 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007933 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007934 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007935 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7936 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007937 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007938 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007939 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7940 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007941 return 0;
7942 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007943 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7944 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007945 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007946#ifndef GLSLANG_WEB
7947 case glslang::EOpMemoryBarrierAtomicCounter:
7948 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7949 spv::MemorySemanticsAcquireReleaseMask);
7950 return 0;
7951 case glslang::EOpMemoryBarrierImage:
7952 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7953 spv::MemorySemanticsAcquireReleaseMask);
7954 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007955 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007956 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007957 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007958 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007959 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007960 case glslang::EOpDeviceMemoryBarrier:
7961 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7962 spv::MemorySemanticsImageMemoryMask |
7963 spv::MemorySemanticsAcquireReleaseMask);
7964 return 0;
7965 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7966 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7967 spv::MemorySemanticsImageMemoryMask |
7968 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007969 return 0;
7970 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007971 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7972 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007973 return 0;
7974 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007975 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7976 spv::MemorySemanticsWorkgroupMemoryMask |
7977 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007978 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007979 case glslang::EOpSubgroupBarrier:
7980 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7981 spv::MemorySemanticsAcquireReleaseMask);
7982 return spv::NoResult;
7983 case glslang::EOpSubgroupMemoryBarrier:
7984 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7985 spv::MemorySemanticsAcquireReleaseMask);
7986 return spv::NoResult;
7987 case glslang::EOpSubgroupMemoryBarrierBuffer:
7988 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7989 spv::MemorySemanticsAcquireReleaseMask);
7990 return spv::NoResult;
7991 case glslang::EOpSubgroupMemoryBarrierImage:
7992 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7993 spv::MemorySemanticsAcquireReleaseMask);
7994 return spv::NoResult;
7995 case glslang::EOpSubgroupMemoryBarrierShared:
7996 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7997 spv::MemorySemanticsAcquireReleaseMask);
7998 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06007999
8000 case glslang::EOpEmitVertex:
8001 builder.createNoResultOp(spv::OpEmitVertex);
8002 return 0;
8003 case glslang::EOpEndPrimitive:
8004 builder.createNoResultOp(spv::OpEndPrimitive);
8005 return 0;
8006
John Kessenich66011cb2018-03-06 16:12:04 -07008007 case glslang::EOpSubgroupElect: {
8008 std::vector<spv::Id> operands;
8009 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
8010 }
Rex Xu9d93a232016-05-05 12:30:44 +08008011 case glslang::EOpTime:
8012 {
8013 std::vector<spv::Id> args; // Dummy arguments
8014 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
8015 return builder.setPrecision(id, precision);
8016 }
Daniel Kochdb32b242020-03-17 20:42:47 -04008017 case glslang::EOpIgnoreIntersection:
8018 builder.createNoResultOp(spv::OpIgnoreIntersectionKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008019 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04008020 case glslang::EOpTerminateRay:
8021 builder.createNoResultOp(spv::OpTerminateRayKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008022 return 0;
Torosdagli06c2eee2020-03-19 11:09:57 -04008023 case glslang::EOpRayQueryInitialize:
8024 builder.createNoResultOp(spv::OpRayQueryInitializeKHR);
8025 return 0;
8026 case glslang::EOpRayQueryTerminate:
8027 builder.createNoResultOp(spv::OpRayQueryTerminateKHR);
8028 return 0;
8029 case glslang::EOpRayQueryGenerateIntersection:
8030 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR);
8031 return 0;
8032 case glslang::EOpRayQueryConfirmIntersection:
8033 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR);
8034 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05008035 case glslang::EOpBeginInvocationInterlock:
8036 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
8037 return 0;
8038 case glslang::EOpEndInvocationInterlock:
8039 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
8040 return 0;
8041
Jeff Bolzba6170b2019-07-01 09:23:23 -05008042 case glslang::EOpIsHelperInvocation:
8043 {
8044 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08008045 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
8046 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
8047 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05008048 }
8049
amhagan91fb0092019-07-10 21:14:38 -04008050 case glslang::EOpReadClockSubgroupKHR: {
8051 std::vector<spv::Id> args;
8052 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
8053 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8054 builder.addCapability(spv::CapabilityShaderClockKHR);
8055 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8056 }
8057
8058 case glslang::EOpReadClockDeviceKHR: {
8059 std::vector<spv::Id> args;
8060 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
8061 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8062 builder.addCapability(spv::CapabilityShaderClockKHR);
8063 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8064 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06008065#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008066 default:
John Kessenich155d3512019-08-08 23:29:20 -06008067 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008068 }
John Kessenich155d3512019-08-08 23:29:20 -06008069
8070 logger->missingFunctionality("unknown operation with no arguments");
8071
8072 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008073}
8074
8075spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
8076{
John Kessenich2f273362015-07-18 22:34:27 -06008077 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06008078 spv::Id id;
8079 if (symbolValues.end() != iter) {
8080 id = iter->second;
8081 return id;
8082 }
8083
8084 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06008085 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
Daniel Kochdb32b242020-03-17 20:42:47 -04008086 auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06008087 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06008088 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06008089 if (forcedType.second != spv::NoType)
8090 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06008091
Rex Xuc884b4a2016-06-29 15:03:44 +08008092 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008093 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
8094 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
8095 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06008096#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008097 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06008098 if (symbol->getQualifier().hasComponent())
8099 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
8100 if (symbol->getQualifier().hasIndex())
8101 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07008102#endif
John Kessenich6c292d32016-02-15 20:58:50 -07008103 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07008104 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06008105 // atomic counters use this:
8106 if (symbol->getQualifier().hasOffset())
8107 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008108 }
8109
scygan2c864272016-05-18 18:09:17 +02008110 if (symbol->getQualifier().hasLocation())
8111 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07008112 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07008113 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07008114 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06008115 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07008116 }
John Kessenich140f3df2015-06-26 16:58:36 -06008117 if (symbol->getQualifier().hasSet())
8118 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07008119 else if (IsDescriptorResource(symbol->getType())) {
8120 // default to 0
8121 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
8122 }
John Kessenich140f3df2015-06-26 16:58:36 -06008123 if (symbol->getQualifier().hasBinding())
8124 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06008125 else if (IsDescriptorResource(symbol->getType())) {
8126 // default to 0
8127 builder.addDecoration(id, spv::DecorationBinding, 0);
8128 }
John Kessenich6c292d32016-02-15 20:58:50 -07008129 if (symbol->getQualifier().hasAttachment())
8130 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06008131 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07008132 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07008133 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008134 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07008135 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
8136 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
8137 builder.addDecoration(id, spv::DecorationXfbStride, stride);
8138 }
8139 if (symbol->getQualifier().hasXfbOffset())
8140 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008141 }
8142
John Kessenichb9197c82019-08-11 07:41:45 -06008143 // add built-in variable decoration
8144 if (builtIn != spv::BuiltInMax) {
8145 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
8146 }
8147
8148#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08008149 if (symbol->getType().isImage()) {
8150 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07008151 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
8152 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08008153 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07008154 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08008155 }
8156
John Kessenich5611c6d2018-04-05 11:25:02 -06008157 // nonuniform
8158 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
8159
chaoc0ad6a4e2016-12-19 16:29:34 -08008160 if (builtIn == spv::BuiltInSampleMask) {
8161 spv::Decoration decoration;
8162 // GL_NV_sample_mask_override_coverage extension
8163 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08008164 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08008165 else
8166 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07008167 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08008168 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07008169 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08008170 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
8171 }
8172 }
chaoc771d89f2017-01-13 01:10:53 -08008173 else if (builtIn == spv::BuiltInLayer) {
8174 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06008175 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008176 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08008177 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
8178 builder.addExtension(spv::E_SPV_NV_viewport_array2);
8179 }
John Kessenichb41bff62017-08-11 13:07:17 -06008180 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008181 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
8182 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08008183 builder.addCapability(spv::CapabilityShaderStereoViewNV);
8184 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
8185 }
8186 }
8187
chaoc6e5acae2016-12-20 13:28:52 -08008188 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008189 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08008190 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08008191 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
8192 }
Chao Chen9eada4b2018-09-19 11:39:56 -07008193 if (symbol->getQualifier().pervertexNV) {
8194 builder.addDecoration(id, spv::DecorationPerVertexNV);
8195 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
8196 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
8197 }
chaoc0ad6a4e2016-12-19 16:29:34 -08008198
John Kessenich5d610ee2018-03-07 18:05:55 -07008199 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
8200 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
8201 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
8202 symbol->getType().getQualifier().semanticName);
8203 }
8204
John Kessenich7015bd62019-08-01 03:28:08 -06008205 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07008206 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
8207 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008208 }
John Kessenichb9197c82019-08-11 07:41:45 -06008209#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008210
John Kessenich140f3df2015-06-26 16:58:36 -06008211 return id;
8212}
8213
John Kessenicha28f7a72019-08-06 07:00:58 -06008214#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008215// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
8216void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
8217{
8218 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07008219 if (qualifier.perPrimitiveNV) {
8220 // Need to add capability/extension for fragment shader.
8221 // Mesh shader already adds this by default.
8222 if (glslangIntermediate->getStage() == EShLangFragment) {
8223 builder.addCapability(spv::CapabilityMeshShadingNV);
8224 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8225 }
Chao Chen3c366992018-09-19 11:41:59 -07008226 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008227 }
Chao Chen3c366992018-09-19 11:41:59 -07008228 if (qualifier.perViewNV)
8229 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
8230 if (qualifier.perTaskNV)
8231 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
8232 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07008233 if (qualifier.perPrimitiveNV) {
8234 // Need to add capability/extension for fragment shader.
8235 // Mesh shader already adds this by default.
8236 if (glslangIntermediate->getStage() == EShLangFragment) {
8237 builder.addCapability(spv::CapabilityMeshShadingNV);
8238 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8239 }
Chao Chen3c366992018-09-19 11:41:59 -07008240 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008241 }
Chao Chen3c366992018-09-19 11:41:59 -07008242 if (qualifier.perViewNV)
8243 builder.addDecoration(id, spv::DecorationPerViewNV);
8244 if (qualifier.perTaskNV)
8245 builder.addDecoration(id, spv::DecorationPerTaskNV);
8246 }
8247}
8248#endif
8249
John Kessenich55e7d112015-11-15 21:33:39 -07008250// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008251// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008252//
8253// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8254//
8255// Recursively walk the nodes. The nodes form a tree whose leaves are
8256// regular constants, which themselves are trees that createSpvConstant()
8257// recursively walks. So, this function walks the "top" of the tree:
8258// - emit specialization constant-building instructions for specConstant
8259// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008260spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008261{
John Kessenich7cc0e282016-03-20 00:46:02 -06008262 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008263
qining4f4bb812016-04-03 23:55:17 -04008264 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008265 if (! node.getQualifier().specConstant) {
8266 // hand off to the non-spec-constant path
8267 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8268 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008269 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8270 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8271 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008272 }
8273
8274 // We now know we have a specialization constant to build
8275
John Kessenichd94c0032016-05-30 19:29:40 -06008276 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008277 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8278 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8279 std::vector<spv::Id> dimConstId;
8280 for (int dim = 0; dim < 3; ++dim) {
8281 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8282 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008283 if (specConst) {
8284 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8285 glslangIntermediate->getLocalSizeSpecId(dim));
8286 }
qining4f4bb812016-04-03 23:55:17 -04008287 }
8288 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8289 }
8290
8291 // An AST node labelled as specialization constant should be a symbol node.
8292 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8293 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008294 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008295 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008296 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8297 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8298 // will set the builder into spec constant op instruction generating mode.
8299 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008300 result = accessChainLoad(sub_tree->getType());
8301 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008302 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008303 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008304 } else {
8305 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008306 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008307 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008308 builder.addName(result, sn->getName().c_str());
8309 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008310 }
qining4f4bb812016-04-03 23:55:17 -04008311
8312 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8313 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008314 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008315 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008316}
8317
John Kessenich140f3df2015-06-26 16:58:36 -06008318// Use 'consts' as the flattened glslang source of scalar constants to recursively
8319// build the aggregate SPIR-V constant.
8320//
8321// If there are not enough elements present in 'consts', 0 will be substituted;
8322// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8323//
John Kessenich8985fc92020-03-03 10:25:07 -07008324spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8325 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008326{
8327 // vector of constants for SPIR-V
8328 std::vector<spv::Id> spvConsts;
8329
8330 // Type is used for struct and array constants
8331 spv::Id typeId = convertGlslangToSpvType(glslangType);
8332
8333 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008334 glslang::TType elementType(glslangType, 0);
8335 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008336 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008337 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008338 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008339 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008340 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008341 } else if (glslangType.isCoopMat()) {
8342 glslang::TType componentType(glslangType.getBasicType());
8343 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008344 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008345 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8346 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008347 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008348 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008349 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8350 bool zero = nextConst >= consts.size();
8351 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008352 case glslang::EbtInt:
8353 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8354 break;
8355 case glslang::EbtUint:
8356 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8357 break;
8358 case glslang::EbtFloat:
8359 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8360 break;
8361 case glslang::EbtBool:
8362 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8363 break;
8364#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008365 case glslang::EbtInt8:
8366 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8367 break;
8368 case glslang::EbtUint8:
8369 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8370 break;
8371 case glslang::EbtInt16:
8372 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8373 break;
8374 case glslang::EbtUint16:
8375 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8376 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008377 case glslang::EbtInt64:
8378 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8379 break;
8380 case glslang::EbtUint64:
8381 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8382 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008383 case glslang::EbtDouble:
8384 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8385 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008386 case glslang::EbtFloat16:
8387 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8388 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008389#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008390 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008391 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008392 break;
8393 }
8394 ++nextConst;
8395 }
8396 } else {
8397 // we have a non-aggregate (scalar) constant
8398 bool zero = nextConst >= consts.size();
8399 spv::Id scalar = 0;
8400 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008401 case glslang::EbtInt:
8402 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8403 break;
8404 case glslang::EbtUint:
8405 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8406 break;
8407 case glslang::EbtFloat:
8408 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8409 break;
8410 case glslang::EbtBool:
8411 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8412 break;
8413#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008414 case glslang::EbtInt8:
8415 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8416 break;
8417 case glslang::EbtUint8:
8418 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8419 break;
8420 case glslang::EbtInt16:
8421 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8422 break;
8423 case glslang::EbtUint16:
8424 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8425 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008426 case glslang::EbtInt64:
8427 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8428 break;
8429 case glslang::EbtUint64:
8430 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8431 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008432 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008433 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008434 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008435 case glslang::EbtFloat16:
8436 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8437 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008438 case glslang::EbtReference:
8439 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8440 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8441 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008442#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008443 case glslang::EbtString:
8444 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8445 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008446 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008447 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008448 break;
8449 }
8450 ++nextConst;
8451 return scalar;
8452 }
8453
8454 return builder.makeCompositeConstant(typeId, spvConsts);
8455}
8456
John Kessenich7c1aa102015-10-15 13:29:11 -06008457// Return true if the node is a constant or symbol whose reading has no
8458// non-trivial observable cost or effect.
8459bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8460{
8461 // don't know what this is
8462 if (node == nullptr)
8463 return false;
8464
8465 // a constant is safe
8466 if (node->getAsConstantUnion() != nullptr)
8467 return true;
8468
8469 // not a symbol means non-trivial
8470 if (node->getAsSymbolNode() == nullptr)
8471 return false;
8472
8473 // a symbol, depends on what's being read
8474 switch (node->getType().getQualifier().storage) {
8475 case glslang::EvqTemporary:
8476 case glslang::EvqGlobal:
8477 case glslang::EvqIn:
8478 case glslang::EvqInOut:
8479 case glslang::EvqConst:
8480 case glslang::EvqConstReadOnly:
8481 case glslang::EvqUniform:
8482 return true;
8483 default:
8484 return false;
8485 }
qining25262b32016-05-06 17:25:16 -04008486}
John Kessenich7c1aa102015-10-15 13:29:11 -06008487
8488// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008489// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008490// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008491// Return true if trivial.
8492bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8493{
8494 if (node == nullptr)
8495 return false;
8496
John Kessenich84cc15f2017-05-24 16:44:47 -06008497 // count non scalars as trivial, as well as anything coming from HLSL
8498 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008499 return true;
8500
John Kessenich7c1aa102015-10-15 13:29:11 -06008501 // symbols and constants are trivial
8502 if (isTrivialLeaf(node))
8503 return true;
8504
8505 // otherwise, it needs to be a simple operation or one or two leaf nodes
8506
8507 // not a simple operation
8508 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8509 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8510 if (binaryNode == nullptr && unaryNode == nullptr)
8511 return false;
8512
8513 // not on leaf nodes
8514 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8515 return false;
8516
8517 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8518 return false;
8519 }
8520
8521 switch (node->getAsOperator()->getOp()) {
8522 case glslang::EOpLogicalNot:
8523 case glslang::EOpConvIntToBool:
8524 case glslang::EOpConvUintToBool:
8525 case glslang::EOpConvFloatToBool:
8526 case glslang::EOpConvDoubleToBool:
8527 case glslang::EOpEqual:
8528 case glslang::EOpNotEqual:
8529 case glslang::EOpLessThan:
8530 case glslang::EOpGreaterThan:
8531 case glslang::EOpLessThanEqual:
8532 case glslang::EOpGreaterThanEqual:
8533 case glslang::EOpIndexDirect:
8534 case glslang::EOpIndexDirectStruct:
8535 case glslang::EOpLogicalXor:
8536 case glslang::EOpAny:
8537 case glslang::EOpAll:
8538 return true;
8539 default:
8540 return false;
8541 }
8542}
8543
8544// Emit short-circuiting code, where 'right' is never evaluated unless
8545// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008546spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8547 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008548{
8549 spv::Id boolTypeId = builder.makeBoolType();
8550
8551 // emit left operand
8552 builder.clearAccessChain();
8553 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008554 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008555
8556 // Operands to accumulate OpPhi operands
8557 std::vector<spv::Id> phiOperands;
8558 // accumulate left operand's phi information
8559 phiOperands.push_back(leftId);
8560 phiOperands.push_back(builder.getBuildPoint()->getId());
8561
8562 // Make the two kinds of operation symmetric with a "!"
8563 // || => emit "if (! left) result = right"
8564 // && => emit "if ( left) result = right"
8565 //
8566 // TODO: this runtime "not" for || could be avoided by adding functionality
8567 // to 'builder' to have an "else" without an "then"
8568 if (op == glslang::EOpLogicalOr)
8569 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8570
8571 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008572 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008573
8574 // emit right operand as the "then" part of the "if"
8575 builder.clearAccessChain();
8576 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008577 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008578
8579 // accumulate left operand's phi information
8580 phiOperands.push_back(rightId);
8581 phiOperands.push_back(builder.getBuildPoint()->getId());
8582
8583 // finish the "if"
8584 ifBuilder.makeEndIf();
8585
8586 // phi together the two results
8587 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8588}
8589
John Kessenicha28f7a72019-08-06 07:00:58 -06008590#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008591// Return type Id of the imported set of extended instructions corresponds to the name.
8592// Import this set if it has not been imported yet.
8593spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8594{
8595 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8596 return extBuiltinMap[name];
8597 else {
Rex Xu51596642016-09-21 18:56:12 +08008598 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008599 spv::Id extBuiltins = builder.import(name);
8600 extBuiltinMap[name] = extBuiltins;
8601 return extBuiltins;
8602 }
8603}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008604#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008605
John Kessenich140f3df2015-06-26 16:58:36 -06008606}; // end anonymous namespace
8607
8608namespace glslang {
8609
John Kessenich68d78fd2015-07-12 19:28:10 -06008610void GetSpirvVersion(std::string& version)
8611{
John Kessenich9e55f632015-07-15 10:03:39 -06008612 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008613 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008614 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008615 version = buf;
8616}
8617
John Kessenicha372a3e2017-11-02 22:32:14 -06008618// For low-order part of the generator's magic number. Bump up
8619// when there is a change in the style (e.g., if SSA form changes,
8620// or a different instruction sequence to do something gets used).
8621int GetSpirvGeneratorVersion()
8622{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008623 // return 1; // start
8624 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008625 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008626 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008627 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008628 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8629 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008630 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
8631 return 8; // switch to new dead block eliminator; use OpUnreachable
John Kessenicha372a3e2017-11-02 22:32:14 -06008632}
8633
John Kessenich140f3df2015-06-26 16:58:36 -06008634// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008635void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008636{
8637 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008638 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008639 if (out.fail())
8640 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008641 for (int i = 0; i < (int)spirv.size(); ++i) {
8642 unsigned int word = spirv[i];
8643 out.write((const char*)&word, 4);
8644 }
8645 out.close();
8646}
8647
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008648// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008649void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008650{
John Kessenich155d3512019-08-08 23:29:20 -06008651#ifndef GLSLANG_WEB
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008652 std::ofstream out;
8653 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008654 if (out.fail())
8655 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008656 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008657 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008658 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008659 if (varName != nullptr) {
8660 out << "\t #pragma once" << std::endl;
8661 out << "const uint32_t " << varName << "[] = {" << std::endl;
8662 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008663 const int WORDS_PER_LINE = 8;
8664 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8665 out << "\t";
8666 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8667 const unsigned int word = spirv[i + j];
8668 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8669 if (i + j + 1 < (int)spirv.size()) {
8670 out << ",";
8671 }
8672 }
8673 out << std::endl;
8674 }
Flavio15017db2017-02-15 14:29:33 -08008675 if (varName != nullptr) {
8676 out << "};";
8677 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008678 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008679#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008680}
8681
John Kessenich140f3df2015-06-26 16:58:36 -06008682//
8683// Set up the glslang traversal
8684//
John Kessenich4e11b612018-08-30 16:56:59 -06008685void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008686{
Lei Zhang17535f72016-05-04 15:55:59 -04008687 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008688 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008689}
8690
John Kessenich4e11b612018-08-30 16:56:59 -06008691void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008692 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008693{
John Kessenich140f3df2015-06-26 16:58:36 -06008694 TIntermNode* root = intermediate.getTreeRoot();
8695
8696 if (root == 0)
8697 return;
8698
John Kessenich4e11b612018-08-30 16:56:59 -06008699 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008700 if (options == nullptr)
8701 options = &defaultOptions;
8702
John Kessenich4e11b612018-08-30 16:56:59 -06008703 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008704
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008705 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008706 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008707 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008708 it.dumpSpv(spirv);
8709
GregFfb03a552018-03-29 11:49:14 -06008710#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008711 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8712 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008713 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8714 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008715 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008716 prelegalization = false;
8717 }
John Kessenich717c80a2018-08-23 15:17:10 -06008718
John Kessenich4e11b612018-08-30 16:56:59 -06008719 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008720 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008721
John Kessenich717c80a2018-08-23 15:17:10 -06008722 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008723 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008724
GregFcd1f1692017-09-21 18:40:22 -06008725#endif
8726
John Kessenich4e11b612018-08-30 16:56:59 -06008727 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008728}
8729
8730}; // end namespace glslang