blob: 92cce814eaffbbc9cdacdcb2e841593d08472d19 [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 ||
4392 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004393 return qualifier != glslang::EvqConstReadOnly;
4394}
4395
4396// Is parameter pass-by-original?
4397bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4398 bool implicitThisParam)
4399{
4400 if (implicitThisParam) // implicit this
4401 return true;
4402 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004403 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004404 return paramType.containsOpaque() || // sampler, etc.
4405 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4406}
4407
John Kessenich140f3df2015-06-26 16:58:36 -06004408// Make all the functions, skeletally, without actually visiting their bodies.
4409void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4410{
John Kessenich8985fc92020-03-03 10:25:07 -07004411 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4412 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004413 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4414 if (paramPrecision != spv::NoPrecision)
4415 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004416 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004417 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004418 // Original and non-writable params pass the pointer directly and
4419 // use restrict/aliased, others are stored to a pointer in Function
4420 // memory and use RestrictPointer/AliasedPointer.
4421 if (originalParam(type.getQualifier().storage, type, false) ||
4422 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004423 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4424 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004425 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004426 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4427 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004428 }
4429 }
John Kessenichfad62972017-07-18 02:35:46 -06004430 };
4431
John Kessenich140f3df2015-06-26 16:58:36 -06004432 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4433 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004434 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004435 continue;
4436
4437 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004438 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004439 //
qining25262b32016-05-06 17:25:16 -04004440 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004441 // function. What it is an address of varies:
4442 //
John Kessenich4bf71552016-09-02 11:20:21 -06004443 // - "in" parameters not marked as "const" can be written to without modifying the calling
4444 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004445 //
4446 // - "const in" parameters can just be the r-value, as no writes need occur.
4447 //
John Kessenich4bf71552016-09-02 11:20:21 -06004448 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4449 // 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 -06004450
4451 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004452 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004453 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4454
John Kessenich155d3512019-08-08 23:29:20 -06004455#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004456 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4457 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004458#else
4459 bool implicitThis = false;
4460#endif
John Kessenich37789792017-03-21 23:56:40 -06004461
John Kessenichfad62972017-07-18 02:35:46 -06004462 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004463 for (int p = 0; p < (int)parameters.size(); ++p) {
4464 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4465 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004466 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004467 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004468 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004469 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4470 else
John Kessenich4bf71552016-09-02 11:20:21 -06004471 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004472 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004473 paramTypes.push_back(typeId);
4474 }
4475
4476 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004477 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4478 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004479 glslFunction->getName().c_str(), paramTypes,
4480 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004481 if (implicitThis)
4482 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004483
4484 // Track function to emit/call later
4485 functionMap[glslFunction->getName().c_str()] = function;
4486
4487 // Set the parameter id's
4488 for (int p = 0; p < (int)parameters.size(); ++p) {
4489 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4490 // give a name too
4491 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004492
4493 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004494 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004495 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004496 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004497 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004498 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004499 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004500 }
4501 }
4502}
4503
4504// Process all the initializers, while skipping the functions and link objects
4505void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4506{
4507 builder.setBuildPoint(shaderEntry->getLastBlock());
4508 for (int i = 0; i < (int)initializers.size(); ++i) {
4509 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004510 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4511 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004512
4513 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004514 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004515 initializer->traverse(this);
4516 }
4517 }
4518}
4519
4520// Process all the functions, while skipping initializers.
4521void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4522{
4523 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4524 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004525 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004526 node->traverse(this);
4527 }
4528}
4529
4530void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4531{
qining25262b32016-05-06 17:25:16 -04004532 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004533 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004534 currentFunction = functionMap[node->getName().c_str()];
4535 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004536 builder.setBuildPoint(functionBlock);
4537}
4538
John Kessenich8985fc92020-03-03 10:25:07 -07004539void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4540 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004541{
Rex Xufc618912015-09-09 16:42:49 +08004542 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004543
4544 glslang::TSampler sampler = {};
4545 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004546#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004547 bool f16ShadowCompare = false;
4548#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004549 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004550 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4551 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004552#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004553 f16ShadowCompare = sampler.shadow &&
4554 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004555#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004556 }
4557
John Kessenich140f3df2015-06-26 16:58:36 -06004558 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4559 builder.clearAccessChain();
4560 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004561
John Kessenicha28f7a72019-08-06 07:00:58 -06004562#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004563 // Special case l-value operands
4564 bool lvalue = false;
4565 switch (node.getOp()) {
4566 case glslang::EOpImageAtomicAdd:
4567 case glslang::EOpImageAtomicMin:
4568 case glslang::EOpImageAtomicMax:
4569 case glslang::EOpImageAtomicAnd:
4570 case glslang::EOpImageAtomicOr:
4571 case glslang::EOpImageAtomicXor:
4572 case glslang::EOpImageAtomicExchange:
4573 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004574 case glslang::EOpImageAtomicLoad:
4575 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004576 if (i == 0)
4577 lvalue = true;
4578 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004579 case glslang::EOpSparseImageLoad:
4580 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4581 lvalue = true;
4582 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004583 case glslang::EOpSparseTexture:
4584 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4585 lvalue = true;
4586 break;
4587 case glslang::EOpSparseTextureClamp:
4588 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4589 lvalue = true;
4590 break;
4591 case glslang::EOpSparseTextureLod:
4592 case glslang::EOpSparseTextureOffset:
4593 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4594 lvalue = true;
4595 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004596 case glslang::EOpSparseTextureFetch:
4597 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4598 lvalue = true;
4599 break;
4600 case glslang::EOpSparseTextureFetchOffset:
4601 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4602 lvalue = true;
4603 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004604 case glslang::EOpSparseTextureLodOffset:
4605 case glslang::EOpSparseTextureGrad:
4606 case glslang::EOpSparseTextureOffsetClamp:
4607 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4608 lvalue = true;
4609 break;
4610 case glslang::EOpSparseTextureGradOffset:
4611 case glslang::EOpSparseTextureGradClamp:
4612 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4613 lvalue = true;
4614 break;
4615 case glslang::EOpSparseTextureGradOffsetClamp:
4616 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4617 lvalue = true;
4618 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004619 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004620 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4621 lvalue = true;
4622 break;
4623 case glslang::EOpSparseTextureGatherOffset:
4624 case glslang::EOpSparseTextureGatherOffsets:
4625 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4626 lvalue = true;
4627 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004628 case glslang::EOpSparseTextureGatherLod:
4629 if (i == 3)
4630 lvalue = true;
4631 break;
4632 case glslang::EOpSparseTextureGatherLodOffset:
4633 case glslang::EOpSparseTextureGatherLodOffsets:
4634 if (i == 4)
4635 lvalue = true;
4636 break;
Rex Xu129799a2017-07-05 17:23:28 +08004637 case glslang::EOpSparseImageLoadLod:
4638 if (i == 3)
4639 lvalue = true;
4640 break;
Chao Chen3a137962018-09-19 11:41:27 -07004641 case glslang::EOpImageSampleFootprintNV:
4642 if (i == 4)
4643 lvalue = true;
4644 break;
4645 case glslang::EOpImageSampleFootprintClampNV:
4646 case glslang::EOpImageSampleFootprintLodNV:
4647 if (i == 5)
4648 lvalue = true;
4649 break;
4650 case glslang::EOpImageSampleFootprintGradNV:
4651 if (i == 6)
4652 lvalue = true;
4653 break;
4654 case glslang::EOpImageSampleFootprintGradClampNV:
4655 if (i == 7)
4656 lvalue = true;
4657 break;
Rex Xufc618912015-09-09 16:42:49 +08004658 default:
4659 break;
4660 }
4661
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004662 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004663 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004664 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4665 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4666 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004667#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004668 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004669 }
4670}
4671
John Kessenichfc51d282015-08-19 13:34:18 -06004672void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004673{
John Kessenichfc51d282015-08-19 13:34:18 -06004674 builder.clearAccessChain();
4675 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004676 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004677}
John Kessenich140f3df2015-06-26 16:58:36 -06004678
John Kessenichfc51d282015-08-19 13:34:18 -06004679spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4680{
John Kesseniche485c7a2017-05-31 18:50:53 -06004681 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004682 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004683
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004684 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004685
John Kessenichfc51d282015-08-19 13:34:18 -06004686 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004687
John Kessenichf43c7392019-03-31 10:51:57 -06004688 const glslang::TType &imageType = node->getAsAggregate()
4689 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4690 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004691 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004692#ifdef GLSLANG_WEB
4693 const bool f16ShadowCompare = false;
4694#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004695 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004696 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4697 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004698#endif
4699
John Kessenichf43c7392019-03-31 10:51:57 -06004700 const auto signExtensionMask = [&]() {
4701 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4702 if (sampler.type == glslang::EbtUint)
4703 return spv::ImageOperandsZeroExtendMask;
4704 else if (sampler.type == glslang::EbtInt)
4705 return spv::ImageOperandsSignExtendMask;
4706 }
4707 return spv::ImageOperandsMaskNone;
4708 };
4709
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004710 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4711
John Kessenichfc51d282015-08-19 13:34:18 -06004712 std::vector<spv::Id> arguments;
4713 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004714 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004715 else
4716 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004717 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004718
4719 spv::Builder::TextureParameters params = { };
4720 params.sampler = arguments[0];
4721
Rex Xu04db3f52015-09-16 11:44:02 +08004722 glslang::TCrackedTextureOp cracked;
4723 node->crackTexture(sampler, cracked);
4724
amhagan05506bb2017-06-13 16:53:02 -04004725 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004726
John Kessenichfc51d282015-08-19 13:34:18 -06004727 // Check for queries
4728 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004729 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4730 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004731 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004732
John Kessenichfc51d282015-08-19 13:34:18 -06004733 switch (node->getOp()) {
4734 case glslang::EOpImageQuerySize:
4735 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004736 if (arguments.size() > 1) {
4737 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004738 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004739 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004740 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004741#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004742 case glslang::EOpImageQuerySamples:
4743 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004744 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004745 case glslang::EOpTextureQueryLod:
4746 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004747 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004748 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004749 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004750 case glslang::EOpSparseTexelsResident:
4751 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004752#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004753 default:
4754 assert(0);
4755 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004756 }
John Kessenich140f3df2015-06-26 16:58:36 -06004757 }
4758
LoopDawg4425f242018-02-18 11:40:01 -07004759 int components = node->getType().getVectorSize();
4760
4761 if (node->getOp() == glslang::EOpTextureFetch) {
4762 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4763 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4764 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4765 // here around e.g. which ones return scalars or other types.
4766 components = 4;
4767 }
4768
4769 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4770
4771 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4772
Rex Xufc618912015-09-09 16:42:49 +08004773 // Check for image functions other than queries
4774 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004775 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004776 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004777 spv::IdImmediate image = { true, *(opIt++) };
4778 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004779
4780 // Handle subpass operations
4781 // TODO: GLSL should change to have the "MS" only on the type rather than the
4782 // built-in function.
4783 if (cracked.subpass) {
4784 // add on the (0,0) coordinate
4785 spv::Id zero = builder.makeIntConstant(0);
4786 std::vector<spv::Id> comps;
4787 comps.push_back(zero);
4788 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004789 spv::IdImmediate coord = { true,
4790 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4791 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004792 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4793 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004794 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004795 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4796 }
4797 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004798 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004799 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004800 spv::IdImmediate imageOperand = { true, *(opIt++) };
4801 operands.push_back(imageOperand);
4802 }
John Kessenich6c292d32016-02-15 20:58:50 -07004803 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004804 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4805 builder.setPrecision(result, precision);
4806 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004807 }
4808
John Kessenich149afc32018-08-14 13:31:43 -06004809 spv::IdImmediate coord = { true, *(opIt++) };
4810 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004811 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004812 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004813 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004814 mask = mask | spv::ImageOperandsSampleMask;
4815 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004816 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004817 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4818 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004819 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004820 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004821 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4822 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004823 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004824 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004825 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4826 operands.push_back(imageOperands);
4827 }
4828 if (mask & spv::ImageOperandsSampleMask) {
4829 spv::IdImmediate imageOperand = { true, *opIt++ };
4830 operands.push_back(imageOperand);
4831 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004832 if (mask & spv::ImageOperandsLodMask) {
4833 spv::IdImmediate imageOperand = { true, *opIt++ };
4834 operands.push_back(imageOperand);
4835 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004836 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004837 spv::IdImmediate imageOperand = { true,
4838 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004839 operands.push_back(imageOperand);
4840 }
4841
John Kessenich149afc32018-08-14 13:31:43 -06004842 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004843 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004844
John Kessenich149afc32018-08-14 13:31:43 -06004845 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004846 builder.setPrecision(result[0], precision);
4847
4848 // If needed, add a conversion constructor to the proper size.
4849 if (components != node->getType().getVectorSize())
4850 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4851
4852 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004853 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004854
Jeff Bolz36831c92018-09-05 10:11:41 -05004855 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004856 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004857 spv::IdImmediate texel = { true, *(opIt + 1) };
4858 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004859 } else {
4860 spv::IdImmediate texel = { true, *opIt };
4861 operands.push_back(texel);
4862 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004863
4864 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004865 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004866 mask = mask | spv::ImageOperandsSampleMask;
4867 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004868 if (cracked.lod) {
4869 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4870 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4871 mask = mask | spv::ImageOperandsLodMask;
4872 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004873 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4874 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004875 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004876 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004877 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4878 operands.push_back(imageOperands);
4879 }
4880 if (mask & spv::ImageOperandsSampleMask) {
4881 spv::IdImmediate imageOperand = { true, *opIt++ };
4882 operands.push_back(imageOperand);
4883 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004884 if (mask & spv::ImageOperandsLodMask) {
4885 spv::IdImmediate imageOperand = { true, *opIt++ };
4886 operands.push_back(imageOperand);
4887 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004888 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004889 spv::IdImmediate imageOperand = { true,
4890 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004891 operands.push_back(imageOperand);
4892 }
4893
John Kessenich56bab042015-09-16 10:54:31 -06004894 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004895 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004896 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004897 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004898 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4899 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004900 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004901 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004902 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4903
Jeff Bolz36831c92018-09-05 10:11:41 -05004904 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004905 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004906 mask = mask | spv::ImageOperandsSampleMask;
4907 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004908 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004909 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4910 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4911
Jeff Bolz36831c92018-09-05 10:11:41 -05004912 mask = mask | spv::ImageOperandsLodMask;
4913 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004914 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4915 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004916 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004917 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004918 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004919 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004920 }
4921 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004922 spv::IdImmediate imageOperand = { true, *opIt++ };
4923 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004924 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004925 if (mask & spv::ImageOperandsLodMask) {
4926 spv::IdImmediate imageOperand = { true, *opIt++ };
4927 operands.push_back(imageOperand);
4928 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004929 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07004930 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
4931 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004932 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004933 }
4934
4935 // Create the return type that was a special structure
4936 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004937 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004938 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4939 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4940
4941 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4942
4943 // Decode the return type
4944 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4945 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004946 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004947 // Process image atomic operations
4948
4949 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4950 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004951 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004952 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004953 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004954
Jeff Bolz36831c92018-09-05 10:11:41 -05004955 spv::Id resultTypeId;
4956 // imageAtomicStore has a void return type so base the pointer type on
4957 // the type of the value operand.
4958 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08004959 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05004960 } else {
4961 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4962 }
John Kessenich56bab042015-09-16 10:54:31 -06004963 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Jeff Bolz39ffdaf2020-03-09 10:48:12 -05004964 if (imageType.getQualifier().nonUniform) {
4965 builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
4966 }
Rex Xufc618912015-09-09 16:42:49 +08004967
4968 std::vector<spv::Id> operands;
4969 operands.push_back(pointer);
4970 for (; opIt != arguments.end(); ++opIt)
4971 operands.push_back(*opIt);
4972
John Kessenich8985fc92020-03-03 10:25:07 -07004973 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
4974 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004975 }
4976 }
4977
John Kessenicha28f7a72019-08-06 07:00:58 -06004978#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004979 // Check for fragment mask functions other than queries
4980 if (cracked.fragMask) {
4981 assert(sampler.ms);
4982
4983 auto opIt = arguments.begin();
4984 std::vector<spv::Id> operands;
4985
4986 // Extract the image if necessary
4987 if (builder.isSampledImage(params.sampler))
4988 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4989
4990 operands.push_back(params.sampler);
4991 ++opIt;
4992
4993 if (sampler.isSubpass()) {
4994 // add on the (0,0) coordinate
4995 spv::Id zero = builder.makeIntConstant(0);
4996 std::vector<spv::Id> comps;
4997 comps.push_back(zero);
4998 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07004999 operands.push_back(builder.makeCompositeConstant(
5000 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04005001 }
5002
5003 for (; opIt != arguments.end(); ++opIt)
5004 operands.push_back(*opIt);
5005
5006 spv::Op fragMaskOp = spv::OpNop;
5007 if (node->getOp() == glslang::EOpFragmentMaskFetch)
5008 fragMaskOp = spv::OpFragmentMaskFetchAMD;
5009 else if (node->getOp() == glslang::EOpFragmentFetch)
5010 fragMaskOp = spv::OpFragmentFetchAMD;
5011
5012 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
5013 builder.addCapability(spv::CapabilityFragmentMaskAMD);
5014 return builder.createOp(fragMaskOp, resultType(), operands);
5015 }
5016#endif
5017
Rex Xufc618912015-09-09 16:42:49 +08005018 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08005019 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07005020 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005021 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08005022
John Kessenichfc51d282015-08-19 13:34:18 -06005023 // check for bias argument
5024 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08005025 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005026 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08005027 if (cracked.gather)
5028 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08005029
5030 if (f16ShadowCompare)
5031 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005032 if (cracked.offset)
5033 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08005034 else if (cracked.offsets)
5035 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005036 if (cracked.grad)
5037 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08005038 if (cracked.lodClamp)
5039 ++nonBiasArgCount;
5040 if (sparse)
5041 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07005042 if (imageFootprint)
5043 //Following three extra arguments
5044 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5045 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06005046 if ((int)arguments.size() > nonBiasArgCount)
5047 bias = true;
5048 }
5049
John Kessenicha5c33d62016-06-02 23:45:21 -06005050 // See if the sampler param should really be just the SPV image part
5051 if (cracked.fetch) {
5052 // a fetch needs to have the image extracted first
5053 if (builder.isSampledImage(params.sampler))
5054 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
5055 }
5056
John Kessenicha28f7a72019-08-06 07:00:58 -06005057#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08005058 if (cracked.gather) {
5059 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
5060 if (bias || cracked.lod ||
5061 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
5062 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08005063 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08005064 }
5065 }
5066#endif
5067
John Kessenichfc51d282015-08-19 13:34:18 -06005068 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07005069
John Kessenichfc51d282015-08-19 13:34:18 -06005070 params.coords = arguments[1];
5071 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07005072 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07005073
5074 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08005075 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005076 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08005077 ++extraArgs;
5078 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07005079 params.Dref = arguments[2];
5080 ++extraArgs;
5081 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06005082 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06005083 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06005084 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06005085 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06005086 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005087 dRefComp = builder.getNumComponents(params.coords) - 1;
5088 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07005089 params.Dref = builder.createCompositeExtract(params.coords,
5090 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06005091 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005092
5093 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06005094 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005095 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06005096 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06005097 } else if (glslangIntermediate->getStage() != EShLangFragment &&
5098 !(glslangIntermediate->getStage() == EShLangCompute &&
5099 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07005100 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
5101 noImplicitLod = true;
5102 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005103
5104 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005105 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005106 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08005107 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005108 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005109
5110 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06005111 if (cracked.grad) {
5112 params.gradX = arguments[2 + extraArgs];
5113 params.gradY = arguments[3 + extraArgs];
5114 extraArgs += 2;
5115 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005116
5117 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07005118 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06005119 params.offset = arguments[2 + extraArgs];
5120 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005121 } else if (cracked.offsets) {
5122 params.offsets = arguments[2 + extraArgs];
5123 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005124 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005125
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005126#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005127 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005128 if (cracked.lodClamp) {
5129 params.lodClamp = arguments[2 + extraArgs];
5130 ++extraArgs;
5131 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005132 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005133 if (sparse) {
5134 params.texelOut = arguments[2 + extraArgs];
5135 ++extraArgs;
5136 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005137 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005138 if (cracked.gather && ! sampler.shadow) {
5139 // default component is 0, if missing, otherwise an argument
5140 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005141 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005142 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005143 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005144 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005145 }
Chao Chen3a137962018-09-19 11:41:27 -07005146 spv::Id resultStruct = spv::NoResult;
5147 if (imageFootprint) {
5148 //Following three extra arguments
5149 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5150 params.granularity = arguments[2 + extraArgs];
5151 params.coarse = arguments[3 + extraArgs];
5152 resultStruct = arguments[4 + extraArgs];
5153 extraArgs += 3;
5154 }
5155#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005156 // bias
5157 if (bias) {
5158 params.bias = arguments[2 + extraArgs];
5159 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005160 }
John Kessenichfc51d282015-08-19 13:34:18 -06005161
John Kessenicha28f7a72019-08-06 07:00:58 -06005162#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005163 if (imageFootprint) {
5164 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5165 builder.addCapability(spv::CapabilityImageFootprintNV);
5166
5167
5168 //resultStructType(OpenGL type) contains 5 elements:
5169 //struct gl_TextureFootprint2DNV {
5170 // uvec2 anchor;
5171 // uvec2 offset;
5172 // uvec2 mask;
5173 // uint lod;
5174 // uint granularity;
5175 //};
5176 //or
5177 //struct gl_TextureFootprint3DNV {
5178 // uvec3 anchor;
5179 // uvec3 offset;
5180 // uvec2 mask;
5181 // uint lod;
5182 // uint granularity;
5183 //};
5184 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5185 assert(builder.isStructType(resultStructType));
5186
5187 //resType (SPIR-V type) contains 6 elements:
5188 //Member 0 must be a Boolean type scalar(LOD),
5189 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5190 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5191 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5192 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5193 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5194 std::vector<spv::Id> members;
5195 members.push_back(resultType());
5196 for (int i = 0; i < 5; i++) {
5197 members.push_back(builder.getContainedTypeId(resultStructType, i));
5198 }
5199 spv::Id resType = builder.makeStructType(members, "ResType");
5200
5201 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005202 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5203 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005204
5205 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5206 for (int i = 0; i < 5; i++) {
5207 builder.clearAccessChain();
5208 builder.setAccessChainLValue(resultStruct);
5209
5210 //Accessing to a struct we created, no coherent flag is set
5211 spv::Builder::AccessChain::CoherentFlags flags;
5212 flags.clear();
5213
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005214 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005215 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
5216 i+1));
Chao Chen3a137962018-09-19 11:41:27 -07005217 }
5218 return builder.createCompositeExtract(res, resultType(), 0);
5219 }
5220#endif
5221
John Kessenich65336482016-06-16 14:06:26 -06005222 // projective component (might not to move)
5223 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5224 // are divided by the last component of P."
5225 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5226 // unused components will appear after all used components."
5227 if (cracked.proj) {
5228 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5229 int projTargetComp;
5230 switch (sampler.dim) {
5231 case glslang::Esd1D: projTargetComp = 1; break;
5232 case glslang::Esd2D: projTargetComp = 2; break;
5233 case glslang::EsdRect: projTargetComp = 2; break;
5234 default: projTargetComp = projSourceComp; break;
5235 }
5236 // copy the projective coordinate if we have to
5237 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005238 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005239 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005240 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005241 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005242 }
5243 }
5244
John Kessenichf8d1d742019-10-21 06:55:11 -06005245#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005246 // nonprivate
5247 if (imageType.getQualifier().nonprivate) {
5248 params.nonprivate = true;
5249 }
5250
5251 // volatile
5252 if (imageType.getQualifier().volatil) {
5253 params.volatil = true;
5254 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005255#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005256
St0fFa1184dd2018-04-09 21:08:14 +02005257 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005258 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5259 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005260 );
LoopDawg4425f242018-02-18 11:40:01 -07005261
5262 if (components != node->getType().getVectorSize())
5263 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5264
5265 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005266}
5267
5268spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5269{
5270 // Grab the function's pointer from the previously created function
5271 spv::Function* function = functionMap[node->getName().c_str()];
5272 if (! function)
5273 return 0;
5274
5275 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5276 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5277
5278 // See comments in makeFunctions() for details about the semantics for parameter passing.
5279 //
5280 // These imply we need a four step process:
5281 // 1. Evaluate the arguments
5282 // 2. Allocate and make copies of in, out, and inout arguments
5283 // 3. Make the call
5284 // 4. Copy back the results
5285
John Kessenichd3ed90b2018-05-04 11:43:03 -06005286 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005287 std::vector<spv::Builder::AccessChain> lValues;
5288 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005289 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005290 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005291 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005292 // build l-value
5293 builder.clearAccessChain();
5294 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005295 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005296 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005297 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005298 // save l-value
5299 lValues.push_back(builder.getAccessChain());
5300 } else {
5301 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005302 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005303 }
5304 }
5305
5306 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5307 // copy the original into that space.
5308 //
5309 // Also, build up the list of actual arguments to pass in for the call
5310 int lValueCount = 0;
5311 int rValueCount = 0;
5312 std::vector<spv::Id> spvArgs;
5313 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5314 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005315 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005316 builder.setAccessChain(lValues[lValueCount]);
5317 arg = builder.accessChainGetLValue();
5318 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005319 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005320 // need space to hold the copy
John Kessenich8985fc92020-03-03 10:25:07 -07005321 arg = builder.createVariable(spv::StorageClassFunction,
5322 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005323 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5324 // need to copy the input into output space
5325 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005326 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005327 builder.clearAccessChain();
5328 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005329 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005330 }
5331 ++lValueCount;
5332 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005333 // process r-value, which involves a copy for a type mismatch
5334 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5335 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5336 builder.clearAccessChain();
5337 builder.setAccessChainLValue(argCopy);
5338 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5339 arg = builder.createLoad(argCopy);
5340 } else
5341 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005342 ++rValueCount;
5343 }
5344 spvArgs.push_back(arg);
5345 }
5346
5347 // 3. Make the call.
5348 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005349 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005350
5351 // 4. Copy back out an "out" arguments.
5352 lValueCount = 0;
5353 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005354 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005355 ++lValueCount;
5356 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005357 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5358 spv::Id copy = builder.createLoad(spvArgs[a]);
5359 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005360 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005361 }
5362 ++lValueCount;
5363 }
5364 }
5365
5366 return result;
5367}
5368
5369// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005370spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005371 spv::Id typeId, spv::Id left, spv::Id right,
5372 glslang::TBasicType typeProxy, bool reduceComparison)
5373{
John Kessenich66011cb2018-03-06 16:12:04 -07005374 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5375 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005376 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005377
5378 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005379 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005380 bool comparison = false;
5381
5382 switch (op) {
5383 case glslang::EOpAdd:
5384 case glslang::EOpAddAssign:
5385 if (isFloat)
5386 binOp = spv::OpFAdd;
5387 else
5388 binOp = spv::OpIAdd;
5389 break;
5390 case glslang::EOpSub:
5391 case glslang::EOpSubAssign:
5392 if (isFloat)
5393 binOp = spv::OpFSub;
5394 else
5395 binOp = spv::OpISub;
5396 break;
5397 case glslang::EOpMul:
5398 case glslang::EOpMulAssign:
5399 if (isFloat)
5400 binOp = spv::OpFMul;
5401 else
5402 binOp = spv::OpIMul;
5403 break;
5404 case glslang::EOpVectorTimesScalar:
5405 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005406 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005407 if (builder.isVector(right))
5408 std::swap(left, right);
5409 assert(builder.isScalar(right));
5410 needMatchingVectors = false;
5411 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005412 } else if (isFloat)
5413 binOp = spv::OpFMul;
5414 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005415 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005416 break;
5417 case glslang::EOpVectorTimesMatrix:
5418 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005419 binOp = spv::OpVectorTimesMatrix;
5420 break;
5421 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005422 binOp = spv::OpMatrixTimesVector;
5423 break;
5424 case glslang::EOpMatrixTimesScalar:
5425 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005426 binOp = spv::OpMatrixTimesScalar;
5427 break;
5428 case glslang::EOpMatrixTimesMatrix:
5429 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005430 binOp = spv::OpMatrixTimesMatrix;
5431 break;
5432 case glslang::EOpOuterProduct:
5433 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005434 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005435 break;
5436
5437 case glslang::EOpDiv:
5438 case glslang::EOpDivAssign:
5439 if (isFloat)
5440 binOp = spv::OpFDiv;
5441 else if (isUnsigned)
5442 binOp = spv::OpUDiv;
5443 else
5444 binOp = spv::OpSDiv;
5445 break;
5446 case glslang::EOpMod:
5447 case glslang::EOpModAssign:
5448 if (isFloat)
5449 binOp = spv::OpFMod;
5450 else if (isUnsigned)
5451 binOp = spv::OpUMod;
5452 else
5453 binOp = spv::OpSMod;
5454 break;
5455 case glslang::EOpRightShift:
5456 case glslang::EOpRightShiftAssign:
5457 if (isUnsigned)
5458 binOp = spv::OpShiftRightLogical;
5459 else
5460 binOp = spv::OpShiftRightArithmetic;
5461 break;
5462 case glslang::EOpLeftShift:
5463 case glslang::EOpLeftShiftAssign:
5464 binOp = spv::OpShiftLeftLogical;
5465 break;
5466 case glslang::EOpAnd:
5467 case glslang::EOpAndAssign:
5468 binOp = spv::OpBitwiseAnd;
5469 break;
5470 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005471 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005472 binOp = spv::OpLogicalAnd;
5473 break;
5474 case glslang::EOpInclusiveOr:
5475 case glslang::EOpInclusiveOrAssign:
5476 binOp = spv::OpBitwiseOr;
5477 break;
5478 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005479 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005480 binOp = spv::OpLogicalOr;
5481 break;
5482 case glslang::EOpExclusiveOr:
5483 case glslang::EOpExclusiveOrAssign:
5484 binOp = spv::OpBitwiseXor;
5485 break;
5486 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005487 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005488 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005489 break;
5490
Ian Romanickb3bd4022019-01-21 08:57:25 -08005491 case glslang::EOpAbsDifference:
5492 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5493 break;
5494
5495 case glslang::EOpAddSaturate:
5496 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5497 break;
5498
5499 case glslang::EOpSubSaturate:
5500 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5501 break;
5502
5503 case glslang::EOpAverage:
5504 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5505 break;
5506
5507 case glslang::EOpAverageRounded:
5508 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5509 break;
5510
5511 case glslang::EOpMul32x16:
5512 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5513 break;
5514
John Kessenich140f3df2015-06-26 16:58:36 -06005515 case glslang::EOpLessThan:
5516 case glslang::EOpGreaterThan:
5517 case glslang::EOpLessThanEqual:
5518 case glslang::EOpGreaterThanEqual:
5519 case glslang::EOpEqual:
5520 case glslang::EOpNotEqual:
5521 case glslang::EOpVectorEqual:
5522 case glslang::EOpVectorNotEqual:
5523 comparison = true;
5524 break;
5525 default:
5526 break;
5527 }
5528
John Kessenich7c1aa102015-10-15 13:29:11 -06005529 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005530 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005531 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005532 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5533 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005534 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005535
5536 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005537 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005538 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005539
qining25262b32016-05-06 17:25:16 -04005540 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005541 decorations.addNoContraction(builder, result);
5542 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005543 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005544 }
5545
5546 if (! comparison)
5547 return 0;
5548
John Kessenich7c1aa102015-10-15 13:29:11 -06005549 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005550
John Kessenich4583b612016-08-07 19:14:22 -06005551 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005552 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5553 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005554 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005555 return result;
5556 }
John Kessenich140f3df2015-06-26 16:58:36 -06005557
5558 switch (op) {
5559 case glslang::EOpLessThan:
5560 if (isFloat)
5561 binOp = spv::OpFOrdLessThan;
5562 else if (isUnsigned)
5563 binOp = spv::OpULessThan;
5564 else
5565 binOp = spv::OpSLessThan;
5566 break;
5567 case glslang::EOpGreaterThan:
5568 if (isFloat)
5569 binOp = spv::OpFOrdGreaterThan;
5570 else if (isUnsigned)
5571 binOp = spv::OpUGreaterThan;
5572 else
5573 binOp = spv::OpSGreaterThan;
5574 break;
5575 case glslang::EOpLessThanEqual:
5576 if (isFloat)
5577 binOp = spv::OpFOrdLessThanEqual;
5578 else if (isUnsigned)
5579 binOp = spv::OpULessThanEqual;
5580 else
5581 binOp = spv::OpSLessThanEqual;
5582 break;
5583 case glslang::EOpGreaterThanEqual:
5584 if (isFloat)
5585 binOp = spv::OpFOrdGreaterThanEqual;
5586 else if (isUnsigned)
5587 binOp = spv::OpUGreaterThanEqual;
5588 else
5589 binOp = spv::OpSGreaterThanEqual;
5590 break;
5591 case glslang::EOpEqual:
5592 case glslang::EOpVectorEqual:
5593 if (isFloat)
5594 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005595 else if (isBool)
5596 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005597 else
5598 binOp = spv::OpIEqual;
5599 break;
5600 case glslang::EOpNotEqual:
5601 case glslang::EOpVectorNotEqual:
5602 if (isFloat)
5603 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005604 else if (isBool)
5605 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005606 else
5607 binOp = spv::OpINotEqual;
5608 break;
5609 default:
5610 break;
5611 }
5612
qining25262b32016-05-06 17:25:16 -04005613 if (binOp != spv::OpNop) {
5614 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005615 decorations.addNoContraction(builder, result);
5616 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005617 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005618 }
John Kessenich140f3df2015-06-26 16:58:36 -06005619
5620 return 0;
5621}
5622
John Kessenich04bb8a02015-12-12 12:28:14 -07005623//
5624// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5625// These can be any of:
5626//
5627// matrix * scalar
5628// scalar * matrix
5629// matrix * matrix linear algebraic
5630// matrix * vector
5631// vector * matrix
5632// matrix * matrix componentwise
5633// matrix op matrix op in {+, -, /}
5634// matrix op scalar op in {+, -, /}
5635// scalar op matrix op in {+, -, /}
5636//
John Kessenichead86222018-03-28 18:01:20 -06005637spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5638 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005639{
5640 bool firstClass = true;
5641
5642 // First, handle first-class matrix operations (* and matrix/scalar)
5643 switch (op) {
5644 case spv::OpFDiv:
5645 if (builder.isMatrix(left) && builder.isScalar(right)) {
5646 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005647 spv::Id resultType = builder.getTypeId(right);
5648 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005649 op = spv::OpMatrixTimesScalar;
5650 } else
5651 firstClass = false;
5652 break;
5653 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005654 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005655 std::swap(left, right);
5656 assert(builder.isScalar(right));
5657 break;
5658 case spv::OpVectorTimesMatrix:
5659 assert(builder.isVector(left));
5660 assert(builder.isMatrix(right));
5661 break;
5662 case spv::OpMatrixTimesVector:
5663 assert(builder.isMatrix(left));
5664 assert(builder.isVector(right));
5665 break;
5666 case spv::OpMatrixTimesMatrix:
5667 assert(builder.isMatrix(left));
5668 assert(builder.isMatrix(right));
5669 break;
5670 default:
5671 firstClass = false;
5672 break;
5673 }
5674
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005675 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5676 firstClass = true;
5677
qining25262b32016-05-06 17:25:16 -04005678 if (firstClass) {
5679 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005680 decorations.addNoContraction(builder, result);
5681 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005682 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005683 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005684
LoopDawg592860c2016-06-09 08:57:35 -06005685 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005686 // The result type of all of them is the same type as the (a) matrix operand.
5687 // The algorithm is to:
5688 // - break the matrix(es) into vectors
5689 // - smear any scalar to a vector
5690 // - do vector operations
5691 // - make a matrix out the vector results
5692 switch (op) {
5693 case spv::OpFAdd:
5694 case spv::OpFSub:
5695 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005696 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005697 case spv::OpFMul:
5698 {
5699 // one time set up...
5700 bool leftMat = builder.isMatrix(left);
5701 bool rightMat = builder.isMatrix(right);
5702 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5703 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5704 spv::Id scalarType = builder.getScalarTypeId(typeId);
5705 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5706 std::vector<spv::Id> results;
5707 spv::Id smearVec = spv::NoResult;
5708 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005709 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005710 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005711 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005712
5713 // do each vector op
5714 for (unsigned int c = 0; c < numCols; ++c) {
5715 std::vector<unsigned int> indexes;
5716 indexes.push_back(c);
5717 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5718 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005719 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005720 decorations.addNoContraction(builder, result);
5721 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005722 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005723 }
5724
5725 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005726 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005727 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005728 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005729 }
5730 default:
5731 assert(0);
5732 return spv::NoResult;
5733 }
5734}
5735
John Kessenichead86222018-03-28 18:01:20 -06005736spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005737 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005738{
5739 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005740 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005741 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005742 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5743 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005744
5745 switch (op) {
5746 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005747 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005748 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005749 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005750 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005751 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005752 unaryOp = spv::OpSNegate;
5753 break;
5754
5755 case glslang::EOpLogicalNot:
5756 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005757 unaryOp = spv::OpLogicalNot;
5758 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005759 case glslang::EOpBitwiseNot:
5760 unaryOp = spv::OpNot;
5761 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005762
John Kessenich140f3df2015-06-26 16:58:36 -06005763 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005764 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005765 break;
5766 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005767 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005768 break;
5769 case glslang::EOpTranspose:
5770 unaryOp = spv::OpTranspose;
5771 break;
5772
5773 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005774 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005775 break;
5776 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005777 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005778 break;
5779 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005780 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005781 break;
5782 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005783 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005784 break;
5785 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005786 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005787 break;
5788 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005789 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005790 break;
5791 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005792 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005793 break;
5794 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005795 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005796 break;
5797
5798 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005799 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005800 break;
5801 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005802 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005803 break;
5804 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005805 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005806 break;
5807 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005808 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005809 break;
5810 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005811 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005812 break;
5813 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005814 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005815 break;
5816
5817 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005818 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005819 break;
5820 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005821 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005822 break;
5823
5824 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005825 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005826 break;
5827 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005828 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005829 break;
5830 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005831 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005832 break;
5833 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005834 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005835 break;
5836 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005837 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005838 break;
5839 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005840 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005841 break;
5842
5843 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005844 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005845 break;
5846 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005847 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005848 break;
5849 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005850 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005851 break;
5852 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005853 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005854 break;
5855 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005856 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005857 break;
5858 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005859 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005860 break;
5861
5862 case glslang::EOpIsNan:
5863 unaryOp = spv::OpIsNan;
5864 break;
5865 case glslang::EOpIsInf:
5866 unaryOp = spv::OpIsInf;
5867 break;
LoopDawg592860c2016-06-09 08:57:35 -06005868 case glslang::EOpIsFinite:
5869 unaryOp = spv::OpIsFinite;
5870 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005871
Rex Xucbc426e2015-12-15 16:03:10 +08005872 case glslang::EOpFloatBitsToInt:
5873 case glslang::EOpFloatBitsToUint:
5874 case glslang::EOpIntBitsToFloat:
5875 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005876 case glslang::EOpDoubleBitsToInt64:
5877 case glslang::EOpDoubleBitsToUint64:
5878 case glslang::EOpInt64BitsToDouble:
5879 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005880 case glslang::EOpFloat16BitsToInt16:
5881 case glslang::EOpFloat16BitsToUint16:
5882 case glslang::EOpInt16BitsToFloat16:
5883 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005884 unaryOp = spv::OpBitcast;
5885 break;
5886
John Kessenich140f3df2015-06-26 16:58:36 -06005887 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005888 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005889 break;
5890 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005891 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005892 break;
5893 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005894 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005895 break;
5896 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005897 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005898 break;
5899 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005900 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005901 break;
5902 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005903 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005904 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005905#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005906 case glslang::EOpPackSnorm4x8:
5907 libCall = spv::GLSLstd450PackSnorm4x8;
5908 break;
5909 case glslang::EOpUnpackSnorm4x8:
5910 libCall = spv::GLSLstd450UnpackSnorm4x8;
5911 break;
5912 case glslang::EOpPackUnorm4x8:
5913 libCall = spv::GLSLstd450PackUnorm4x8;
5914 break;
5915 case glslang::EOpUnpackUnorm4x8:
5916 libCall = spv::GLSLstd450UnpackUnorm4x8;
5917 break;
5918 case glslang::EOpPackDouble2x32:
5919 libCall = spv::GLSLstd450PackDouble2x32;
5920 break;
5921 case glslang::EOpUnpackDouble2x32:
5922 libCall = spv::GLSLstd450UnpackDouble2x32;
5923 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005924#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005925
Rex Xu8ff43de2016-04-22 16:51:45 +08005926 case glslang::EOpPackInt2x32:
5927 case glslang::EOpUnpackInt2x32:
5928 case glslang::EOpPackUint2x32:
5929 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005930 case glslang::EOpPack16:
5931 case glslang::EOpPack32:
5932 case glslang::EOpPack64:
5933 case glslang::EOpUnpack32:
5934 case glslang::EOpUnpack16:
5935 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005936 case glslang::EOpPackInt2x16:
5937 case glslang::EOpUnpackInt2x16:
5938 case glslang::EOpPackUint2x16:
5939 case glslang::EOpUnpackUint2x16:
5940 case glslang::EOpPackInt4x16:
5941 case glslang::EOpUnpackInt4x16:
5942 case glslang::EOpPackUint4x16:
5943 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005944 case glslang::EOpPackFloat2x16:
5945 case glslang::EOpUnpackFloat2x16:
5946 unaryOp = spv::OpBitcast;
5947 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005948
John Kessenich140f3df2015-06-26 16:58:36 -06005949 case glslang::EOpDPdx:
5950 unaryOp = spv::OpDPdx;
5951 break;
5952 case glslang::EOpDPdy:
5953 unaryOp = spv::OpDPdy;
5954 break;
5955 case glslang::EOpFwidth:
5956 unaryOp = spv::OpFwidth;
5957 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005958
John Kessenich140f3df2015-06-26 16:58:36 -06005959 case glslang::EOpAny:
5960 unaryOp = spv::OpAny;
5961 break;
5962 case glslang::EOpAll:
5963 unaryOp = spv::OpAll;
5964 break;
5965
5966 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005967 if (isFloat)
5968 libCall = spv::GLSLstd450FAbs;
5969 else
5970 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005971 break;
5972 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005973 if (isFloat)
5974 libCall = spv::GLSLstd450FSign;
5975 else
5976 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005977 break;
5978
John Kessenicha28f7a72019-08-06 07:00:58 -06005979#ifndef GLSLANG_WEB
5980 case glslang::EOpDPdxFine:
5981 unaryOp = spv::OpDPdxFine;
5982 break;
5983 case glslang::EOpDPdyFine:
5984 unaryOp = spv::OpDPdyFine;
5985 break;
5986 case glslang::EOpFwidthFine:
5987 unaryOp = spv::OpFwidthFine;
5988 break;
5989 case glslang::EOpDPdxCoarse:
5990 unaryOp = spv::OpDPdxCoarse;
5991 break;
5992 case glslang::EOpDPdyCoarse:
5993 unaryOp = spv::OpDPdyCoarse;
5994 break;
5995 case glslang::EOpFwidthCoarse:
5996 unaryOp = spv::OpFwidthCoarse;
5997 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04005998 case glslang::EOpRayQueryProceed:
5999 unaryOp = spv::OpRayQueryProceedKHR;
6000 break;
6001 case glslang::EOpRayQueryGetRayTMin:
6002 unaryOp = spv::OpRayQueryGetRayTMinKHR;
6003 break;
6004 case glslang::EOpRayQueryGetRayFlags:
6005 unaryOp = spv::OpRayQueryGetRayFlagsKHR;
6006 break;
6007 case glslang::EOpRayQueryGetWorldRayOrigin:
6008 unaryOp = spv::OpRayQueryGetWorldRayOriginKHR;
6009 break;
6010 case glslang::EOpRayQueryGetWorldRayDirection:
6011 unaryOp = spv::OpRayQueryGetWorldRayDirectionKHR;
6012 break;
6013 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
6014 unaryOp = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
6015 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006016 case glslang::EOpInterpolateAtCentroid:
6017 if (typeProxy == glslang::EbtFloat16)
6018 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6019 libCall = spv::GLSLstd450InterpolateAtCentroid;
6020 break;
John Kessenichfc51d282015-08-19 13:34:18 -06006021 case glslang::EOpAtomicCounterIncrement:
6022 case glslang::EOpAtomicCounterDecrement:
6023 case glslang::EOpAtomicCounter:
6024 {
6025 // Handle all of the atomics in one place, in createAtomicOperation()
6026 std::vector<spv::Id> operands;
6027 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006028 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06006029 }
6030
John Kessenichfc51d282015-08-19 13:34:18 -06006031 case glslang::EOpBitFieldReverse:
6032 unaryOp = spv::OpBitReverse;
6033 break;
6034 case glslang::EOpBitCount:
6035 unaryOp = spv::OpBitCount;
6036 break;
6037 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006038 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006039 break;
6040 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006041 if (isUnsigned)
6042 libCall = spv::GLSLstd450FindUMsb;
6043 else
6044 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006045 break;
6046
Ian Romanickb3bd4022019-01-21 08:57:25 -08006047 case glslang::EOpCountLeadingZeros:
6048 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6049 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6050 unaryOp = spv::OpUCountLeadingZerosINTEL;
6051 break;
6052
6053 case glslang::EOpCountTrailingZeros:
6054 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6055 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6056 unaryOp = spv::OpUCountTrailingZerosINTEL;
6057 break;
6058
Rex Xu574ab042016-04-14 16:53:07 +08006059 case glslang::EOpBallot:
6060 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006061 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006062 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08006063 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08006064 case glslang::EOpMinInvocations:
6065 case glslang::EOpMaxInvocations:
6066 case glslang::EOpAddInvocations:
6067 case glslang::EOpMinInvocationsNonUniform:
6068 case glslang::EOpMaxInvocationsNonUniform:
6069 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006070 case glslang::EOpMinInvocationsInclusiveScan:
6071 case glslang::EOpMaxInvocationsInclusiveScan:
6072 case glslang::EOpAddInvocationsInclusiveScan:
6073 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6074 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6075 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6076 case glslang::EOpMinInvocationsExclusiveScan:
6077 case glslang::EOpMaxInvocationsExclusiveScan:
6078 case glslang::EOpAddInvocationsExclusiveScan:
6079 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6080 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6081 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08006082 {
6083 std::vector<spv::Id> operands;
6084 operands.push_back(operand);
6085 return createInvocationsOperation(op, typeId, operands, typeProxy);
6086 }
John Kessenich66011cb2018-03-06 16:12:04 -07006087 case glslang::EOpSubgroupAll:
6088 case glslang::EOpSubgroupAny:
6089 case glslang::EOpSubgroupAllEqual:
6090 case glslang::EOpSubgroupBroadcastFirst:
6091 case glslang::EOpSubgroupBallot:
6092 case glslang::EOpSubgroupInverseBallot:
6093 case glslang::EOpSubgroupBallotBitCount:
6094 case glslang::EOpSubgroupBallotInclusiveBitCount:
6095 case glslang::EOpSubgroupBallotExclusiveBitCount:
6096 case glslang::EOpSubgroupBallotFindLSB:
6097 case glslang::EOpSubgroupBallotFindMSB:
6098 case glslang::EOpSubgroupAdd:
6099 case glslang::EOpSubgroupMul:
6100 case glslang::EOpSubgroupMin:
6101 case glslang::EOpSubgroupMax:
6102 case glslang::EOpSubgroupAnd:
6103 case glslang::EOpSubgroupOr:
6104 case glslang::EOpSubgroupXor:
6105 case glslang::EOpSubgroupInclusiveAdd:
6106 case glslang::EOpSubgroupInclusiveMul:
6107 case glslang::EOpSubgroupInclusiveMin:
6108 case glslang::EOpSubgroupInclusiveMax:
6109 case glslang::EOpSubgroupInclusiveAnd:
6110 case glslang::EOpSubgroupInclusiveOr:
6111 case glslang::EOpSubgroupInclusiveXor:
6112 case glslang::EOpSubgroupExclusiveAdd:
6113 case glslang::EOpSubgroupExclusiveMul:
6114 case glslang::EOpSubgroupExclusiveMin:
6115 case glslang::EOpSubgroupExclusiveMax:
6116 case glslang::EOpSubgroupExclusiveAnd:
6117 case glslang::EOpSubgroupExclusiveOr:
6118 case glslang::EOpSubgroupExclusiveXor:
6119 case glslang::EOpSubgroupQuadSwapHorizontal:
6120 case glslang::EOpSubgroupQuadSwapVertical:
6121 case glslang::EOpSubgroupQuadSwapDiagonal: {
6122 std::vector<spv::Id> operands;
6123 operands.push_back(operand);
6124 return createSubgroupOperation(op, typeId, operands, typeProxy);
6125 }
Rex Xu9d93a232016-05-05 12:30:44 +08006126 case glslang::EOpMbcnt:
6127 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6128 libCall = spv::MbcntAMD;
6129 break;
6130
6131 case glslang::EOpCubeFaceIndex:
6132 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6133 libCall = spv::CubeFaceIndexAMD;
6134 break;
6135
6136 case glslang::EOpCubeFaceCoord:
6137 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6138 libCall = spv::CubeFaceCoordAMD;
6139 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006140 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006141 unaryOp = spv::OpGroupNonUniformPartitionNV;
6142 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006143 case glslang::EOpConstructReference:
6144 unaryOp = spv::OpBitcast;
6145 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006146#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006147
6148 case glslang::EOpCopyObject:
6149 unaryOp = spv::OpCopyObject;
6150 break;
6151
John Kessenich140f3df2015-06-26 16:58:36 -06006152 default:
6153 return 0;
6154 }
6155
6156 spv::Id id;
6157 if (libCall >= 0) {
6158 std::vector<spv::Id> args;
6159 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006160 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006161 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006162 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006163 }
John Kessenich140f3df2015-06-26 16:58:36 -06006164
John Kessenichb9197c82019-08-11 07:41:45 -06006165 decorations.addNoContraction(builder, id);
6166 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006167 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006168}
6169
John Kessenich7a53f762016-01-20 11:19:27 -07006170// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006171spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6172 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006173{
6174 // Handle unary operations vector by vector.
6175 // The result type is the same type as the original type.
6176 // The algorithm is to:
6177 // - break the matrix into vectors
6178 // - apply the operation to each vector
6179 // - make a matrix out the vector results
6180
6181 // get the types sorted out
6182 int numCols = builder.getNumColumns(operand);
6183 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006184 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6185 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006186 std::vector<spv::Id> results;
6187
6188 // do each vector op
6189 for (int c = 0; c < numCols; ++c) {
6190 std::vector<unsigned int> indexes;
6191 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006192 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6193 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006194 decorations.addNoContraction(builder, destVec);
6195 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006196 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006197 }
6198
6199 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006200 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006201 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006202 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006203}
6204
John Kessenichad7645f2018-06-04 19:11:25 -06006205// For converting integers where both the bitwidth and the signedness could
6206// change, but only do the width change here. The caller is still responsible
6207// for the signedness conversion.
6208spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006209{
John Kessenichad7645f2018-06-04 19:11:25 -06006210 // Get the result type width, based on the type to convert to.
6211 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006212 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006213 case glslang::EOpConvInt16ToUint8:
6214 case glslang::EOpConvIntToUint8:
6215 case glslang::EOpConvInt64ToUint8:
6216 case glslang::EOpConvUint16ToInt8:
6217 case glslang::EOpConvUintToInt8:
6218 case glslang::EOpConvUint64ToInt8:
6219 width = 8;
6220 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006221 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006222 case glslang::EOpConvIntToUint16:
6223 case glslang::EOpConvInt64ToUint16:
6224 case glslang::EOpConvUint8ToInt16:
6225 case glslang::EOpConvUintToInt16:
6226 case glslang::EOpConvUint64ToInt16:
6227 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006228 break;
6229 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006230 case glslang::EOpConvInt16ToUint:
6231 case glslang::EOpConvInt64ToUint:
6232 case glslang::EOpConvUint8ToInt:
6233 case glslang::EOpConvUint16ToInt:
6234 case glslang::EOpConvUint64ToInt:
6235 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006236 break;
6237 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006238 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006239 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006240 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006241 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006242 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006243 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006244 break;
6245
6246 default:
6247 assert(false && "Default missing");
6248 break;
6249 }
6250
John Kessenichad7645f2018-06-04 19:11:25 -06006251 // Get the conversion operation and result type,
6252 // based on the target width, but the source type.
6253 spv::Id type = spv::NoType;
6254 spv::Op convOp = spv::OpNop;
6255 switch(op) {
6256 case glslang::EOpConvInt8ToUint16:
6257 case glslang::EOpConvInt8ToUint:
6258 case glslang::EOpConvInt8ToUint64:
6259 case glslang::EOpConvInt16ToUint8:
6260 case glslang::EOpConvInt16ToUint:
6261 case glslang::EOpConvInt16ToUint64:
6262 case glslang::EOpConvIntToUint8:
6263 case glslang::EOpConvIntToUint16:
6264 case glslang::EOpConvIntToUint64:
6265 case glslang::EOpConvInt64ToUint8:
6266 case glslang::EOpConvInt64ToUint16:
6267 case glslang::EOpConvInt64ToUint:
6268 convOp = spv::OpSConvert;
6269 type = builder.makeIntType(width);
6270 break;
6271 default:
6272 convOp = spv::OpUConvert;
6273 type = builder.makeUintType(width);
6274 break;
6275 }
6276
John Kessenich66011cb2018-03-06 16:12:04 -07006277 if (vectorSize > 0)
6278 type = builder.makeVectorType(type, vectorSize);
6279
John Kessenichad7645f2018-06-04 19:11:25 -06006280 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006281}
6282
John Kessenichead86222018-03-28 18:01:20 -06006283spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6284 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006285{
6286 spv::Op convOp = spv::OpNop;
6287 spv::Id zero = 0;
6288 spv::Id one = 0;
6289
6290 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6291
6292 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006293 case glslang::EOpConvIntToBool:
6294 case glslang::EOpConvUintToBool:
6295 zero = builder.makeUintConstant(0);
6296 zero = makeSmearedConstant(zero, vectorSize);
6297 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006298 case glslang::EOpConvFloatToBool:
6299 zero = builder.makeFloatConstant(0.0F);
6300 zero = makeSmearedConstant(zero, vectorSize);
6301 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006302 case glslang::EOpConvBoolToFloat:
6303 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006304 zero = builder.makeFloatConstant(0.0F);
6305 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006306 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006307
John Kessenich140f3df2015-06-26 16:58:36 -06006308 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006309 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006310#ifndef GLSLANG_WEB
6311 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006312 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006313 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006314 } else
6315#endif
6316 {
6317 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006318 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006319 }
Rex Xucabbb782017-03-24 13:41:14 +08006320
John Kessenich140f3df2015-06-26 16:58:36 -06006321 convOp = spv::OpSelect;
6322 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006323
John Kessenich140f3df2015-06-26 16:58:36 -06006324 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006325 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006326#ifndef GLSLANG_WEB
6327 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006328 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006329 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006330 } else
6331#endif
6332 {
6333 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006334 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006335 }
Rex Xucabbb782017-03-24 13:41:14 +08006336
John Kessenich140f3df2015-06-26 16:58:36 -06006337 convOp = spv::OpSelect;
6338 break;
6339
John Kessenich66011cb2018-03-06 16:12:04 -07006340 case glslang::EOpConvInt8ToFloat16:
6341 case glslang::EOpConvInt8ToFloat:
6342 case glslang::EOpConvInt8ToDouble:
6343 case glslang::EOpConvInt16ToFloat16:
6344 case glslang::EOpConvInt16ToFloat:
6345 case glslang::EOpConvInt16ToDouble:
6346 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006347 case glslang::EOpConvIntToFloat:
6348 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006349 case glslang::EOpConvInt64ToFloat:
6350 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006351 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006352 convOp = spv::OpConvertSToF;
6353 break;
6354
John Kessenich66011cb2018-03-06 16:12:04 -07006355 case glslang::EOpConvUint8ToFloat16:
6356 case glslang::EOpConvUint8ToFloat:
6357 case glslang::EOpConvUint8ToDouble:
6358 case glslang::EOpConvUint16ToFloat16:
6359 case glslang::EOpConvUint16ToFloat:
6360 case glslang::EOpConvUint16ToDouble:
6361 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006362 case glslang::EOpConvUintToFloat:
6363 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006364 case glslang::EOpConvUint64ToFloat:
6365 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006366 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006367 convOp = spv::OpConvertUToF;
6368 break;
6369
John Kessenich66011cb2018-03-06 16:12:04 -07006370 case glslang::EOpConvFloat16ToInt8:
6371 case glslang::EOpConvFloatToInt8:
6372 case glslang::EOpConvDoubleToInt8:
6373 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006374 case glslang::EOpConvFloatToInt16:
6375 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006376 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006377 case glslang::EOpConvFloatToInt:
6378 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006379 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006380 case glslang::EOpConvFloatToInt64:
6381 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006382 convOp = spv::OpConvertFToS;
6383 break;
6384
John Kessenich66011cb2018-03-06 16:12:04 -07006385 case glslang::EOpConvUint8ToInt8:
6386 case glslang::EOpConvInt8ToUint8:
6387 case glslang::EOpConvUint16ToInt16:
6388 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006389 case glslang::EOpConvUintToInt:
6390 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006391 case glslang::EOpConvUint64ToInt64:
6392 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006393 if (builder.isInSpecConstCodeGenMode()) {
6394 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006395#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006396 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6397 zero = builder.makeUint8Constant(0);
6398 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006399 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006400 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6401 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006402 } else
6403#endif
6404 {
Rex Xucabbb782017-03-24 13:41:14 +08006405 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006406 }
qining189b2032016-04-12 23:16:20 -04006407 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006408 // Use OpIAdd, instead of OpBitcast to do the conversion when
6409 // generating for OpSpecConstantOp instruction.
6410 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6411 }
6412 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006413 convOp = spv::OpBitcast;
6414 break;
6415
John Kessenich66011cb2018-03-06 16:12:04 -07006416 case glslang::EOpConvFloat16ToUint8:
6417 case glslang::EOpConvFloatToUint8:
6418 case glslang::EOpConvDoubleToUint8:
6419 case glslang::EOpConvFloat16ToUint16:
6420 case glslang::EOpConvFloatToUint16:
6421 case glslang::EOpConvDoubleToUint16:
6422 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006423 case glslang::EOpConvFloatToUint:
6424 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006425 case glslang::EOpConvFloatToUint64:
6426 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006427 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006428 convOp = spv::OpConvertFToU;
6429 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006430
John Kessenich39697cd2019-08-08 10:35:51 -06006431#ifndef GLSLANG_WEB
6432 case glslang::EOpConvInt8ToBool:
6433 case glslang::EOpConvUint8ToBool:
6434 zero = builder.makeUint8Constant(0);
6435 zero = makeSmearedConstant(zero, vectorSize);
6436 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6437 case glslang::EOpConvInt16ToBool:
6438 case glslang::EOpConvUint16ToBool:
6439 zero = builder.makeUint16Constant(0);
6440 zero = makeSmearedConstant(zero, vectorSize);
6441 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6442 case glslang::EOpConvInt64ToBool:
6443 case glslang::EOpConvUint64ToBool:
6444 zero = builder.makeUint64Constant(0);
6445 zero = makeSmearedConstant(zero, vectorSize);
6446 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6447 case glslang::EOpConvDoubleToBool:
6448 zero = builder.makeDoubleConstant(0.0);
6449 zero = makeSmearedConstant(zero, vectorSize);
6450 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6451 case glslang::EOpConvFloat16ToBool:
6452 zero = builder.makeFloat16Constant(0.0F);
6453 zero = makeSmearedConstant(zero, vectorSize);
6454 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6455 case glslang::EOpConvBoolToDouble:
6456 convOp = spv::OpSelect;
6457 zero = builder.makeDoubleConstant(0.0);
6458 one = builder.makeDoubleConstant(1.0);
6459 break;
6460 case glslang::EOpConvBoolToFloat16:
6461 convOp = spv::OpSelect;
6462 zero = builder.makeFloat16Constant(0.0F);
6463 one = builder.makeFloat16Constant(1.0F);
6464 break;
6465 case glslang::EOpConvBoolToInt8:
6466 zero = builder.makeInt8Constant(0);
6467 one = builder.makeInt8Constant(1);
6468 convOp = spv::OpSelect;
6469 break;
6470 case glslang::EOpConvBoolToUint8:
6471 zero = builder.makeUint8Constant(0);
6472 one = builder.makeUint8Constant(1);
6473 convOp = spv::OpSelect;
6474 break;
6475 case glslang::EOpConvBoolToInt16:
6476 zero = builder.makeInt16Constant(0);
6477 one = builder.makeInt16Constant(1);
6478 convOp = spv::OpSelect;
6479 break;
6480 case glslang::EOpConvBoolToUint16:
6481 zero = builder.makeUint16Constant(0);
6482 one = builder.makeUint16Constant(1);
6483 convOp = spv::OpSelect;
6484 break;
6485 case glslang::EOpConvDoubleToFloat:
6486 case glslang::EOpConvFloatToDouble:
6487 case glslang::EOpConvDoubleToFloat16:
6488 case glslang::EOpConvFloat16ToDouble:
6489 case glslang::EOpConvFloatToFloat16:
6490 case glslang::EOpConvFloat16ToFloat:
6491 convOp = spv::OpFConvert;
6492 if (builder.isMatrixType(destType))
6493 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6494 break;
6495
John Kessenich66011cb2018-03-06 16:12:04 -07006496 case glslang::EOpConvInt8ToInt16:
6497 case glslang::EOpConvInt8ToInt:
6498 case glslang::EOpConvInt8ToInt64:
6499 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006500 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006501 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006502 case glslang::EOpConvIntToInt8:
6503 case glslang::EOpConvIntToInt16:
6504 case glslang::EOpConvIntToInt64:
6505 case glslang::EOpConvInt64ToInt8:
6506 case glslang::EOpConvInt64ToInt16:
6507 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006508 convOp = spv::OpSConvert;
6509 break;
6510
John Kessenich66011cb2018-03-06 16:12:04 -07006511 case glslang::EOpConvUint8ToUint16:
6512 case glslang::EOpConvUint8ToUint:
6513 case glslang::EOpConvUint8ToUint64:
6514 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006515 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006516 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006517 case glslang::EOpConvUintToUint8:
6518 case glslang::EOpConvUintToUint16:
6519 case glslang::EOpConvUintToUint64:
6520 case glslang::EOpConvUint64ToUint8:
6521 case glslang::EOpConvUint64ToUint16:
6522 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006523 convOp = spv::OpUConvert;
6524 break;
6525
John Kessenich66011cb2018-03-06 16:12:04 -07006526 case glslang::EOpConvInt8ToUint16:
6527 case glslang::EOpConvInt8ToUint:
6528 case glslang::EOpConvInt8ToUint64:
6529 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006530 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006531 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006532 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006533 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006534 case glslang::EOpConvIntToUint64:
6535 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006536 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006537 case glslang::EOpConvInt64ToUint:
6538 case glslang::EOpConvUint8ToInt16:
6539 case glslang::EOpConvUint8ToInt:
6540 case glslang::EOpConvUint8ToInt64:
6541 case glslang::EOpConvUint16ToInt8:
6542 case glslang::EOpConvUint16ToInt:
6543 case glslang::EOpConvUint16ToInt64:
6544 case glslang::EOpConvUintToInt8:
6545 case glslang::EOpConvUintToInt16:
6546 case glslang::EOpConvUintToInt64:
6547 case glslang::EOpConvUint64ToInt8:
6548 case glslang::EOpConvUint64ToInt16:
6549 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006550 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006551 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006552
6553 if (builder.isInSpecConstCodeGenMode()) {
6554 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006555 switch(op) {
6556 case glslang::EOpConvInt16ToUint8:
6557 case glslang::EOpConvIntToUint8:
6558 case glslang::EOpConvInt64ToUint8:
6559 case glslang::EOpConvUint16ToInt8:
6560 case glslang::EOpConvUintToInt8:
6561 case glslang::EOpConvUint64ToInt8:
6562 zero = builder.makeUint8Constant(0);
6563 break;
6564 case glslang::EOpConvInt8ToUint16:
6565 case glslang::EOpConvIntToUint16:
6566 case glslang::EOpConvInt64ToUint16:
6567 case glslang::EOpConvUint8ToInt16:
6568 case glslang::EOpConvUintToInt16:
6569 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006570 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006571 break;
6572 case glslang::EOpConvInt8ToUint:
6573 case glslang::EOpConvInt16ToUint:
6574 case glslang::EOpConvInt64ToUint:
6575 case glslang::EOpConvUint8ToInt:
6576 case glslang::EOpConvUint16ToInt:
6577 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006578 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006579 break;
6580 case glslang::EOpConvInt8ToUint64:
6581 case glslang::EOpConvInt16ToUint64:
6582 case glslang::EOpConvIntToUint64:
6583 case glslang::EOpConvUint8ToInt64:
6584 case glslang::EOpConvUint16ToInt64:
6585 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006586 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006587 break;
6588 default:
6589 assert(false && "Default missing");
6590 break;
6591 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006592 zero = makeSmearedConstant(zero, vectorSize);
6593 // Use OpIAdd, instead of OpBitcast to do the conversion when
6594 // generating for OpSpecConstantOp instruction.
6595 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6596 }
6597 // For normal run-time conversion instruction, use OpBitcast.
6598 convOp = spv::OpBitcast;
6599 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006600 case glslang::EOpConvUint64ToPtr:
6601 convOp = spv::OpConvertUToPtr;
6602 break;
6603 case glslang::EOpConvPtrToUint64:
6604 convOp = spv::OpConvertPtrToU;
6605 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006606 case glslang::EOpConvPtrToUvec2:
6607 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006608 if (builder.isVector(operand))
6609 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6610 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006611 convOp = spv::OpBitcast;
6612 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006613#endif
6614
John Kessenich140f3df2015-06-26 16:58:36 -06006615 default:
6616 break;
6617 }
6618
6619 spv::Id result = 0;
6620 if (convOp == spv::OpNop)
6621 return result;
6622
6623 if (convOp == spv::OpSelect) {
6624 zero = makeSmearedConstant(zero, vectorSize);
6625 one = makeSmearedConstant(one, vectorSize);
6626 result = builder.createTriOp(convOp, destType, operand, one, zero);
6627 } else
6628 result = builder.createUnaryOp(convOp, destType, operand);
6629
John Kessenichead86222018-03-28 18:01:20 -06006630 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006631 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006632 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006633}
6634
6635spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6636{
6637 if (vectorSize == 0)
6638 return constant;
6639
6640 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6641 std::vector<spv::Id> components;
6642 for (int c = 0; c < vectorSize; ++c)
6643 components.push_back(constant);
6644 return builder.makeCompositeConstant(vectorTypeId, components);
6645}
6646
John Kessenich426394d2015-07-23 10:22:48 -06006647// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006648spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6649 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6650 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006651{
6652 spv::Op opCode = spv::OpNop;
6653
6654 switch (op) {
6655 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006656 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006657 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006658 opCode = spv::OpAtomicIAdd;
6659 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006660 case glslang::EOpAtomicCounterSubtract:
6661 opCode = spv::OpAtomicISub;
6662 break;
John Kessenich426394d2015-07-23 10:22:48 -06006663 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006664 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006665 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006666 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6667 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006668 break;
6669 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006670 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006671 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006672 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6673 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006674 break;
6675 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006676 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006677 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006678 opCode = spv::OpAtomicAnd;
6679 break;
6680 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006681 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006682 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006683 opCode = spv::OpAtomicOr;
6684 break;
6685 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006686 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006687 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006688 opCode = spv::OpAtomicXor;
6689 break;
6690 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006691 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006692 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006693 opCode = spv::OpAtomicExchange;
6694 break;
6695 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006696 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006697 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006698 opCode = spv::OpAtomicCompareExchange;
6699 break;
6700 case glslang::EOpAtomicCounterIncrement:
6701 opCode = spv::OpAtomicIIncrement;
6702 break;
6703 case glslang::EOpAtomicCounterDecrement:
6704 opCode = spv::OpAtomicIDecrement;
6705 break;
6706 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006707 case glslang::EOpImageAtomicLoad:
6708 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006709 opCode = spv::OpAtomicLoad;
6710 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006711 case glslang::EOpAtomicStore:
6712 case glslang::EOpImageAtomicStore:
6713 opCode = spv::OpAtomicStore;
6714 break;
John Kessenich426394d2015-07-23 10:22:48 -06006715 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006716 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006717 break;
6718 }
6719
Rex Xue8fe8b02017-09-26 15:42:56 +08006720 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6721 builder.addCapability(spv::CapabilityInt64Atomics);
6722
John Kessenich426394d2015-07-23 10:22:48 -06006723 // Sort out the operands
6724 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006725 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006726 // - compare-exchange swaps the value and comparator
6727 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006728 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006729 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6730 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6731 spv::Id scopeId;
6732 if (glslangIntermediate->usingVulkanMemoryModel()) {
6733 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6734 } else {
6735 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6736 }
6737 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006738 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6739 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006740 spv::MemorySemanticsVolatileMask :
6741 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006742 spv::Id semanticsId2 = semanticsId;
6743
6744 pointerId = operands[0];
6745 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6746 // no additional operands
6747 } else if (opCode == spv::OpAtomicCompareExchange) {
6748 compareId = operands[1];
6749 valueId = operands[2];
6750 if (operands.size() > 3) {
6751 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006752 semanticsId = builder.makeUintConstant(
6753 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6754 semanticsId2 = builder.makeUintConstant(
6755 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006756 }
6757 } else if (opCode == spv::OpAtomicLoad) {
6758 if (operands.size() > 1) {
6759 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006760 semanticsId = builder.makeUintConstant(
6761 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006762 }
6763 } else {
6764 // atomic store or RMW
6765 valueId = operands[1];
6766 if (operands.size() > 2) {
6767 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006768 semanticsId = builder.makeUintConstant
6769 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006770 }
Rex Xu04db3f52015-09-16 11:44:02 +08006771 }
John Kessenich426394d2015-07-23 10:22:48 -06006772
Jeff Bolz36831c92018-09-05 10:11:41 -05006773 // Check for capabilities
6774 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006775 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6776 spv::MemorySemanticsMakeVisibleKHRMask |
6777 spv::MemorySemanticsOutputMemoryKHRMask |
6778 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006779 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6780 }
John Kessenich426394d2015-07-23 10:22:48 -06006781
Jeff Bolz36831c92018-09-05 10:11:41 -05006782 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6783 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6784 }
John Kessenich48d6e792017-10-06 21:21:48 -06006785
Jeff Bolz36831c92018-09-05 10:11:41 -05006786 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6787 spvAtomicOperands.push_back(pointerId);
6788 spvAtomicOperands.push_back(scopeId);
6789 spvAtomicOperands.push_back(semanticsId);
6790 if (opCode == spv::OpAtomicCompareExchange) {
6791 spvAtomicOperands.push_back(semanticsId2);
6792 spvAtomicOperands.push_back(valueId);
6793 spvAtomicOperands.push_back(compareId);
6794 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6795 spvAtomicOperands.push_back(valueId);
6796 }
John Kessenich48d6e792017-10-06 21:21:48 -06006797
Jeff Bolz36831c92018-09-05 10:11:41 -05006798 if (opCode == spv::OpAtomicStore) {
6799 builder.createNoResultOp(opCode, spvAtomicOperands);
6800 return 0;
6801 } else {
6802 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6803
6804 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6805 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6806 if (op == glslang::EOpAtomicCounterDecrement)
6807 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6808
6809 return resultId;
6810 }
John Kessenich426394d2015-07-23 10:22:48 -06006811}
6812
John Kessenich91cef522016-05-05 16:45:40 -06006813// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07006814spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
6815 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006816{
John Kessenich66011cb2018-03-06 16:12:04 -07006817 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6818 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006819
Rex Xu51596642016-09-21 18:56:12 +08006820 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006821 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006822 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6823
chaocf200da82016-12-20 12:44:35 -08006824 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6825 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006826 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6827 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006828 } else if (op == glslang::EOpAnyInvocation ||
6829 op == glslang::EOpAllInvocations ||
6830 op == glslang::EOpAllInvocationsEqual) {
6831 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6832 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006833 } else {
6834 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006835 if (op == glslang::EOpMinInvocationsNonUniform ||
6836 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006837 op == glslang::EOpAddInvocationsNonUniform ||
6838 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6839 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6840 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6841 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6842 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6843 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006844 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006845
Rex Xu430ef402016-10-14 17:22:23 +08006846 switch (op) {
6847 case glslang::EOpMinInvocations:
6848 case glslang::EOpMaxInvocations:
6849 case glslang::EOpAddInvocations:
6850 case glslang::EOpMinInvocationsNonUniform:
6851 case glslang::EOpMaxInvocationsNonUniform:
6852 case glslang::EOpAddInvocationsNonUniform:
6853 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006854 break;
6855 case glslang::EOpMinInvocationsInclusiveScan:
6856 case glslang::EOpMaxInvocationsInclusiveScan:
6857 case glslang::EOpAddInvocationsInclusiveScan:
6858 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6859 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6860 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6861 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006862 break;
6863 case glslang::EOpMinInvocationsExclusiveScan:
6864 case glslang::EOpMaxInvocationsExclusiveScan:
6865 case glslang::EOpAddInvocationsExclusiveScan:
6866 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6867 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6868 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6869 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006870 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006871 default:
6872 break;
Rex Xu430ef402016-10-14 17:22:23 +08006873 }
John Kessenich149afc32018-08-14 13:31:43 -06006874 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6875 spvGroupOperands.push_back(scope);
6876 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006877 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006878 spvGroupOperands.push_back(groupOp);
6879 }
Rex Xu51596642016-09-21 18:56:12 +08006880 }
6881
John Kessenich149afc32018-08-14 13:31:43 -06006882 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6883 spv::IdImmediate op = { true, *opIt };
6884 spvGroupOperands.push_back(op);
6885 }
John Kessenich91cef522016-05-05 16:45:40 -06006886
6887 switch (op) {
6888 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006889 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006890 break;
John Kessenich91cef522016-05-05 16:45:40 -06006891 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006892 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006893 break;
John Kessenich91cef522016-05-05 16:45:40 -06006894 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006895 opCode = spv::OpSubgroupAllEqualKHR;
6896 break;
Rex Xu51596642016-09-21 18:56:12 +08006897 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006898 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006899 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006900 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006901 break;
6902 case glslang::EOpReadFirstInvocation:
6903 opCode = spv::OpSubgroupFirstInvocationKHR;
6904 break;
6905 case glslang::EOpBallot:
6906 {
6907 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6908 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6909 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6910 //
6911 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6912 //
6913 spv::Id uintType = builder.makeUintType(32);
6914 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6915 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6916
6917 std::vector<spv::Id> components;
6918 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6919 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6920
6921 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6922 return builder.createUnaryOp(spv::OpBitcast, typeId,
6923 builder.createCompositeConstruct(uvec2Type, components));
6924 }
6925
Rex Xu9d93a232016-05-05 12:30:44 +08006926 case glslang::EOpMinInvocations:
6927 case glslang::EOpMaxInvocations:
6928 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006929 case glslang::EOpMinInvocationsInclusiveScan:
6930 case glslang::EOpMaxInvocationsInclusiveScan:
6931 case glslang::EOpAddInvocationsInclusiveScan:
6932 case glslang::EOpMinInvocationsExclusiveScan:
6933 case glslang::EOpMaxInvocationsExclusiveScan:
6934 case glslang::EOpAddInvocationsExclusiveScan:
6935 if (op == glslang::EOpMinInvocations ||
6936 op == glslang::EOpMinInvocationsInclusiveScan ||
6937 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006938 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006939 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006940 else {
6941 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006942 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006943 else
Rex Xu51596642016-09-21 18:56:12 +08006944 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006945 }
Rex Xu430ef402016-10-14 17:22:23 +08006946 } else if (op == glslang::EOpMaxInvocations ||
6947 op == glslang::EOpMaxInvocationsInclusiveScan ||
6948 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006949 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006950 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006951 else {
6952 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006953 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006954 else
Rex Xu51596642016-09-21 18:56:12 +08006955 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006956 }
6957 } else {
6958 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006959 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006960 else
Rex Xu51596642016-09-21 18:56:12 +08006961 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006962 }
6963
Rex Xu2bbbe062016-08-23 15:41:05 +08006964 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006965 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006966
6967 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006968 case glslang::EOpMinInvocationsNonUniform:
6969 case glslang::EOpMaxInvocationsNonUniform:
6970 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006971 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6972 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6973 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6974 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6975 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6976 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6977 if (op == glslang::EOpMinInvocationsNonUniform ||
6978 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6979 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006980 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006981 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006982 else {
6983 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006984 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006985 else
Rex Xu51596642016-09-21 18:56:12 +08006986 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006987 }
6988 }
Rex Xu430ef402016-10-14 17:22:23 +08006989 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6990 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6991 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006992 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006993 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006994 else {
6995 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006996 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006997 else
Rex Xu51596642016-09-21 18:56:12 +08006998 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006999 }
7000 }
7001 else {
7002 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007003 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007004 else
Rex Xu51596642016-09-21 18:56:12 +08007005 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007006 }
7007
Rex Xu2bbbe062016-08-23 15:41:05 +08007008 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007009 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007010
7011 break;
John Kessenich91cef522016-05-05 16:45:40 -06007012 default:
7013 logger->missingFunctionality("invocation operation");
7014 return spv::NoResult;
7015 }
Rex Xu51596642016-09-21 18:56:12 +08007016
7017 assert(opCode != spv::OpNop);
7018 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06007019}
7020
Rex Xu2bbbe062016-08-23 15:41:05 +08007021// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06007022spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
7023 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08007024{
7025 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
7026 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08007027 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08007028 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07007029 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
7030 op == spv::OpGroupSMinNonUniformAMD ||
7031 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
7032 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08007033 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
7034
7035 // Handle group invocation operations scalar by scalar.
7036 // The result type is the same type as the original type.
7037 // The algorithm is to:
7038 // - break the vector into scalars
7039 // - apply the operation to each scalar
7040 // - make a vector out the scalar results
7041
7042 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08007043 int numComponents = builder.getNumComponents(operands[0]);
7044 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08007045 std::vector<spv::Id> results;
7046
7047 // do each scalar op
7048 for (int comp = 0; comp < numComponents; ++comp) {
7049 std::vector<unsigned int> indexes;
7050 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06007051 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
7052 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08007053 if (op == spv::OpSubgroupReadInvocationKHR) {
7054 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007055 spv::IdImmediate operand = { true, operands[1] };
7056 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08007057 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06007058 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7059 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08007060 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007061 spv::IdImmediate operand = { true, operands[1] };
7062 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08007063 } else {
John Kessenich149afc32018-08-14 13:31:43 -06007064 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7065 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06007066 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007067 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08007068 spvGroupOperands.push_back(scalar);
7069 }
Rex Xu2bbbe062016-08-23 15:41:05 +08007070
Rex Xub7072052016-09-26 15:53:40 +08007071 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08007072 }
7073
7074 // put the pieces together
7075 return builder.createCompositeConstruct(typeId, results);
7076}
Rex Xu2bbbe062016-08-23 15:41:05 +08007077
John Kessenich66011cb2018-03-06 16:12:04 -07007078// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06007079spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
7080 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07007081{
7082 // Add the required capabilities.
7083 switch (op) {
7084 case glslang::EOpSubgroupElect:
7085 builder.addCapability(spv::CapabilityGroupNonUniform);
7086 break;
7087 case glslang::EOpSubgroupAll:
7088 case glslang::EOpSubgroupAny:
7089 case glslang::EOpSubgroupAllEqual:
7090 builder.addCapability(spv::CapabilityGroupNonUniform);
7091 builder.addCapability(spv::CapabilityGroupNonUniformVote);
7092 break;
7093 case glslang::EOpSubgroupBroadcast:
7094 case glslang::EOpSubgroupBroadcastFirst:
7095 case glslang::EOpSubgroupBallot:
7096 case glslang::EOpSubgroupInverseBallot:
7097 case glslang::EOpSubgroupBallotBitExtract:
7098 case glslang::EOpSubgroupBallotBitCount:
7099 case glslang::EOpSubgroupBallotInclusiveBitCount:
7100 case glslang::EOpSubgroupBallotExclusiveBitCount:
7101 case glslang::EOpSubgroupBallotFindLSB:
7102 case glslang::EOpSubgroupBallotFindMSB:
7103 builder.addCapability(spv::CapabilityGroupNonUniform);
7104 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
7105 break;
7106 case glslang::EOpSubgroupShuffle:
7107 case glslang::EOpSubgroupShuffleXor:
7108 builder.addCapability(spv::CapabilityGroupNonUniform);
7109 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
7110 break;
7111 case glslang::EOpSubgroupShuffleUp:
7112 case glslang::EOpSubgroupShuffleDown:
7113 builder.addCapability(spv::CapabilityGroupNonUniform);
7114 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
7115 break;
7116 case glslang::EOpSubgroupAdd:
7117 case glslang::EOpSubgroupMul:
7118 case glslang::EOpSubgroupMin:
7119 case glslang::EOpSubgroupMax:
7120 case glslang::EOpSubgroupAnd:
7121 case glslang::EOpSubgroupOr:
7122 case glslang::EOpSubgroupXor:
7123 case glslang::EOpSubgroupInclusiveAdd:
7124 case glslang::EOpSubgroupInclusiveMul:
7125 case glslang::EOpSubgroupInclusiveMin:
7126 case glslang::EOpSubgroupInclusiveMax:
7127 case glslang::EOpSubgroupInclusiveAnd:
7128 case glslang::EOpSubgroupInclusiveOr:
7129 case glslang::EOpSubgroupInclusiveXor:
7130 case glslang::EOpSubgroupExclusiveAdd:
7131 case glslang::EOpSubgroupExclusiveMul:
7132 case glslang::EOpSubgroupExclusiveMin:
7133 case glslang::EOpSubgroupExclusiveMax:
7134 case glslang::EOpSubgroupExclusiveAnd:
7135 case glslang::EOpSubgroupExclusiveOr:
7136 case glslang::EOpSubgroupExclusiveXor:
7137 builder.addCapability(spv::CapabilityGroupNonUniform);
7138 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
7139 break;
7140 case glslang::EOpSubgroupClusteredAdd:
7141 case glslang::EOpSubgroupClusteredMul:
7142 case glslang::EOpSubgroupClusteredMin:
7143 case glslang::EOpSubgroupClusteredMax:
7144 case glslang::EOpSubgroupClusteredAnd:
7145 case glslang::EOpSubgroupClusteredOr:
7146 case glslang::EOpSubgroupClusteredXor:
7147 builder.addCapability(spv::CapabilityGroupNonUniform);
7148 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7149 break;
7150 case glslang::EOpSubgroupQuadBroadcast:
7151 case glslang::EOpSubgroupQuadSwapHorizontal:
7152 case glslang::EOpSubgroupQuadSwapVertical:
7153 case glslang::EOpSubgroupQuadSwapDiagonal:
7154 builder.addCapability(spv::CapabilityGroupNonUniform);
7155 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7156 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007157 case glslang::EOpSubgroupPartitionedAdd:
7158 case glslang::EOpSubgroupPartitionedMul:
7159 case glslang::EOpSubgroupPartitionedMin:
7160 case glslang::EOpSubgroupPartitionedMax:
7161 case glslang::EOpSubgroupPartitionedAnd:
7162 case glslang::EOpSubgroupPartitionedOr:
7163 case glslang::EOpSubgroupPartitionedXor:
7164 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7165 case glslang::EOpSubgroupPartitionedInclusiveMul:
7166 case glslang::EOpSubgroupPartitionedInclusiveMin:
7167 case glslang::EOpSubgroupPartitionedInclusiveMax:
7168 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7169 case glslang::EOpSubgroupPartitionedInclusiveOr:
7170 case glslang::EOpSubgroupPartitionedInclusiveXor:
7171 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7172 case glslang::EOpSubgroupPartitionedExclusiveMul:
7173 case glslang::EOpSubgroupPartitionedExclusiveMin:
7174 case glslang::EOpSubgroupPartitionedExclusiveMax:
7175 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7176 case glslang::EOpSubgroupPartitionedExclusiveOr:
7177 case glslang::EOpSubgroupPartitionedExclusiveXor:
7178 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7179 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7180 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007181 default: assert(0 && "Unhandled subgroup operation!");
7182 }
7183
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007184
7185 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7186 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007187 const bool isBool = typeProxy == glslang::EbtBool;
7188
7189 spv::Op opCode = spv::OpNop;
7190
7191 // Figure out which opcode to use.
7192 switch (op) {
7193 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7194 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7195 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7196 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7197 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7198 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7199 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7200 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7201 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7202 case glslang::EOpSubgroupBallotBitCount:
7203 case glslang::EOpSubgroupBallotInclusiveBitCount:
7204 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7205 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7206 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7207 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7208 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7209 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7210 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7211 case glslang::EOpSubgroupAdd:
7212 case glslang::EOpSubgroupInclusiveAdd:
7213 case glslang::EOpSubgroupExclusiveAdd:
7214 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007215 case glslang::EOpSubgroupPartitionedAdd:
7216 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7217 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007218 if (isFloat) {
7219 opCode = spv::OpGroupNonUniformFAdd;
7220 } else {
7221 opCode = spv::OpGroupNonUniformIAdd;
7222 }
7223 break;
7224 case glslang::EOpSubgroupMul:
7225 case glslang::EOpSubgroupInclusiveMul:
7226 case glslang::EOpSubgroupExclusiveMul:
7227 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007228 case glslang::EOpSubgroupPartitionedMul:
7229 case glslang::EOpSubgroupPartitionedInclusiveMul:
7230 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007231 if (isFloat) {
7232 opCode = spv::OpGroupNonUniformFMul;
7233 } else {
7234 opCode = spv::OpGroupNonUniformIMul;
7235 }
7236 break;
7237 case glslang::EOpSubgroupMin:
7238 case glslang::EOpSubgroupInclusiveMin:
7239 case glslang::EOpSubgroupExclusiveMin:
7240 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007241 case glslang::EOpSubgroupPartitionedMin:
7242 case glslang::EOpSubgroupPartitionedInclusiveMin:
7243 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007244 if (isFloat) {
7245 opCode = spv::OpGroupNonUniformFMin;
7246 } else if (isUnsigned) {
7247 opCode = spv::OpGroupNonUniformUMin;
7248 } else {
7249 opCode = spv::OpGroupNonUniformSMin;
7250 }
7251 break;
7252 case glslang::EOpSubgroupMax:
7253 case glslang::EOpSubgroupInclusiveMax:
7254 case glslang::EOpSubgroupExclusiveMax:
7255 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007256 case glslang::EOpSubgroupPartitionedMax:
7257 case glslang::EOpSubgroupPartitionedInclusiveMax:
7258 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007259 if (isFloat) {
7260 opCode = spv::OpGroupNonUniformFMax;
7261 } else if (isUnsigned) {
7262 opCode = spv::OpGroupNonUniformUMax;
7263 } else {
7264 opCode = spv::OpGroupNonUniformSMax;
7265 }
7266 break;
7267 case glslang::EOpSubgroupAnd:
7268 case glslang::EOpSubgroupInclusiveAnd:
7269 case glslang::EOpSubgroupExclusiveAnd:
7270 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007271 case glslang::EOpSubgroupPartitionedAnd:
7272 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7273 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007274 if (isBool) {
7275 opCode = spv::OpGroupNonUniformLogicalAnd;
7276 } else {
7277 opCode = spv::OpGroupNonUniformBitwiseAnd;
7278 }
7279 break;
7280 case glslang::EOpSubgroupOr:
7281 case glslang::EOpSubgroupInclusiveOr:
7282 case glslang::EOpSubgroupExclusiveOr:
7283 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007284 case glslang::EOpSubgroupPartitionedOr:
7285 case glslang::EOpSubgroupPartitionedInclusiveOr:
7286 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007287 if (isBool) {
7288 opCode = spv::OpGroupNonUniformLogicalOr;
7289 } else {
7290 opCode = spv::OpGroupNonUniformBitwiseOr;
7291 }
7292 break;
7293 case glslang::EOpSubgroupXor:
7294 case glslang::EOpSubgroupInclusiveXor:
7295 case glslang::EOpSubgroupExclusiveXor:
7296 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007297 case glslang::EOpSubgroupPartitionedXor:
7298 case glslang::EOpSubgroupPartitionedInclusiveXor:
7299 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007300 if (isBool) {
7301 opCode = spv::OpGroupNonUniformLogicalXor;
7302 } else {
7303 opCode = spv::OpGroupNonUniformBitwiseXor;
7304 }
7305 break;
7306 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7307 case glslang::EOpSubgroupQuadSwapHorizontal:
7308 case glslang::EOpSubgroupQuadSwapVertical:
7309 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7310 default: assert(0 && "Unhandled subgroup operation!");
7311 }
7312
John Kessenich149afc32018-08-14 13:31:43 -06007313 // get the right Group Operation
7314 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007315 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007316 default:
7317 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007318 case glslang::EOpSubgroupBallotBitCount:
7319 case glslang::EOpSubgroupAdd:
7320 case glslang::EOpSubgroupMul:
7321 case glslang::EOpSubgroupMin:
7322 case glslang::EOpSubgroupMax:
7323 case glslang::EOpSubgroupAnd:
7324 case glslang::EOpSubgroupOr:
7325 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007326 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007327 break;
7328 case glslang::EOpSubgroupBallotInclusiveBitCount:
7329 case glslang::EOpSubgroupInclusiveAdd:
7330 case glslang::EOpSubgroupInclusiveMul:
7331 case glslang::EOpSubgroupInclusiveMin:
7332 case glslang::EOpSubgroupInclusiveMax:
7333 case glslang::EOpSubgroupInclusiveAnd:
7334 case glslang::EOpSubgroupInclusiveOr:
7335 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007336 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007337 break;
7338 case glslang::EOpSubgroupBallotExclusiveBitCount:
7339 case glslang::EOpSubgroupExclusiveAdd:
7340 case glslang::EOpSubgroupExclusiveMul:
7341 case glslang::EOpSubgroupExclusiveMin:
7342 case glslang::EOpSubgroupExclusiveMax:
7343 case glslang::EOpSubgroupExclusiveAnd:
7344 case glslang::EOpSubgroupExclusiveOr:
7345 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007346 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007347 break;
7348 case glslang::EOpSubgroupClusteredAdd:
7349 case glslang::EOpSubgroupClusteredMul:
7350 case glslang::EOpSubgroupClusteredMin:
7351 case glslang::EOpSubgroupClusteredMax:
7352 case glslang::EOpSubgroupClusteredAnd:
7353 case glslang::EOpSubgroupClusteredOr:
7354 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007355 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007356 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007357 case glslang::EOpSubgroupPartitionedAdd:
7358 case glslang::EOpSubgroupPartitionedMul:
7359 case glslang::EOpSubgroupPartitionedMin:
7360 case glslang::EOpSubgroupPartitionedMax:
7361 case glslang::EOpSubgroupPartitionedAnd:
7362 case glslang::EOpSubgroupPartitionedOr:
7363 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007364 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007365 break;
7366 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7367 case glslang::EOpSubgroupPartitionedInclusiveMul:
7368 case glslang::EOpSubgroupPartitionedInclusiveMin:
7369 case glslang::EOpSubgroupPartitionedInclusiveMax:
7370 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7371 case glslang::EOpSubgroupPartitionedInclusiveOr:
7372 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007373 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007374 break;
7375 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7376 case glslang::EOpSubgroupPartitionedExclusiveMul:
7377 case glslang::EOpSubgroupPartitionedExclusiveMin:
7378 case glslang::EOpSubgroupPartitionedExclusiveMax:
7379 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7380 case glslang::EOpSubgroupPartitionedExclusiveOr:
7381 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007382 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007383 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007384 }
7385
John Kessenich149afc32018-08-14 13:31:43 -06007386 // build the instruction
7387 std::vector<spv::IdImmediate> spvGroupOperands;
7388
7389 // Every operation begins with the Execution Scope operand.
7390 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7391 spvGroupOperands.push_back(executionScope);
7392
7393 // Next, for all operations that use a Group Operation, push that as an operand.
7394 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007395 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007396 spvGroupOperands.push_back(groupOperand);
7397 }
7398
John Kessenich66011cb2018-03-06 16:12:04 -07007399 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007400 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7401 spv::IdImmediate operand = { true, *opIt };
7402 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007403 }
7404
7405 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007406 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007407 switch (op) {
7408 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007409 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7410 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7411 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7412 }
7413 if (directionId != spv::NoResult) {
7414 spv::IdImmediate direction = { true, directionId };
7415 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007416 }
7417
7418 return builder.createOp(opCode, typeId, spvGroupOperands);
7419}
7420
John Kessenich8985fc92020-03-03 10:25:07 -07007421spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7422 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007423{
John Kessenich66011cb2018-03-06 16:12:04 -07007424 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7425 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007426
John Kessenich140f3df2015-06-26 16:58:36 -06007427 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007428 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007429 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007430 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007431 spv::Id typeId0 = 0;
7432 if (consumedOperands > 0)
7433 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007434 spv::Id typeId1 = 0;
7435 if (consumedOperands > 1)
7436 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007437 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007438
7439 switch (op) {
7440 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007441 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007442 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007443 else if (isUnsigned)
7444 libCall = spv::GLSLstd450UMin;
7445 else
7446 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007447 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007448 break;
7449 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007450 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007451 break;
7452 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007453 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007454 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007455 else if (isUnsigned)
7456 libCall = spv::GLSLstd450UMax;
7457 else
7458 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007459 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007460 break;
7461 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007462 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007463 break;
7464 case glslang::EOpDot:
7465 opCode = spv::OpDot;
7466 break;
7467 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007468 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007469 break;
7470
7471 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007472 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007473 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007474 else if (isUnsigned)
7475 libCall = spv::GLSLstd450UClamp;
7476 else
7477 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007478 builder.promoteScalar(precision, operands.front(), operands[1]);
7479 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007480 break;
7481 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007482 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7483 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007484 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007485 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007486 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007487 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007488 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007489 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007490 break;
7491 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007492 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007493 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007494 break;
7495 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007496 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007497 builder.promoteScalar(precision, operands[0], operands[2]);
7498 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007499 break;
7500
7501 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007502 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007503 break;
7504 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007505 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007506 break;
7507 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007508 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007509 break;
7510 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007511 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007512 break;
7513 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007514 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007515 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007516 case glslang::EOpBarrier:
7517 {
7518 // This is for the extended controlBarrier function, with four operands.
7519 // The unextended barrier() goes through createNoArgOperation.
7520 assert(operands.size() == 4);
7521 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7522 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7523 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007524 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7525 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007526 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7527 spv::MemorySemanticsMakeVisibleKHRMask |
7528 spv::MemorySemanticsOutputMemoryKHRMask |
7529 spv::MemorySemanticsVolatileMask)) {
7530 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7531 }
John Kessenich8985fc92020-03-03 10:25:07 -07007532 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7533 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007534 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7535 }
7536 return 0;
7537 }
7538 break;
7539 case glslang::EOpMemoryBarrier:
7540 {
7541 // This is for the extended memoryBarrier function, with three operands.
7542 // The unextended memoryBarrier() goes through createNoArgOperation.
7543 assert(operands.size() == 3);
7544 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7545 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7546 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7547 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7548 spv::MemorySemanticsMakeVisibleKHRMask |
7549 spv::MemorySemanticsOutputMemoryKHRMask |
7550 spv::MemorySemanticsVolatileMask)) {
7551 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7552 }
7553 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7554 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7555 }
7556 return 0;
7557 }
7558 break;
7559
John Kessenicha28f7a72019-08-06 07:00:58 -06007560#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007561 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007562 if (typeProxy == glslang::EbtFloat16)
7563 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007564 libCall = spv::GLSLstd450InterpolateAtSample;
7565 break;
7566 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007567 if (typeProxy == glslang::EbtFloat16)
7568 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007569 libCall = spv::GLSLstd450InterpolateAtOffset;
7570 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007571 case glslang::EOpAddCarry:
7572 opCode = spv::OpIAddCarry;
7573 typeId = builder.makeStructResultType(typeId0, typeId0);
7574 consumedOperands = 2;
7575 break;
7576 case glslang::EOpSubBorrow:
7577 opCode = spv::OpISubBorrow;
7578 typeId = builder.makeStructResultType(typeId0, typeId0);
7579 consumedOperands = 2;
7580 break;
7581 case glslang::EOpUMulExtended:
7582 opCode = spv::OpUMulExtended;
7583 typeId = builder.makeStructResultType(typeId0, typeId0);
7584 consumedOperands = 2;
7585 break;
7586 case glslang::EOpIMulExtended:
7587 opCode = spv::OpSMulExtended;
7588 typeId = builder.makeStructResultType(typeId0, typeId0);
7589 consumedOperands = 2;
7590 break;
7591 case glslang::EOpBitfieldExtract:
7592 if (isUnsigned)
7593 opCode = spv::OpBitFieldUExtract;
7594 else
7595 opCode = spv::OpBitFieldSExtract;
7596 break;
7597 case glslang::EOpBitfieldInsert:
7598 opCode = spv::OpBitFieldInsert;
7599 break;
7600
7601 case glslang::EOpFma:
7602 libCall = spv::GLSLstd450Fma;
7603 break;
7604 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007605 {
7606 libCall = spv::GLSLstd450FrexpStruct;
7607 assert(builder.isPointerType(typeId1));
7608 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007609 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007610 if (width == 16)
7611 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7612 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007613 if (builder.getNumComponents(operands[0]) == 1)
7614 frexpIntType = builder.makeIntegerType(width, true);
7615 else
John Kessenich8985fc92020-03-03 10:25:07 -07007616 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7617 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007618 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7619 consumedOperands = 1;
7620 }
John Kessenich55e7d112015-11-15 21:33:39 -07007621 break;
7622 case glslang::EOpLdexp:
7623 libCall = spv::GLSLstd450Ldexp;
7624 break;
7625
Rex Xu574ab042016-04-14 16:53:07 +08007626 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007627 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007628
John Kessenich66011cb2018-03-06 16:12:04 -07007629 case glslang::EOpSubgroupBroadcast:
7630 case glslang::EOpSubgroupBallotBitExtract:
7631 case glslang::EOpSubgroupShuffle:
7632 case glslang::EOpSubgroupShuffleXor:
7633 case glslang::EOpSubgroupShuffleUp:
7634 case glslang::EOpSubgroupShuffleDown:
7635 case glslang::EOpSubgroupClusteredAdd:
7636 case glslang::EOpSubgroupClusteredMul:
7637 case glslang::EOpSubgroupClusteredMin:
7638 case glslang::EOpSubgroupClusteredMax:
7639 case glslang::EOpSubgroupClusteredAnd:
7640 case glslang::EOpSubgroupClusteredOr:
7641 case glslang::EOpSubgroupClusteredXor:
7642 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007643 case glslang::EOpSubgroupPartitionedAdd:
7644 case glslang::EOpSubgroupPartitionedMul:
7645 case glslang::EOpSubgroupPartitionedMin:
7646 case glslang::EOpSubgroupPartitionedMax:
7647 case glslang::EOpSubgroupPartitionedAnd:
7648 case glslang::EOpSubgroupPartitionedOr:
7649 case glslang::EOpSubgroupPartitionedXor:
7650 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7651 case glslang::EOpSubgroupPartitionedInclusiveMul:
7652 case glslang::EOpSubgroupPartitionedInclusiveMin:
7653 case glslang::EOpSubgroupPartitionedInclusiveMax:
7654 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7655 case glslang::EOpSubgroupPartitionedInclusiveOr:
7656 case glslang::EOpSubgroupPartitionedInclusiveXor:
7657 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7658 case glslang::EOpSubgroupPartitionedExclusiveMul:
7659 case glslang::EOpSubgroupPartitionedExclusiveMin:
7660 case glslang::EOpSubgroupPartitionedExclusiveMax:
7661 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7662 case glslang::EOpSubgroupPartitionedExclusiveOr:
7663 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007664 return createSubgroupOperation(op, typeId, operands, typeProxy);
7665
Rex Xu9d93a232016-05-05 12:30:44 +08007666 case glslang::EOpSwizzleInvocations:
7667 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7668 libCall = spv::SwizzleInvocationsAMD;
7669 break;
7670 case glslang::EOpSwizzleInvocationsMasked:
7671 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7672 libCall = spv::SwizzleInvocationsMaskedAMD;
7673 break;
7674 case glslang::EOpWriteInvocation:
7675 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7676 libCall = spv::WriteInvocationAMD;
7677 break;
7678
7679 case glslang::EOpMin3:
7680 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7681 if (isFloat)
7682 libCall = spv::FMin3AMD;
7683 else {
7684 if (isUnsigned)
7685 libCall = spv::UMin3AMD;
7686 else
7687 libCall = spv::SMin3AMD;
7688 }
7689 break;
7690 case glslang::EOpMax3:
7691 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7692 if (isFloat)
7693 libCall = spv::FMax3AMD;
7694 else {
7695 if (isUnsigned)
7696 libCall = spv::UMax3AMD;
7697 else
7698 libCall = spv::SMax3AMD;
7699 }
7700 break;
7701 case glslang::EOpMid3:
7702 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7703 if (isFloat)
7704 libCall = spv::FMid3AMD;
7705 else {
7706 if (isUnsigned)
7707 libCall = spv::UMid3AMD;
7708 else
7709 libCall = spv::SMid3AMD;
7710 }
7711 break;
7712
7713 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007714 if (typeProxy == glslang::EbtFloat16)
7715 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007716 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7717 libCall = spv::InterpolateAtVertexAMD;
7718 break;
Chao Chen3c366992018-09-19 11:41:59 -07007719
Daniel Kochdb32b242020-03-17 20:42:47 -04007720 case glslang::EOpReportIntersection:
Chao Chenb50c02e2018-09-19 11:42:24 -07007721 typeId = builder.makeBoolType();
Daniel Kochdb32b242020-03-17 20:42:47 -04007722 opCode = spv::OpReportIntersectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007723 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04007724 case glslang::EOpTrace:
Daniel Kochdb32b242020-03-17 20:42:47 -04007725 builder.createNoResultOp(spv::OpTraceRayKHR, operands);
Ashwin Leleff1783d2018-10-22 16:41:44 -07007726 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04007727 case glslang::EOpExecuteCallable:
Daniel Kochdb32b242020-03-17 20:42:47 -04007728 builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007729 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007730
7731 case glslang::EOpRayQueryInitialize:
Torosdagli06c2eee2020-03-19 11:09:57 -04007732 builder.createNoResultOp(spv::OpRayQueryInitializeKHR, operands);
7733 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007734 case glslang::EOpRayQueryTerminate:
Torosdagli06c2eee2020-03-19 11:09:57 -04007735 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operands);
7736 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007737 case glslang::EOpRayQueryGenerateIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007738 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR, operands);
7739 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007740 case glslang::EOpRayQueryConfirmIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007741 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operands);
7742 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007743 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04007744 typeId = builder.makeBoolType();
7745 opCode = spv::OpRayQueryProceedKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007746 break;
7747 case glslang::EOpRayQueryGetIntersectionType:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007748 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007749 opCode = spv::OpRayQueryGetIntersectionTypeKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007750 break;
7751 case glslang::EOpRayQueryGetRayTMin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007752 typeId = builder.makeFloatType(32);
7753 opCode = spv::OpRayQueryGetRayTMinKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007754 break;
7755 case glslang::EOpRayQueryGetRayFlags:
Torosdagli06c2eee2020-03-19 11:09:57 -04007756 typeId = builder.makeIntType(32);
7757 opCode = spv::OpRayQueryGetRayFlagsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007758 break;
7759 case glslang::EOpRayQueryGetIntersectionT:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007760 typeId = builder.makeFloatType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007761 opCode = spv::OpRayQueryGetIntersectionTKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007762 break;
7763 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007764 typeId = builder.makeIntType(32);
7765 opCode = spv::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007766 break;
7767 case glslang::EOpRayQueryGetIntersectionInstanceId:
Torosdagli06c2eee2020-03-19 11:09:57 -04007768 typeId = builder.makeIntType(32);
7769 opCode = spv::OpRayQueryGetIntersectionInstanceIdKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007770 break;
7771 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
Torosdagli06c2eee2020-03-19 11:09:57 -04007772 typeId = builder.makeIntType(32);
7773 opCode = spv::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007774 break;
7775 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007776 typeId = builder.makeIntType(32);
7777 opCode = spv::OpRayQueryGetIntersectionGeometryIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007778 break;
7779 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007780 typeId = builder.makeIntType(32);
7781 opCode = spv::OpRayQueryGetIntersectionPrimitiveIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007782 break;
7783 case glslang::EOpRayQueryGetIntersectionBarycentrics:
Torosdagli06c2eee2020-03-19 11:09:57 -04007784 typeId = builder.makeVectorType(builder.makeFloatType(32), 2);
7785 opCode = spv::OpRayQueryGetIntersectionBarycentricsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007786 break;
7787 case glslang::EOpRayQueryGetIntersectionFrontFace:
Torosdagli06c2eee2020-03-19 11:09:57 -04007788 typeId = builder.makeBoolType();
7789 opCode = spv::OpRayQueryGetIntersectionFrontFaceKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007790 break;
7791 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
Torosdagli06c2eee2020-03-19 11:09:57 -04007792 typeId = builder.makeBoolType();
7793 opCode = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007794 break;
7795 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007796 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7797 opCode = spv::OpRayQueryGetIntersectionObjectRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007798 break;
7799 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007800 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7801 opCode = spv::OpRayQueryGetIntersectionObjectRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007802 break;
7803 case glslang::EOpRayQueryGetWorldRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007804 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7805 opCode = spv::OpRayQueryGetWorldRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007806 break;
7807 case glslang::EOpRayQueryGetWorldRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007808 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7809 opCode = spv::OpRayQueryGetWorldRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007810 break;
7811 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
Torosdagli06c2eee2020-03-19 11:09:57 -04007812 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007813 opCode = spv::OpRayQueryGetIntersectionObjectToWorldKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007814 break;
7815 case glslang::EOpRayQueryGetIntersectionWorldToObject:
Torosdagli06c2eee2020-03-19 11:09:57 -04007816 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007817 opCode = spv::OpRayQueryGetIntersectionWorldToObjectKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007818 break;
Chao Chen3c366992018-09-19 11:41:59 -07007819 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7820 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7821 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007822 case glslang::EOpCooperativeMatrixMulAdd:
7823 opCode = spv::OpCooperativeMatrixMulAddNV;
7824 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007825#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007826 default:
7827 return 0;
7828 }
7829
7830 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007831 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007832 // Use an extended instruction from the standard library.
7833 // Construct the call arguments, without modifying the original operands vector.
7834 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7835 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007836 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007837 } else if (opCode == spv::OpDot && !isFloat) {
7838 // int dot(int, int)
7839 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7840 const int componentCount = builder.getNumComponents(operands[0]);
7841 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7842 builder.setPrecision(mulOp, precision);
7843 id = builder.createCompositeExtract(mulOp, typeId, 0);
7844 for (int i = 1; i < componentCount; ++i) {
7845 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07007846 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01007847 }
John Kessenich2359bd02015-12-06 19:29:11 -07007848 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007849 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007850 case 0:
7851 // should all be handled by visitAggregate and createNoArgOperation
7852 assert(0);
7853 return 0;
7854 case 1:
7855 // should all be handled by createUnaryOperation
7856 assert(0);
7857 return 0;
7858 case 2:
7859 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7860 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007861 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007862 // anything 3 or over doesn't have l-value operands, so all should be consumed
7863 assert(consumedOperands == operands.size());
7864 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007865 break;
7866 }
7867 }
7868
John Kessenichb9197c82019-08-11 07:41:45 -06007869#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007870 // Decode the return types that were structures
7871 switch (op) {
7872 case glslang::EOpAddCarry:
7873 case glslang::EOpSubBorrow:
7874 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7875 id = builder.createCompositeExtract(id, typeId0, 0);
7876 break;
7877 case glslang::EOpUMulExtended:
7878 case glslang::EOpIMulExtended:
7879 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7880 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7881 break;
7882 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007883 {
7884 assert(operands.size() == 2);
7885 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7886 // "exp" is floating-point type (from HLSL intrinsic)
7887 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7888 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7889 builder.createStore(member1, operands[1]);
7890 } else
7891 // "exp" is integer type (from GLSL built-in function)
7892 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7893 id = builder.createCompositeExtract(id, typeId0, 0);
7894 }
John Kessenich55e7d112015-11-15 21:33:39 -07007895 break;
7896 default:
7897 break;
7898 }
John Kessenichb9197c82019-08-11 07:41:45 -06007899#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007900
John Kessenich32cfd492016-02-02 12:37:46 -07007901 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007902}
7903
Rex Xu9d93a232016-05-05 12:30:44 +08007904// Intrinsics with no arguments (or no return value, and no precision).
7905spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007906{
Jeff Bolz36831c92018-09-05 10:11:41 -05007907 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07007908 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
7909 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007910
7911 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007912 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007913 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007914 if (glslangIntermediate->usingVulkanMemoryModel()) {
7915 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7916 spv::MemorySemanticsOutputMemoryKHRMask |
7917 spv::MemorySemanticsAcquireReleaseMask);
7918 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7919 } else {
7920 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7921 }
John Kessenich82979362017-12-11 04:02:24 -07007922 } else {
7923 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7924 spv::MemorySemanticsWorkgroupMemoryMask |
7925 spv::MemorySemanticsAcquireReleaseMask);
7926 }
John Kessenich140f3df2015-06-26 16:58:36 -06007927 return 0;
7928 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007929 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7930 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007931 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007932 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007933 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7934 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007935 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007936 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007937 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7938 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007939 return 0;
7940 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007941 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7942 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007943 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007944#ifndef GLSLANG_WEB
7945 case glslang::EOpMemoryBarrierAtomicCounter:
7946 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7947 spv::MemorySemanticsAcquireReleaseMask);
7948 return 0;
7949 case glslang::EOpMemoryBarrierImage:
7950 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7951 spv::MemorySemanticsAcquireReleaseMask);
7952 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007953 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007954 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007955 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007956 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007957 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007958 case glslang::EOpDeviceMemoryBarrier:
7959 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7960 spv::MemorySemanticsImageMemoryMask |
7961 spv::MemorySemanticsAcquireReleaseMask);
7962 return 0;
7963 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7964 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7965 spv::MemorySemanticsImageMemoryMask |
7966 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007967 return 0;
7968 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007969 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7970 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007971 return 0;
7972 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007973 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7974 spv::MemorySemanticsWorkgroupMemoryMask |
7975 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007976 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007977 case glslang::EOpSubgroupBarrier:
7978 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7979 spv::MemorySemanticsAcquireReleaseMask);
7980 return spv::NoResult;
7981 case glslang::EOpSubgroupMemoryBarrier:
7982 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7983 spv::MemorySemanticsAcquireReleaseMask);
7984 return spv::NoResult;
7985 case glslang::EOpSubgroupMemoryBarrierBuffer:
7986 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7987 spv::MemorySemanticsAcquireReleaseMask);
7988 return spv::NoResult;
7989 case glslang::EOpSubgroupMemoryBarrierImage:
7990 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7991 spv::MemorySemanticsAcquireReleaseMask);
7992 return spv::NoResult;
7993 case glslang::EOpSubgroupMemoryBarrierShared:
7994 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7995 spv::MemorySemanticsAcquireReleaseMask);
7996 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06007997
7998 case glslang::EOpEmitVertex:
7999 builder.createNoResultOp(spv::OpEmitVertex);
8000 return 0;
8001 case glslang::EOpEndPrimitive:
8002 builder.createNoResultOp(spv::OpEndPrimitive);
8003 return 0;
8004
John Kessenich66011cb2018-03-06 16:12:04 -07008005 case glslang::EOpSubgroupElect: {
8006 std::vector<spv::Id> operands;
8007 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
8008 }
Rex Xu9d93a232016-05-05 12:30:44 +08008009 case glslang::EOpTime:
8010 {
8011 std::vector<spv::Id> args; // Dummy arguments
8012 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
8013 return builder.setPrecision(id, precision);
8014 }
Daniel Kochdb32b242020-03-17 20:42:47 -04008015 case glslang::EOpIgnoreIntersection:
8016 builder.createNoResultOp(spv::OpIgnoreIntersectionKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008017 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04008018 case glslang::EOpTerminateRay:
8019 builder.createNoResultOp(spv::OpTerminateRayKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008020 return 0;
Torosdagli06c2eee2020-03-19 11:09:57 -04008021 case glslang::EOpRayQueryInitialize:
8022 builder.createNoResultOp(spv::OpRayQueryInitializeKHR);
8023 return 0;
8024 case glslang::EOpRayQueryTerminate:
8025 builder.createNoResultOp(spv::OpRayQueryTerminateKHR);
8026 return 0;
8027 case glslang::EOpRayQueryGenerateIntersection:
8028 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR);
8029 return 0;
8030 case glslang::EOpRayQueryConfirmIntersection:
8031 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR);
8032 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05008033 case glslang::EOpBeginInvocationInterlock:
8034 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
8035 return 0;
8036 case glslang::EOpEndInvocationInterlock:
8037 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
8038 return 0;
8039
Jeff Bolzba6170b2019-07-01 09:23:23 -05008040 case glslang::EOpIsHelperInvocation:
8041 {
8042 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08008043 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
8044 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
8045 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05008046 }
8047
amhagan91fb0092019-07-10 21:14:38 -04008048 case glslang::EOpReadClockSubgroupKHR: {
8049 std::vector<spv::Id> args;
8050 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
8051 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8052 builder.addCapability(spv::CapabilityShaderClockKHR);
8053 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8054 }
8055
8056 case glslang::EOpReadClockDeviceKHR: {
8057 std::vector<spv::Id> args;
8058 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
8059 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8060 builder.addCapability(spv::CapabilityShaderClockKHR);
8061 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8062 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06008063#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008064 default:
John Kessenich155d3512019-08-08 23:29:20 -06008065 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008066 }
John Kessenich155d3512019-08-08 23:29:20 -06008067
8068 logger->missingFunctionality("unknown operation with no arguments");
8069
8070 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008071}
8072
8073spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
8074{
John Kessenich2f273362015-07-18 22:34:27 -06008075 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06008076 spv::Id id;
8077 if (symbolValues.end() != iter) {
8078 id = iter->second;
8079 return id;
8080 }
8081
8082 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06008083 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
Daniel Kochdb32b242020-03-17 20:42:47 -04008084 auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06008085 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06008086 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06008087 if (forcedType.second != spv::NoType)
8088 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06008089
Rex Xuc884b4a2016-06-29 15:03:44 +08008090 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008091 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
8092 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
8093 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06008094#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008095 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06008096 if (symbol->getQualifier().hasComponent())
8097 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
8098 if (symbol->getQualifier().hasIndex())
8099 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07008100#endif
John Kessenich6c292d32016-02-15 20:58:50 -07008101 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07008102 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06008103 // atomic counters use this:
8104 if (symbol->getQualifier().hasOffset())
8105 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008106 }
8107
scygan2c864272016-05-18 18:09:17 +02008108 if (symbol->getQualifier().hasLocation())
8109 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07008110 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07008111 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07008112 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06008113 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07008114 }
John Kessenich140f3df2015-06-26 16:58:36 -06008115 if (symbol->getQualifier().hasSet())
8116 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07008117 else if (IsDescriptorResource(symbol->getType())) {
8118 // default to 0
8119 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
8120 }
John Kessenich140f3df2015-06-26 16:58:36 -06008121 if (symbol->getQualifier().hasBinding())
8122 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06008123 else if (IsDescriptorResource(symbol->getType())) {
8124 // default to 0
8125 builder.addDecoration(id, spv::DecorationBinding, 0);
8126 }
John Kessenich6c292d32016-02-15 20:58:50 -07008127 if (symbol->getQualifier().hasAttachment())
8128 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06008129 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07008130 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07008131 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008132 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07008133 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
8134 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
8135 builder.addDecoration(id, spv::DecorationXfbStride, stride);
8136 }
8137 if (symbol->getQualifier().hasXfbOffset())
8138 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008139 }
8140
John Kessenichb9197c82019-08-11 07:41:45 -06008141 // add built-in variable decoration
8142 if (builtIn != spv::BuiltInMax) {
8143 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
8144 }
8145
8146#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08008147 if (symbol->getType().isImage()) {
8148 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07008149 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
8150 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08008151 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07008152 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08008153 }
8154
John Kessenich5611c6d2018-04-05 11:25:02 -06008155 // nonuniform
8156 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
8157
chaoc0ad6a4e2016-12-19 16:29:34 -08008158 if (builtIn == spv::BuiltInSampleMask) {
8159 spv::Decoration decoration;
8160 // GL_NV_sample_mask_override_coverage extension
8161 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08008162 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08008163 else
8164 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07008165 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08008166 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07008167 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08008168 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
8169 }
8170 }
chaoc771d89f2017-01-13 01:10:53 -08008171 else if (builtIn == spv::BuiltInLayer) {
8172 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06008173 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008174 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08008175 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
8176 builder.addExtension(spv::E_SPV_NV_viewport_array2);
8177 }
John Kessenichb41bff62017-08-11 13:07:17 -06008178 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008179 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
8180 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08008181 builder.addCapability(spv::CapabilityShaderStereoViewNV);
8182 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
8183 }
8184 }
8185
chaoc6e5acae2016-12-20 13:28:52 -08008186 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008187 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08008188 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08008189 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
8190 }
Chao Chen9eada4b2018-09-19 11:39:56 -07008191 if (symbol->getQualifier().pervertexNV) {
8192 builder.addDecoration(id, spv::DecorationPerVertexNV);
8193 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
8194 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
8195 }
chaoc0ad6a4e2016-12-19 16:29:34 -08008196
John Kessenich5d610ee2018-03-07 18:05:55 -07008197 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
8198 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
8199 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
8200 symbol->getType().getQualifier().semanticName);
8201 }
8202
John Kessenich7015bd62019-08-01 03:28:08 -06008203 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07008204 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
8205 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008206 }
John Kessenichb9197c82019-08-11 07:41:45 -06008207#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008208
John Kessenich140f3df2015-06-26 16:58:36 -06008209 return id;
8210}
8211
John Kessenicha28f7a72019-08-06 07:00:58 -06008212#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008213// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
8214void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
8215{
8216 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07008217 if (qualifier.perPrimitiveNV) {
8218 // Need to add capability/extension for fragment shader.
8219 // Mesh shader already adds this by default.
8220 if (glslangIntermediate->getStage() == EShLangFragment) {
8221 builder.addCapability(spv::CapabilityMeshShadingNV);
8222 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8223 }
Chao Chen3c366992018-09-19 11:41:59 -07008224 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008225 }
Chao Chen3c366992018-09-19 11:41:59 -07008226 if (qualifier.perViewNV)
8227 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
8228 if (qualifier.perTaskNV)
8229 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
8230 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07008231 if (qualifier.perPrimitiveNV) {
8232 // Need to add capability/extension for fragment shader.
8233 // Mesh shader already adds this by default.
8234 if (glslangIntermediate->getStage() == EShLangFragment) {
8235 builder.addCapability(spv::CapabilityMeshShadingNV);
8236 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8237 }
Chao Chen3c366992018-09-19 11:41:59 -07008238 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008239 }
Chao Chen3c366992018-09-19 11:41:59 -07008240 if (qualifier.perViewNV)
8241 builder.addDecoration(id, spv::DecorationPerViewNV);
8242 if (qualifier.perTaskNV)
8243 builder.addDecoration(id, spv::DecorationPerTaskNV);
8244 }
8245}
8246#endif
8247
John Kessenich55e7d112015-11-15 21:33:39 -07008248// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008249// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008250//
8251// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8252//
8253// Recursively walk the nodes. The nodes form a tree whose leaves are
8254// regular constants, which themselves are trees that createSpvConstant()
8255// recursively walks. So, this function walks the "top" of the tree:
8256// - emit specialization constant-building instructions for specConstant
8257// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008258spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008259{
John Kessenich7cc0e282016-03-20 00:46:02 -06008260 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008261
qining4f4bb812016-04-03 23:55:17 -04008262 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008263 if (! node.getQualifier().specConstant) {
8264 // hand off to the non-spec-constant path
8265 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8266 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008267 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8268 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8269 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008270 }
8271
8272 // We now know we have a specialization constant to build
8273
John Kessenichd94c0032016-05-30 19:29:40 -06008274 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008275 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8276 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8277 std::vector<spv::Id> dimConstId;
8278 for (int dim = 0; dim < 3; ++dim) {
8279 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8280 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008281 if (specConst) {
8282 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8283 glslangIntermediate->getLocalSizeSpecId(dim));
8284 }
qining4f4bb812016-04-03 23:55:17 -04008285 }
8286 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8287 }
8288
8289 // An AST node labelled as specialization constant should be a symbol node.
8290 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8291 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008292 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008293 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008294 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8295 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8296 // will set the builder into spec constant op instruction generating mode.
8297 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008298 result = accessChainLoad(sub_tree->getType());
8299 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008300 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008301 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008302 } else {
8303 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008304 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008305 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008306 builder.addName(result, sn->getName().c_str());
8307 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008308 }
qining4f4bb812016-04-03 23:55:17 -04008309
8310 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8311 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008312 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008313 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008314}
8315
John Kessenich140f3df2015-06-26 16:58:36 -06008316// Use 'consts' as the flattened glslang source of scalar constants to recursively
8317// build the aggregate SPIR-V constant.
8318//
8319// If there are not enough elements present in 'consts', 0 will be substituted;
8320// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8321//
John Kessenich8985fc92020-03-03 10:25:07 -07008322spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8323 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008324{
8325 // vector of constants for SPIR-V
8326 std::vector<spv::Id> spvConsts;
8327
8328 // Type is used for struct and array constants
8329 spv::Id typeId = convertGlslangToSpvType(glslangType);
8330
8331 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008332 glslang::TType elementType(glslangType, 0);
8333 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008334 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008335 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008336 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008337 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008338 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008339 } else if (glslangType.isCoopMat()) {
8340 glslang::TType componentType(glslangType.getBasicType());
8341 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008342 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008343 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8344 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008345 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008346 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008347 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8348 bool zero = nextConst >= consts.size();
8349 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008350 case glslang::EbtInt:
8351 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8352 break;
8353 case glslang::EbtUint:
8354 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8355 break;
8356 case glslang::EbtFloat:
8357 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8358 break;
8359 case glslang::EbtBool:
8360 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8361 break;
8362#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008363 case glslang::EbtInt8:
8364 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8365 break;
8366 case glslang::EbtUint8:
8367 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8368 break;
8369 case glslang::EbtInt16:
8370 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8371 break;
8372 case glslang::EbtUint16:
8373 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8374 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008375 case glslang::EbtInt64:
8376 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8377 break;
8378 case glslang::EbtUint64:
8379 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8380 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008381 case glslang::EbtDouble:
8382 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8383 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008384 case glslang::EbtFloat16:
8385 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8386 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008387#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008388 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008389 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008390 break;
8391 }
8392 ++nextConst;
8393 }
8394 } else {
8395 // we have a non-aggregate (scalar) constant
8396 bool zero = nextConst >= consts.size();
8397 spv::Id scalar = 0;
8398 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008399 case glslang::EbtInt:
8400 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8401 break;
8402 case glslang::EbtUint:
8403 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8404 break;
8405 case glslang::EbtFloat:
8406 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8407 break;
8408 case glslang::EbtBool:
8409 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8410 break;
8411#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008412 case glslang::EbtInt8:
8413 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8414 break;
8415 case glslang::EbtUint8:
8416 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8417 break;
8418 case glslang::EbtInt16:
8419 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8420 break;
8421 case glslang::EbtUint16:
8422 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8423 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008424 case glslang::EbtInt64:
8425 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8426 break;
8427 case glslang::EbtUint64:
8428 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8429 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008430 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008431 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008432 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008433 case glslang::EbtFloat16:
8434 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8435 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008436 case glslang::EbtReference:
8437 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8438 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8439 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008440#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008441 case glslang::EbtString:
8442 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8443 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008444 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008445 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008446 break;
8447 }
8448 ++nextConst;
8449 return scalar;
8450 }
8451
8452 return builder.makeCompositeConstant(typeId, spvConsts);
8453}
8454
John Kessenich7c1aa102015-10-15 13:29:11 -06008455// Return true if the node is a constant or symbol whose reading has no
8456// non-trivial observable cost or effect.
8457bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8458{
8459 // don't know what this is
8460 if (node == nullptr)
8461 return false;
8462
8463 // a constant is safe
8464 if (node->getAsConstantUnion() != nullptr)
8465 return true;
8466
8467 // not a symbol means non-trivial
8468 if (node->getAsSymbolNode() == nullptr)
8469 return false;
8470
8471 // a symbol, depends on what's being read
8472 switch (node->getType().getQualifier().storage) {
8473 case glslang::EvqTemporary:
8474 case glslang::EvqGlobal:
8475 case glslang::EvqIn:
8476 case glslang::EvqInOut:
8477 case glslang::EvqConst:
8478 case glslang::EvqConstReadOnly:
8479 case glslang::EvqUniform:
8480 return true;
8481 default:
8482 return false;
8483 }
qining25262b32016-05-06 17:25:16 -04008484}
John Kessenich7c1aa102015-10-15 13:29:11 -06008485
8486// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008487// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008488// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008489// Return true if trivial.
8490bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8491{
8492 if (node == nullptr)
8493 return false;
8494
John Kessenich84cc15f2017-05-24 16:44:47 -06008495 // count non scalars as trivial, as well as anything coming from HLSL
8496 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008497 return true;
8498
John Kessenich7c1aa102015-10-15 13:29:11 -06008499 // symbols and constants are trivial
8500 if (isTrivialLeaf(node))
8501 return true;
8502
8503 // otherwise, it needs to be a simple operation or one or two leaf nodes
8504
8505 // not a simple operation
8506 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8507 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8508 if (binaryNode == nullptr && unaryNode == nullptr)
8509 return false;
8510
8511 // not on leaf nodes
8512 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8513 return false;
8514
8515 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8516 return false;
8517 }
8518
8519 switch (node->getAsOperator()->getOp()) {
8520 case glslang::EOpLogicalNot:
8521 case glslang::EOpConvIntToBool:
8522 case glslang::EOpConvUintToBool:
8523 case glslang::EOpConvFloatToBool:
8524 case glslang::EOpConvDoubleToBool:
8525 case glslang::EOpEqual:
8526 case glslang::EOpNotEqual:
8527 case glslang::EOpLessThan:
8528 case glslang::EOpGreaterThan:
8529 case glslang::EOpLessThanEqual:
8530 case glslang::EOpGreaterThanEqual:
8531 case glslang::EOpIndexDirect:
8532 case glslang::EOpIndexDirectStruct:
8533 case glslang::EOpLogicalXor:
8534 case glslang::EOpAny:
8535 case glslang::EOpAll:
8536 return true;
8537 default:
8538 return false;
8539 }
8540}
8541
8542// Emit short-circuiting code, where 'right' is never evaluated unless
8543// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008544spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8545 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008546{
8547 spv::Id boolTypeId = builder.makeBoolType();
8548
8549 // emit left operand
8550 builder.clearAccessChain();
8551 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008552 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008553
8554 // Operands to accumulate OpPhi operands
8555 std::vector<spv::Id> phiOperands;
8556 // accumulate left operand's phi information
8557 phiOperands.push_back(leftId);
8558 phiOperands.push_back(builder.getBuildPoint()->getId());
8559
8560 // Make the two kinds of operation symmetric with a "!"
8561 // || => emit "if (! left) result = right"
8562 // && => emit "if ( left) result = right"
8563 //
8564 // TODO: this runtime "not" for || could be avoided by adding functionality
8565 // to 'builder' to have an "else" without an "then"
8566 if (op == glslang::EOpLogicalOr)
8567 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8568
8569 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008570 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008571
8572 // emit right operand as the "then" part of the "if"
8573 builder.clearAccessChain();
8574 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008575 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008576
8577 // accumulate left operand's phi information
8578 phiOperands.push_back(rightId);
8579 phiOperands.push_back(builder.getBuildPoint()->getId());
8580
8581 // finish the "if"
8582 ifBuilder.makeEndIf();
8583
8584 // phi together the two results
8585 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8586}
8587
John Kessenicha28f7a72019-08-06 07:00:58 -06008588#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008589// Return type Id of the imported set of extended instructions corresponds to the name.
8590// Import this set if it has not been imported yet.
8591spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8592{
8593 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8594 return extBuiltinMap[name];
8595 else {
Rex Xu51596642016-09-21 18:56:12 +08008596 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008597 spv::Id extBuiltins = builder.import(name);
8598 extBuiltinMap[name] = extBuiltins;
8599 return extBuiltins;
8600 }
8601}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008602#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008603
John Kessenich140f3df2015-06-26 16:58:36 -06008604}; // end anonymous namespace
8605
8606namespace glslang {
8607
John Kessenich68d78fd2015-07-12 19:28:10 -06008608void GetSpirvVersion(std::string& version)
8609{
John Kessenich9e55f632015-07-15 10:03:39 -06008610 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008611 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008612 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008613 version = buf;
8614}
8615
John Kessenicha372a3e2017-11-02 22:32:14 -06008616// For low-order part of the generator's magic number. Bump up
8617// when there is a change in the style (e.g., if SSA form changes,
8618// or a different instruction sequence to do something gets used).
8619int GetSpirvGeneratorVersion()
8620{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008621 // return 1; // start
8622 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008623 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008624 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008625 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008626 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8627 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008628 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
8629 return 8; // switch to new dead block eliminator; use OpUnreachable
John Kessenicha372a3e2017-11-02 22:32:14 -06008630}
8631
John Kessenich140f3df2015-06-26 16:58:36 -06008632// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008633void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008634{
8635 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008636 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008637 if (out.fail())
8638 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008639 for (int i = 0; i < (int)spirv.size(); ++i) {
8640 unsigned int word = spirv[i];
8641 out.write((const char*)&word, 4);
8642 }
8643 out.close();
8644}
8645
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008646// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008647void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008648{
John Kessenich155d3512019-08-08 23:29:20 -06008649#ifndef GLSLANG_WEB
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008650 std::ofstream out;
8651 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008652 if (out.fail())
8653 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008654 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008655 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008656 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008657 if (varName != nullptr) {
8658 out << "\t #pragma once" << std::endl;
8659 out << "const uint32_t " << varName << "[] = {" << std::endl;
8660 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008661 const int WORDS_PER_LINE = 8;
8662 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8663 out << "\t";
8664 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8665 const unsigned int word = spirv[i + j];
8666 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8667 if (i + j + 1 < (int)spirv.size()) {
8668 out << ",";
8669 }
8670 }
8671 out << std::endl;
8672 }
Flavio15017db2017-02-15 14:29:33 -08008673 if (varName != nullptr) {
8674 out << "};";
8675 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008676 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008677#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008678}
8679
John Kessenich140f3df2015-06-26 16:58:36 -06008680//
8681// Set up the glslang traversal
8682//
John Kessenich4e11b612018-08-30 16:56:59 -06008683void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008684{
Lei Zhang17535f72016-05-04 15:55:59 -04008685 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008686 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008687}
8688
John Kessenich4e11b612018-08-30 16:56:59 -06008689void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008690 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008691{
John Kessenich140f3df2015-06-26 16:58:36 -06008692 TIntermNode* root = intermediate.getTreeRoot();
8693
8694 if (root == 0)
8695 return;
8696
John Kessenich4e11b612018-08-30 16:56:59 -06008697 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008698 if (options == nullptr)
8699 options = &defaultOptions;
8700
John Kessenich4e11b612018-08-30 16:56:59 -06008701 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008702
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008703 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008704 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008705 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008706 it.dumpSpv(spirv);
8707
GregFfb03a552018-03-29 11:49:14 -06008708#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008709 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8710 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008711 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8712 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008713 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008714 prelegalization = false;
8715 }
John Kessenich717c80a2018-08-23 15:17:10 -06008716
John Kessenich4e11b612018-08-30 16:56:59 -06008717 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008718 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008719
John Kessenich717c80a2018-08-23 15:17:10 -06008720 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008721 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008722
GregFcd1f1692017-09-21 18:40:22 -06008723#endif
8724
John Kessenich4e11b612018-08-30 16:56:59 -06008725 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008726}
8727
8728}; // end namespace glslang