blob: 61291ea37a22f9913623e18cd556062b870d04d2 [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 Torosdagli7d37a682020-03-26 10:52:33 -04001186 return spv::StorageClassWorkgroup;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001187 if (type.getQualifier().isPipeInput())
1188 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001189 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001190 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001191
1192 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001193 type.getQualifier().storage == glslang::EvqUniform) {
John Kessenichdeec1932019-08-13 08:00:30 -06001194 if (type.isAtomic())
John Kessenichbed4e4f2017-09-08 02:38:07 -06001195 return spv::StorageClassAtomicCounter;
1196 if (type.containsOpaque())
1197 return spv::StorageClassUniformConstant;
1198 }
1199
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001200 if (type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001201 type.getQualifier().isShaderRecord()) {
1202 return spv::StorageClassShaderRecordBufferKHR;
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001203 }
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001204
John Kessenichbed4e4f2017-09-08 02:38:07 -06001205 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001206 builder.addIncorporatedExtension(spv::E_SPV_KHR_storage_buffer_storage_class, spv::Spv_1_3);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001207 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001208 }
1209
1210 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich7015bd62019-08-01 03:28:08 -06001211 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001212 return spv::StorageClassPushConstant;
1213 if (type.getBasicType() == glslang::EbtBlock)
1214 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001215 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001216 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001217
1218 switch (type.getQualifier().storage) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001219 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1220 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1221 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenichdeec1932019-08-13 08:00:30 -06001222 case glslang::EvqShared: return spv::StorageClassWorkgroup;
John Kessenich3dd1ce52019-10-17 07:08:40 -06001223#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -04001224 case glslang::EvqPayload: return spv::StorageClassRayPayloadKHR;
1225 case glslang::EvqPayloadIn: return spv::StorageClassIncomingRayPayloadKHR;
1226 case glslang::EvqHitAttr: return spv::StorageClassHitAttributeKHR;
1227 case glslang::EvqCallableData: return spv::StorageClassCallableDataKHR;
1228 case glslang::EvqCallableDataIn: return spv::StorageClassIncomingCallableDataKHR;
Chao Chenb50c02e2018-09-19 11:42:24 -07001229#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001230 default:
1231 assert(0);
1232 break;
1233 }
1234
1235 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001236}
1237
John Kessenich5611c6d2018-04-05 11:25:02 -06001238// Add capabilities pertaining to how an array is indexed.
1239void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1240 const glslang::TType& indexType)
1241{
John Kessenichb9197c82019-08-11 07:41:45 -06001242#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06001243 if (indexType.getQualifier().isNonUniform()) {
1244 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001245 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001246 if (baseType.getBasicType() == glslang::EbtSampler) {
1247 if (baseType.getQualifier().hasAttachment())
1248 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001249 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001250 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001251 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001252 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1253 else if (baseType.isImage())
1254 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1255 else if (baseType.isTexture())
1256 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1257 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1258 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1259 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1260 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1261 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1262 }
1263 } else {
1264 // assume a dynamically uniform index
1265 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001266 if (baseType.getQualifier().hasAttachment()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001267 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001268 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001269 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001270 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001271 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001272 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001273 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001274 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001275 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001276 }
1277 }
John Kessenichb9197c82019-08-11 07:41:45 -06001278#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06001279}
1280
qining25262b32016-05-06 17:25:16 -04001281// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001282// descriptor set.
1283bool IsDescriptorResource(const glslang::TType& type)
1284{
John Kessenichf7497e22016-03-08 21:36:22 -07001285 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001286 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001287 return type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001288 ! type.getQualifier().isShaderRecord() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001289 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001290
1291 // non block...
1292 // basically samplerXXX/subpass/sampler/texture are all included
1293 // if they are the global-scope-class, not the function parameter
1294 // (or local, if they ever exist) class.
1295 if (type.getBasicType() == glslang::EbtSampler)
1296 return type.getQualifier().isUniformOrBuffer();
1297
1298 // None of the above.
1299 return false;
1300}
1301
John Kesseniche0b6cad2015-12-24 10:30:13 -07001302void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1303{
1304 if (child.layoutMatrix == glslang::ElmNone)
1305 child.layoutMatrix = parent.layoutMatrix;
1306
1307 if (parent.invariant)
1308 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001309 if (parent.flat)
1310 child.flat = true;
1311 if (parent.centroid)
1312 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001313#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001314 if (parent.nopersp)
1315 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001316 if (parent.explicitInterp)
1317 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001318 if (parent.perPrimitiveNV)
1319 child.perPrimitiveNV = true;
1320 if (parent.perViewNV)
1321 child.perViewNV = true;
1322 if (parent.perTaskNV)
1323 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001324 if (parent.patch)
1325 child.patch = true;
1326 if (parent.sample)
1327 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001328 if (parent.coherent)
1329 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001330 if (parent.devicecoherent)
1331 child.devicecoherent = true;
1332 if (parent.queuefamilycoherent)
1333 child.queuefamilycoherent = true;
1334 if (parent.workgroupcoherent)
1335 child.workgroupcoherent = true;
1336 if (parent.subgroupcoherent)
1337 child.subgroupcoherent = true;
Daniel Kochdb32b242020-03-17 20:42:47 -04001338 if (parent.shadercallcoherent)
1339 child.shadercallcoherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001340 if (parent.nonprivate)
1341 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001342 if (parent.volatil)
1343 child.volatil = true;
1344 if (parent.restrict)
1345 child.restrict = true;
1346 if (parent.readonly)
1347 child.readonly = true;
1348 if (parent.writeonly)
1349 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001350#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001351}
1352
John Kessenichf2b7f332016-09-01 17:05:23 -06001353bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001354{
John Kessenich7b9fa252016-01-21 18:56:57 -07001355 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001356 // - struct members might inherit from a struct declaration
1357 // (note that non-block structs don't explicitly inherit,
1358 // only implicitly, meaning no decoration involved)
1359 // - affect decorations on the struct members
1360 // (note smooth does not, and expecting something like volatile
1361 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001362 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001363 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001364}
1365
John Kessenich140f3df2015-06-26 16:58:36 -06001366//
1367// Implement the TGlslangToSpvTraverser class.
1368//
1369
John Kessenich8985fc92020-03-03 10:25:07 -07001370TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion,
1371 const glslang::TIntermediate* glslangIntermediate,
1372 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options) :
1373 TIntermTraverser(true, false, true),
1374 options(options),
1375 shaderEntry(nullptr), currentFunction(nullptr),
1376 sequenceDepth(0), logger(buildLogger),
1377 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
1378 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
1379 glslangIntermediate(glslangIntermediate),
Jeff Bolz04d73732019-05-31 13:06:01 -05001380 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp()),
1381 nonSemanticDebugPrintf(0)
John Kessenich140f3df2015-06-26 16:58:36 -06001382{
1383 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1384
1385 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001386 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1387 glslangIntermediate->getVersion());
1388
John Kessenich121853f2017-05-31 17:11:16 -06001389 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001390 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001391 builder.setSourceFile(glslangIntermediate->getSourceFile());
1392
1393 // Set the source shader's text. If for SPV version 1.0, include
1394 // a preamble in comments stating the OpModuleProcessed instructions.
1395 // Otherwise, emit those as actual instructions.
1396 std::string text;
1397 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1398 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001399 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001400 text.append("// OpModuleProcessed ");
1401 text.append(processes[p]);
1402 text.append("\n");
1403 } else
1404 builder.addModuleProcessed(processes[p]);
1405 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001406 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001407 text.append("#line 1\n");
1408 text.append(glslangIntermediate->getSourceText());
1409 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001410 // Pass name and text for all included files
1411 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1412 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1413 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001414 }
John Kessenich140f3df2015-06-26 16:58:36 -06001415 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001416
1417 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1418 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1419
1420 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1421 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
John Kessenich1ff0c182019-10-10 12:01:13 -06001422 builder.addIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001423 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
John Kessenich8985fc92020-03-03 10:25:07 -07001424 }
Jeff Bolz36831c92018-09-05 10:11:41 -05001425 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001426 memoryModel = spv::MemoryModelVulkanKHR;
1427 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001428 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001429 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001430 builder.setMemoryModel(addressingModel, memoryModel);
1431
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001432 if (glslangIntermediate->usingVariablePointers()) {
1433 builder.addCapability(spv::CapabilityVariablePointers);
1434 }
1435
John Kessenicheee9d532016-09-19 18:09:30 -06001436 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1437 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001438
1439 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001440 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1441 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001442 builder.addSourceExtension(it->c_str());
1443
1444 // Add the top-level modes for this shader.
1445
John Kessenich92187592016-02-01 13:45:25 -07001446 if (glslangIntermediate->getXfbMode()) {
1447 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001448 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001449 }
John Kessenich140f3df2015-06-26 16:58:36 -06001450
1451 unsigned int mode;
1452 switch (glslangIntermediate->getStage()) {
1453 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001454 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001455 break;
1456
John Kessenicha28f7a72019-08-06 07:00:58 -06001457 case EShLangFragment:
1458 builder.addCapability(spv::CapabilityShader);
1459 if (glslangIntermediate->getPixelCenterInteger())
1460 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1461
1462 if (glslangIntermediate->getOriginUpperLeft())
1463 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1464 else
1465 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1466
1467 if (glslangIntermediate->getEarlyFragmentTests())
1468 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1469
1470 if (glslangIntermediate->getPostDepthCoverage()) {
1471 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1472 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1473 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1474 }
1475
John Kessenichb9197c82019-08-11 07:41:45 -06001476 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1477 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1478
1479#ifndef GLSLANG_WEB
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001480
John Kessenicha28f7a72019-08-06 07:00:58 -06001481 switch(glslangIntermediate->getDepth()) {
1482 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1483 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1484 default: mode = spv::ExecutionModeMax; break;
1485 }
1486 if (mode != spv::ExecutionModeMax)
1487 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001488 switch (glslangIntermediate->getInterlockOrdering()) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001489 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT;
1490 break;
1491 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT;
1492 break;
1493 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT;
1494 break;
1495 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT;
1496 break;
1497 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT;
1498 break;
1499 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT;
1500 break;
1501 default: mode = spv::ExecutionModeMax;
1502 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001503 }
1504 if (mode != spv::ExecutionModeMax) {
1505 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1506 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1507 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1508 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1509 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1510 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1511 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1512 } else {
1513 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1514 }
1515 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1516 }
John Kessenichb9197c82019-08-11 07:41:45 -06001517#endif
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001518 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001519
John Kessenicha28f7a72019-08-06 07:00:58 -06001520 case EShLangCompute:
1521 builder.addCapability(spv::CapabilityShader);
1522 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1523 glslangIntermediate->getLocalSize(1),
1524 glslangIntermediate->getLocalSize(2));
1525 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1526 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1527 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1528 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1529 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1530 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1531 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1532 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1533 }
1534 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001535#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001536 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001537 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001538 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001539
steve-lunarge7412492017-03-23 11:56:07 -06001540 glslang::TLayoutGeometry primitive;
1541
1542 if (glslangIntermediate->getStage() == EShLangTessControl) {
John Kessenich8985fc92020-03-03 10:25:07 -07001543 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1544 glslangIntermediate->getVertices());
steve-lunarge7412492017-03-23 11:56:07 -06001545 primitive = glslangIntermediate->getOutputPrimitive();
1546 } else {
1547 primitive = glslangIntermediate->getInputPrimitive();
1548 }
1549
1550 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001551 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1552 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1553 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001554 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001555 }
John Kessenich4016e382016-07-15 11:53:56 -06001556 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001557 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1558
John Kesseniche6903322015-10-13 16:29:02 -06001559 switch (glslangIntermediate->getVertexSpacing()) {
1560 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1561 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1562 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001563 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001564 }
John Kessenich4016e382016-07-15 11:53:56 -06001565 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001566 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1567
1568 switch (glslangIntermediate->getVertexOrder()) {
1569 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1570 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001571 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001572 }
John Kessenich4016e382016-07-15 11:53:56 -06001573 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001574 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1575
1576 if (glslangIntermediate->getPointMode())
1577 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001578 break;
1579
1580 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001581 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001582 switch (glslangIntermediate->getInputPrimitive()) {
1583 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1584 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1585 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001586 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001587 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001588 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001589 }
John Kessenich4016e382016-07-15 11:53:56 -06001590 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001591 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001592
John Kessenich140f3df2015-06-26 16:58:36 -06001593 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1594
1595 switch (glslangIntermediate->getOutputPrimitive()) {
1596 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1597 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1598 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001599 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001600 }
John Kessenich4016e382016-07-15 11:53:56 -06001601 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001602 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1603 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1604 break;
1605
Daniel Kochdb32b242020-03-17 20:42:47 -04001606 case EShLangRayGen:
1607 case EShLangIntersect:
1608 case EShLangAnyHit:
1609 case EShLangClosestHit:
1610 case EShLangMiss:
1611 case EShLangCallable:
1612 {
1613 auto& extensions = glslangIntermediate->getRequestedExtensions();
1614 if (extensions.find("GL_NV_ray_tracing") == extensions.end()) {
1615 builder.addCapability(spv::CapabilityRayTracingProvisionalKHR);
1616 builder.addExtension("SPV_KHR_ray_tracing");
1617 }
1618 else {
1619 builder.addCapability(spv::CapabilityRayTracingNV);
1620 builder.addExtension("SPV_NV_ray_tracing");
1621 }
Chao Chenb50c02e2018-09-19 11:42:24 -07001622 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04001623 }
Chao Chen3c366992018-09-19 11:41:59 -07001624 case EShLangTaskNV:
1625 case EShLangMeshNV:
1626 builder.addCapability(spv::CapabilityMeshShadingNV);
1627 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1628 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1629 glslangIntermediate->getLocalSize(1),
1630 glslangIntermediate->getLocalSize(2));
1631 if (glslangIntermediate->getStage() == EShLangMeshNV) {
John Kessenich8985fc92020-03-03 10:25:07 -07001632 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1633 glslangIntermediate->getVertices());
1634 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV,
1635 glslangIntermediate->getPrimitives());
Chao Chen3c366992018-09-19 11:41:59 -07001636
1637 switch (glslangIntermediate->getOutputPrimitive()) {
1638 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1639 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1640 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1641 default: mode = spv::ExecutionModeMax; break;
1642 }
1643 if (mode != spv::ExecutionModeMax)
1644 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1645 }
1646 break;
1647#endif
1648
John Kessenich140f3df2015-06-26 16:58:36 -06001649 default:
1650 break;
1651 }
John Kessenich140f3df2015-06-26 16:58:36 -06001652}
1653
John Kessenichfca82622016-11-26 13:23:20 -07001654// Finish creating SPV, after the traversal is complete.
1655void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001656{
John Kessenichf04c51b2018-08-03 15:56:12 -06001657 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001658 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001659 builder.setBuildPoint(shaderEntry->getLastBlock());
1660 builder.leaveFunction();
1661 }
1662
John Kessenich7ba63412015-12-20 17:37:07 -07001663 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001664 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1665 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001666
David Neto8c3d5b42019-10-21 14:50:31 -04001667 // Add capabilities, extensions, remove unneeded decorations, etc.,
John Kessenichf04c51b2018-08-03 15:56:12 -06001668 // based on the resulting SPIR-V.
David Neto8c3d5b42019-10-21 14:50:31 -04001669 // Note: WebGPU code generation must have the opportunity to aggressively
1670 // prune unreachable merge blocks and continue targets.
John Kessenichf04c51b2018-08-03 15:56:12 -06001671 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001672}
1673
John Kessenichfca82622016-11-26 13:23:20 -07001674// Write the SPV into 'out'.
1675void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001676{
John Kessenichfca82622016-11-26 13:23:20 -07001677 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001678}
1679
1680//
1681// Implement the traversal functions.
1682//
1683// Return true from interior nodes to have the external traversal
1684// continue on to children. Return false if children were
1685// already processed.
1686//
1687
1688//
qining25262b32016-05-06 17:25:16 -04001689// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001690// - uniform/input reads
1691// - output writes
1692// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1693// - something simple that degenerates into the last bullet
1694//
1695void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1696{
qining75d1d802016-04-06 14:42:01 -04001697 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
Roy05a5b532020-01-03 16:21:34 +08001698 if (symbol->getType().isStruct())
1699 glslangTypeToIdMap[symbol->getType().getStruct()] = symbol->getId();
1700
qining75d1d802016-04-06 14:42:01 -04001701 if (symbol->getType().getQualifier().isSpecConstant())
1702 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1703
John Kessenich140f3df2015-06-26 16:58:36 -06001704 // getSymbolId() will set up all the IO decorations on the first call.
1705 // Formal function parameters were mapped during makeFunctions().
1706 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001707
John Kessenich7ba63412015-12-20 17:37:07 -07001708 if (builder.isPointer(id)) {
John Kessenich9c14f772019-06-17 08:38:35 -06001709 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
John Kessenich7c7731e2019-01-04 16:47:06 +07001710 // Consider adding to the OpEntryPoint interface list.
1711 // Only looking at structures if they have at least one member.
1712 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1713 spv::StorageClass sc = builder.getStorageClass(id);
1714 // Before SPIR-V 1.4, we only want to include Input and Output.
1715 // Starting with SPIR-V 1.4, we want all globals.
1716 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1717 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001718 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001719 }
John Kessenich5f77d862017-09-19 11:09:59 -06001720 }
John Kessenich9c14f772019-06-17 08:38:35 -06001721
Daniel Kochdb32b242020-03-17 20:42:47 -04001722 // If the SPIR-V type is required to be different than the AST type
1723 // (for ex SubgroupMasks or 3x4 ObjectToWorld/WorldToObject matrices),
John Kessenich9c14f772019-06-17 08:38:35 -06001724 // translate now from the SPIR-V type to the AST type, for the consuming
1725 // operation.
1726 // Note this turns it from an l-value to an r-value.
1727 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1728 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1729 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001730 }
1731
1732 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001733 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001734 // Prepare to generate code for the access
1735
1736 // L-value chains will be computed left to right. We're on the symbol now,
1737 // which is the left-most part of the access chain, so now is "clear" time,
1738 // followed by setting the base.
1739 builder.clearAccessChain();
1740
1741 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001742 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001743 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001744 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001745 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001746 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001747 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001748 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001749 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1750 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001751 builder.setAccessChainRValue(id);
1752 else
1753 builder.setAccessChainLValue(id);
1754 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001755
John Kessenichb9197c82019-08-11 07:41:45 -06001756#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001757 // Process linkage-only nodes for any special additional interface work.
1758 if (linkageOnly) {
1759 if (glslangIntermediate->getHlslFunctionality1()) {
1760 // Map implicit counter buffers to their originating buffers, which should have been
1761 // seen by now, given earlier pruning of unused counters, and preservation of order
1762 // of declaration.
1763 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1764 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1765 // Save possible originating buffers for counter buffers, keyed by
1766 // making the potential counter-buffer name.
1767 std::string keyName = symbol->getName().c_str();
1768 keyName = glslangIntermediate->addCounterBufferName(keyName);
1769 counterOriginator[keyName] = symbol;
1770 } else {
1771 // Handle a counter buffer, by finding the saved originating buffer.
1772 std::string keyName = symbol->getName().c_str();
1773 auto it = counterOriginator.find(keyName);
1774 if (it != counterOriginator.end()) {
1775 id = getSymbolId(it->second);
1776 if (id != spv::NoResult) {
1777 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001778 if (counterId != spv::NoResult) {
1779 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001780 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001781 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001782 }
1783 }
1784 }
1785 }
1786 }
1787 }
John Kessenich155d3512019-08-08 23:29:20 -06001788#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001789}
1790
1791bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1792{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001793 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Roy05a5b532020-01-03 16:21:34 +08001794 if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
1795 glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
1796 }
1797 if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
1798 glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
1799 }
John Kesseniche485c7a2017-05-31 18:50:53 -06001800
qining40887662016-04-03 22:20:42 -04001801 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1802 if (node->getType().getQualifier().isSpecConstant())
1803 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1804
John Kessenich140f3df2015-06-26 16:58:36 -06001805 // First, handle special cases
1806 switch (node->getOp()) {
1807 case glslang::EOpAssign:
1808 case glslang::EOpAddAssign:
1809 case glslang::EOpSubAssign:
1810 case glslang::EOpMulAssign:
1811 case glslang::EOpVectorTimesMatrixAssign:
1812 case glslang::EOpVectorTimesScalarAssign:
1813 case glslang::EOpMatrixTimesScalarAssign:
1814 case glslang::EOpMatrixTimesMatrixAssign:
1815 case glslang::EOpDivAssign:
1816 case glslang::EOpModAssign:
1817 case glslang::EOpAndAssign:
1818 case glslang::EOpInclusiveOrAssign:
1819 case glslang::EOpExclusiveOrAssign:
1820 case glslang::EOpLeftShiftAssign:
1821 case glslang::EOpRightShiftAssign:
1822 // A bin-op assign "a += b" means the same thing as "a = a + b"
1823 // where a is evaluated before b. For a simple assignment, GLSL
1824 // says to evaluate the left before the right. So, always, left
1825 // node then right node.
1826 {
1827 // get the left l-value, save it away
1828 builder.clearAccessChain();
1829 node->getLeft()->traverse(this);
1830 spv::Builder::AccessChain lValue = builder.getAccessChain();
1831
1832 // evaluate the right
1833 builder.clearAccessChain();
1834 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001835 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001836
1837 if (node->getOp() != glslang::EOpAssign) {
1838 // the left is also an r-value
1839 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001840 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001841
1842 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001843 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001844 TranslateNoContractionDecoration(node->getType().getQualifier()),
1845 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001846 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001847 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1848 node->getType().getBasicType());
1849
1850 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001851 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001852 }
1853
1854 // store the result
1855 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001856 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001857
1858 // assignments are expressions having an rValue after they are evaluated...
1859 builder.clearAccessChain();
1860 builder.setAccessChainRValue(rValue);
1861 }
1862 return false;
1863 case glslang::EOpIndexDirect:
1864 case glslang::EOpIndexDirectStruct:
1865 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001866 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001867 // Get the left part of the access chain.
1868 node->getLeft()->traverse(this);
1869
1870 // Add the next element in the chain
1871
David Netoa901ffe2016-06-08 14:11:40 +01001872 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001873 if (! node->getLeft()->getType().isArray() &&
1874 node->getLeft()->getType().isVector() &&
1875 node->getOp() == glslang::EOpIndexDirect) {
1876 // This is essentially a hard-coded vector swizzle of size 1,
1877 // so short circuit the access-chain stuff with a swizzle.
1878 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001879 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001880 int dummySize;
1881 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1882 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001883 glslangIntermediate->getBaseAlignmentScalar(
1884 node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001885 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001886
1887 // Load through a block reference is performed with a dot operator that
1888 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1889 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001890 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001891 !node->getLeft()->getType().isArray() &&
1892 node->getOp() == glslang::EOpIndexDirectStruct)
1893 {
1894 spv::Id left = accessChainLoad(node->getLeft()->getType());
1895 builder.clearAccessChain();
1896 builder.setAccessChainLValue(left);
1897 }
1898
David Netoa901ffe2016-06-08 14:11:40 +01001899 int spvIndex = glslangIndex;
1900 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1901 node->getOp() == glslang::EOpIndexDirectStruct)
1902 {
1903 // This may be, e.g., an anonymous block-member selection, which generally need
1904 // index remapping due to hidden members in anonymous blocks.
Roy05a5b532020-01-03 16:21:34 +08001905 int glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
1906 if (memberRemapper.find(glslangId) != memberRemapper.end()) {
1907 std::vector<int>& remapper = memberRemapper[glslangId];
1908 assert(remapper.size() > 0);
1909 spvIndex = remapper[glslangIndex];
1910 }
David Netoa901ffe2016-06-08 14:11:40 +01001911 }
John Kessenichebb50532016-05-16 19:22:05 -06001912
David Netoa901ffe2016-06-08 14:11:40 +01001913 // normal case for indexing array or structure or block
John Kessenich8985fc92020-03-03 10:25:07 -07001914 builder.accessChainPush(builder.makeIntConstant(spvIndex),
1915 TranslateCoherent(node->getLeft()->getType()),
1916 node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001917
1918 // Add capabilities here for accessing PointSize and clip/cull distance.
1919 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001920 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001921 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001922 }
1923 }
1924 return false;
1925 case glslang::EOpIndexIndirect:
1926 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001927 // Array, matrix, or vector indirection with variable index.
1928 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001929 // matrices are arrays of vectors, so will also work for a matrix.
1930 // Will use the access chain's 'component' for variable index into a vector.
1931
1932 // This adapter is building access chains left to right.
1933 // Set up the access chain to the left.
1934 node->getLeft()->traverse(this);
1935
1936 // save it so that computing the right side doesn't trash it
1937 spv::Builder::AccessChain partial = builder.getAccessChain();
1938
1939 // compute the next index in the chain
1940 builder.clearAccessChain();
1941 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001942 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001943
John Kessenich5611c6d2018-04-05 11:25:02 -06001944 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1945
John Kessenich140f3df2015-06-26 16:58:36 -06001946 // restore the saved access chain
1947 builder.setAccessChain(partial);
1948
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001949 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1950 int dummySize;
1951 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1952 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001953 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1954 dummySize));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001955 } else
John Kessenich8985fc92020-03-03 10:25:07 -07001956 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()),
1957 node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001958 }
1959 return false;
1960 case glslang::EOpVectorSwizzle:
1961 {
1962 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001963 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001964 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001965 int dummySize;
1966 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1967 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001968 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1969 dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001970 }
1971 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001972 case glslang::EOpMatrixSwizzle:
1973 logger->missingFunctionality("matrix swizzle");
1974 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001975 case glslang::EOpLogicalOr:
1976 case glslang::EOpLogicalAnd:
1977 {
1978
1979 // These may require short circuiting, but can sometimes be done as straight
1980 // binary operations. The right operand must be short circuited if it has
1981 // side effects, and should probably be if it is complex.
1982 if (isTrivial(node->getRight()->getAsTyped()))
1983 break; // handle below as a normal binary operation
1984 // otherwise, we need to do dynamic short circuiting on the right operand
John Kessenich8985fc92020-03-03 10:25:07 -07001985 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(),
1986 *node->getRight()->getAsTyped());
John Kessenich7c1aa102015-10-15 13:29:11 -06001987 builder.clearAccessChain();
1988 builder.setAccessChainRValue(result);
1989 }
1990 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001991 default:
1992 break;
1993 }
1994
1995 // Assume generic binary op...
1996
John Kessenich32cfd492016-02-02 12:37:46 -07001997 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001998 builder.clearAccessChain();
1999 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002000 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002001
John Kessenich32cfd492016-02-02 12:37:46 -07002002 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06002003 builder.clearAccessChain();
2004 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002005 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002006
John Kessenich32cfd492016-02-02 12:37:46 -07002007 // get result
John Kessenichead86222018-03-28 18:01:20 -06002008 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002009 TranslateNoContractionDecoration(node->getType().getQualifier()),
2010 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002011 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07002012 convertGlslangToSpvType(node->getType()), left, right,
2013 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002014
John Kessenich50e57562015-12-21 21:21:11 -07002015 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06002016 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002017 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07002018 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06002019 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06002020 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06002021 return false;
2022 }
John Kessenich140f3df2015-06-26 16:58:36 -06002023}
2024
John Kessenich9c14f772019-06-17 08:38:35 -06002025// Figure out what, if any, type changes are needed when accessing a specific built-in.
2026// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
2027// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
Daniel Kochdb32b242020-03-17 20:42:47 -04002028std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(glslang::TBuiltInVariable glslangBuiltIn,
John Kessenich9c14f772019-06-17 08:38:35 -06002029 const glslang::TType& glslangType)
2030{
Daniel Kochdb32b242020-03-17 20:42:47 -04002031 switch(glslangBuiltIn)
John Kessenich9c14f772019-06-17 08:38:35 -06002032 {
Daniel Kochdb32b242020-03-17 20:42:47 -04002033 case glslang::EbvSubGroupEqMask:
2034 case glslang::EbvSubGroupGeMask:
2035 case glslang::EbvSubGroupGtMask:
2036 case glslang::EbvSubGroupLeMask:
2037 case glslang::EbvSubGroupLtMask: {
John Kessenich9c14f772019-06-17 08:38:35 -06002038 // these require changing a 64-bit scaler -> a vector of 32-bit components
2039 if (glslangType.isVector())
2040 break;
2041 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
2042 builder.makeUintType(64));
2043 return ret;
2044 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002045 // There are no SPIR-V builtins defined for these and map onto original non-transposed
2046 // builtins. During visitBinary we insert a transpose
2047 case glslang::EbvWorldToObject3x4:
2048 case glslang::EbvObjectToWorld3x4: {
2049 std::pair<spv::Id, spv::Id> ret(builder.makeMatrixType(builder.makeFloatType(32), 4, 3),
2050 builder.makeMatrixType(builder.makeFloatType(32), 3, 4)
2051 );
2052 return ret;
2053 }
John Kessenich9c14f772019-06-17 08:38:35 -06002054 default:
2055 break;
2056 }
2057
2058 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2059 return ret;
2060}
2061
2062// For an object previously identified (see getForcedType() and forceType)
2063// as needing type translations, do the translation needed for a load, turning
2064// an L-value into in R-value.
2065spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2066{
2067 const auto forceIt = forceType.find(object);
2068 if (forceIt == forceType.end())
2069 return object;
2070
2071 spv::Id desiredTypeId = forceIt->second;
2072 spv::Id objectTypeId = builder.getTypeId(object);
2073 assert(builder.isPointerType(objectTypeId));
2074 objectTypeId = builder.getContainedTypeId(objectTypeId);
2075 if (builder.isVectorType(objectTypeId) &&
2076 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2077 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2078 // handle 32-bit v.xy* -> 64-bit
2079 builder.clearAccessChain();
2080 builder.setAccessChainLValue(object);
2081 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2082 std::vector<spv::Id> components;
2083 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2084 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2085
2086 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2087 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2088 builder.createCompositeConstruct(vecType, components));
2089 } else {
2090 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2091 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002092 } else if (builder.isMatrixType(objectTypeId)) {
2093 // There are no SPIR-V builtins defined for 3x4 variants of ObjectToWorld/WorldToObject
2094 // and we insert a transpose after loading the original non-transposed builtins
2095 builder.clearAccessChain();
2096 builder.setAccessChainLValue(object);
2097 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2098 return builder.createUnaryOp(spv::OpTranspose, desiredTypeId, object);
2099
2100 } else {
John Kessenich9c14f772019-06-17 08:38:35 -06002101 logger->missingFunctionality("forcing non 32-bit vector type");
2102 }
2103
2104 return object;
2105}
2106
John Kessenich140f3df2015-06-26 16:58:36 -06002107bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2108{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002109 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002110
qining40887662016-04-03 22:20:42 -04002111 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2112 if (node->getType().getQualifier().isSpecConstant())
2113 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2114
John Kessenichfc51d282015-08-19 13:34:18 -06002115 spv::Id result = spv::NoResult;
2116
2117 // try texturing first
2118 result = createImageTextureFunctionCall(node);
2119 if (result != spv::NoResult) {
2120 builder.clearAccessChain();
2121 builder.setAccessChainRValue(result);
2122
2123 return false; // done with this node
2124 }
2125
2126 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002127
2128 if (node->getOp() == glslang::EOpArrayLength) {
2129 // Quite special; won't want to evaluate the operand.
2130
John Kessenich5611c6d2018-04-05 11:25:02 -06002131 // Currently, the front-end does not allow .length() on an array until it is sized,
2132 // except for the last block membeor of an SSBO.
2133 // TODO: If this changes, link-time sized arrays might show up here, and need their
2134 // size extracted.
2135
John Kessenichc9a80832015-09-12 12:17:44 -06002136 // Normal .length() would have been constant folded by the front-end.
2137 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002138 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002139
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002140 spv::Id length;
2141 if (node->getOperand()->getType().isCoopMat()) {
2142 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2143
2144 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2145 assert(builder.isCooperativeMatrixType(typeId));
2146
2147 length = builder.createCooperativeMatrixLength(typeId);
2148 } else {
2149 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2150 block->traverse(this);
John Kessenich8985fc92020-03-03 10:25:07 -07002151 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()
2152 ->getConstArray()[0].getUConst();
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002153 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2154 }
John Kessenichc9a80832015-09-12 12:17:44 -06002155
John Kessenich8c869672018-11-28 07:01:37 -07002156 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2157 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2158 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002159 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2160 if (builder.isInSpecConstCodeGenMode()) {
2161 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2162 } else {
2163 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2164 }
2165 }
John Kessenich8c869672018-11-28 07:01:37 -07002166
John Kessenichc9a80832015-09-12 12:17:44 -06002167 builder.clearAccessChain();
2168 builder.setAccessChainRValue(length);
2169
2170 return false;
2171 }
2172
John Kessenichfc51d282015-08-19 13:34:18 -06002173 // Start by evaluating the operand
2174
John Kessenich8c8505c2016-07-26 12:50:38 -06002175 // Does it need a swizzle inversion? If so, evaluation is inverted;
2176 // operate first on the swizzle base, then apply the swizzle.
2177 spv::Id invertedType = spv::NoType;
John Kessenich8985fc92020-03-03 10:25:07 -07002178 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2179 invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenich8c8505c2016-07-26 12:50:38 -06002180 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2181 invertedType = getInvertedSwizzleType(*node->getOperand());
2182
John Kessenich140f3df2015-06-26 16:58:36 -06002183 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002184 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002185 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002186 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002187 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002188 operandNode = node->getOperand();
2189
2190 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002191
Rex Xufc618912015-09-09 16:42:49 +08002192 spv::Id operand = spv::NoResult;
2193
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002194 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2195
John Kessenichfb4f2332019-08-09 03:49:15 -06002196#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002197 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2198 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002199 node->getOp() == glslang::EOpAtomicCounter ||
Neslisah Torosdagli7d37a682020-03-26 10:52:33 -04002200 node->getOp() == glslang::EOpInterpolateAtCentroid ||
2201 node->getOp() == glslang::EOpRayQueryProceed ||
2202 node->getOp() == glslang::EOpRayQueryGetRayTMin ||
2203 node->getOp() == glslang::EOpRayQueryGetRayFlags ||
2204 node->getOp() == glslang::EOpRayQueryGetWorldRayOrigin ||
2205 node->getOp() == glslang::EOpRayQueryGetWorldRayDirection ||
2206 node->getOp() == glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque ||
2207 node->getOp() == glslang::EOpRayQueryTerminate ||
2208 node->getOp() == glslang::EOpRayQueryConfirmIntersection) {
Rex Xufc618912015-09-09 16:42:49 +08002209 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002210 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2211 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2212 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002213#endif
2214 {
John Kessenich32cfd492016-02-02 12:37:46 -07002215 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002216 }
John Kessenich140f3df2015-06-26 16:58:36 -06002217
John Kessenichead86222018-03-28 18:01:20 -06002218 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002219 TranslateNoContractionDecoration(node->getType().getQualifier()),
2220 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002221
2222 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002223 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002224 result = createConversion(node->getOp(), decorations, resultType(), operand,
2225 node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002226
2227 // if not, then possibly an operation
2228 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002229 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand,
2230 node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002231
2232 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002233 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002234 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002235 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002236 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002237
John Kessenich140f3df2015-06-26 16:58:36 -06002238 builder.clearAccessChain();
2239 builder.setAccessChainRValue(result);
2240
2241 return false; // done with this node
2242 }
2243
2244 // it must be a special case, check...
2245 switch (node->getOp()) {
2246 case glslang::EOpPostIncrement:
2247 case glslang::EOpPostDecrement:
2248 case glslang::EOpPreIncrement:
2249 case glslang::EOpPreDecrement:
2250 {
2251 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002252 spv::Id one = 0;
2253 if (node->getBasicType() == glslang::EbtFloat)
2254 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002255#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002256 else if (node->getBasicType() == glslang::EbtDouble)
2257 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002258 else if (node->getBasicType() == glslang::EbtFloat16)
2259 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002260 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2261 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002262 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2263 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002264 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2265 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002266#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002267 else
2268 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002269 glslang::TOperator op;
2270 if (node->getOp() == glslang::EOpPreIncrement ||
2271 node->getOp() == glslang::EOpPostIncrement)
2272 op = glslang::EOpAdd;
2273 else
2274 op = glslang::EOpSub;
2275
John Kessenichead86222018-03-28 18:01:20 -06002276 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002277 convertGlslangToSpvType(node->getType()), operand, one,
2278 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002279 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002280
2281 // The result of operation is always stored, but conditionally the
2282 // consumed result. The consumed result is always an r-value.
2283 builder.accessChainStore(result);
2284 builder.clearAccessChain();
2285 if (node->getOp() == glslang::EOpPreIncrement ||
2286 node->getOp() == glslang::EOpPreDecrement)
2287 builder.setAccessChainRValue(result);
2288 else
2289 builder.setAccessChainRValue(operand);
2290 }
2291
2292 return false;
2293
John Kessenich155d3512019-08-08 23:29:20 -06002294#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002295 case glslang::EOpEmitStreamVertex:
2296 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2297 return false;
2298 case glslang::EOpEndStreamPrimitive:
2299 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2300 return false;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002301 case glslang::EOpRayQueryTerminate:
2302 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operand);
2303 return false;
2304 case glslang::EOpRayQueryConfirmIntersection:
2305 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operand);
2306 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002307#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002308
2309 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002310 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002311 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002312 }
John Kessenich140f3df2015-06-26 16:58:36 -06002313}
2314
Jeff Bolz53134492019-06-25 13:31:10 -05002315// Construct a composite object, recursively copying members if their types don't match
2316spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2317{
2318 for (int c = 0; c < (int)constituents.size(); ++c) {
2319 spv::Id& constituent = constituents[c];
2320 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2321 spv::Id rType = builder.getTypeId(constituent);
2322 if (lType != rType) {
2323 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2324 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2325 } else if (builder.isStructType(rType)) {
2326 std::vector<spv::Id> rTypeConstituents;
2327 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2328 for (int i = 0; i < numrTypeConstituents; ++i) {
John Kessenich8985fc92020-03-03 10:25:07 -07002329 rTypeConstituents.push_back(builder.createCompositeExtract(constituent,
2330 builder.getContainedTypeId(rType, i), i));
Jeff Bolz53134492019-06-25 13:31:10 -05002331 }
2332 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2333 } else {
2334 assert(builder.isArrayType(rType));
2335 std::vector<spv::Id> rTypeConstituents;
2336 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2337
2338 spv::Id elementRType = builder.getContainedTypeId(rType);
2339 for (int i = 0; i < numrTypeConstituents; ++i) {
2340 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2341 }
2342 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2343 }
2344 }
2345 }
2346 return builder.createCompositeConstruct(resultTypeId, constituents);
2347}
2348
John Kessenich140f3df2015-06-26 16:58:36 -06002349bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2350{
qining27e04a02016-04-14 16:40:20 -04002351 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2352 if (node->getType().getQualifier().isSpecConstant())
2353 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2354
John Kessenichfc51d282015-08-19 13:34:18 -06002355 spv::Id result = spv::NoResult;
John Kessenichbbbd9a22020-03-03 07:21:37 -07002356 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
John Kessenich8985fc92020-03-03 10:25:07 -07002357 spv::Builder::AccessChain complexLvalue; // for holding swizzling l-values too complex for SPIR-V,
2358 // for at out parameter
John Kessenichbbbd9a22020-03-03 07:21:37 -07002359 spv::Id temporaryLvalue = spv::NoResult; // temporary to pass, as proxy for complexLValue
2360
John Kessenich8985fc92020-03-03 10:25:07 -07002361 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2362 invertedType :
2363 convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002364
2365 // try texturing
2366 result = createImageTextureFunctionCall(node);
2367 if (result != spv::NoResult) {
2368 builder.clearAccessChain();
2369 builder.setAccessChainRValue(result);
2370
2371 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002372 }
2373#ifndef GLSLANG_WEB
2374 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002375 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002376 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002377 // "imageStore" is a special case, which has no result
2378 return false;
2379 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002380#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002381
John Kessenich140f3df2015-06-26 16:58:36 -06002382 glslang::TOperator binOp = glslang::EOpNull;
2383 bool reduceComparison = true;
2384 bool isMatrix = false;
2385 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002386 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002387
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002388 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2389
John Kessenich140f3df2015-06-26 16:58:36 -06002390 assert(node->getOp());
2391
John Kessenichf6640762016-08-01 19:44:00 -06002392 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002393
2394 switch (node->getOp()) {
2395 case glslang::EOpSequence:
2396 {
2397 if (preVisit)
2398 ++sequenceDepth;
2399 else
2400 --sequenceDepth;
2401
2402 if (sequenceDepth == 1) {
2403 // If this is the parent node of all the functions, we want to see them
2404 // early, so all call points have actual SPIR-V functions to reference.
2405 // In all cases, still let the traverser visit the children for us.
2406 makeFunctions(node->getAsAggregate()->getSequence());
2407
John Kessenich6fccb3c2016-09-19 16:01:41 -06002408 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002409 // anything else gets there, so visit out of order, doing them all now.
2410 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2411
John Kessenich6a60c2f2016-12-08 21:01:59 -07002412 // 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 -06002413 // so do them manually.
2414 visitFunctions(node->getAsAggregate()->getSequence());
2415
2416 return false;
2417 }
2418
2419 return true;
2420 }
2421 case glslang::EOpLinkerObjects:
2422 {
2423 if (visit == glslang::EvPreVisit)
2424 linkageOnly = true;
2425 else
2426 linkageOnly = false;
2427
2428 return true;
2429 }
2430 case glslang::EOpComma:
2431 {
2432 // processing from left to right naturally leaves the right-most
2433 // lying around in the access chain
2434 glslang::TIntermSequence& glslangOperands = node->getSequence();
2435 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2436 glslangOperands[i]->traverse(this);
2437
2438 return false;
2439 }
2440 case glslang::EOpFunction:
2441 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002442 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002443 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002444 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002445 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002446 } else {
2447 handleFunctionEntry(node);
2448 }
2449 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002450 if (inEntryPoint)
2451 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002452 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002453 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002454 }
2455
2456 return true;
2457 case glslang::EOpParameters:
2458 // Parameters will have been consumed by EOpFunction processing, but not
2459 // the body, so we still visited the function node's children, making this
2460 // child redundant.
2461 return false;
2462 case glslang::EOpFunctionCall:
2463 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002464 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002465 if (node->isUserDefined())
2466 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07002467 if (result) {
2468 builder.clearAccessChain();
2469 builder.setAccessChainRValue(result);
2470 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002471 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002472
2473 return false;
2474 }
2475 case glslang::EOpConstructMat2x2:
2476 case glslang::EOpConstructMat2x3:
2477 case glslang::EOpConstructMat2x4:
2478 case glslang::EOpConstructMat3x2:
2479 case glslang::EOpConstructMat3x3:
2480 case glslang::EOpConstructMat3x4:
2481 case glslang::EOpConstructMat4x2:
2482 case glslang::EOpConstructMat4x3:
2483 case glslang::EOpConstructMat4x4:
2484 case glslang::EOpConstructDMat2x2:
2485 case glslang::EOpConstructDMat2x3:
2486 case glslang::EOpConstructDMat2x4:
2487 case glslang::EOpConstructDMat3x2:
2488 case glslang::EOpConstructDMat3x3:
2489 case glslang::EOpConstructDMat3x4:
2490 case glslang::EOpConstructDMat4x2:
2491 case glslang::EOpConstructDMat4x3:
2492 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002493 case glslang::EOpConstructIMat2x2:
2494 case glslang::EOpConstructIMat2x3:
2495 case glslang::EOpConstructIMat2x4:
2496 case glslang::EOpConstructIMat3x2:
2497 case glslang::EOpConstructIMat3x3:
2498 case glslang::EOpConstructIMat3x4:
2499 case glslang::EOpConstructIMat4x2:
2500 case glslang::EOpConstructIMat4x3:
2501 case glslang::EOpConstructIMat4x4:
2502 case glslang::EOpConstructUMat2x2:
2503 case glslang::EOpConstructUMat2x3:
2504 case glslang::EOpConstructUMat2x4:
2505 case glslang::EOpConstructUMat3x2:
2506 case glslang::EOpConstructUMat3x3:
2507 case glslang::EOpConstructUMat3x4:
2508 case glslang::EOpConstructUMat4x2:
2509 case glslang::EOpConstructUMat4x3:
2510 case glslang::EOpConstructUMat4x4:
2511 case glslang::EOpConstructBMat2x2:
2512 case glslang::EOpConstructBMat2x3:
2513 case glslang::EOpConstructBMat2x4:
2514 case glslang::EOpConstructBMat3x2:
2515 case glslang::EOpConstructBMat3x3:
2516 case glslang::EOpConstructBMat3x4:
2517 case glslang::EOpConstructBMat4x2:
2518 case glslang::EOpConstructBMat4x3:
2519 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002520 case glslang::EOpConstructF16Mat2x2:
2521 case glslang::EOpConstructF16Mat2x3:
2522 case glslang::EOpConstructF16Mat2x4:
2523 case glslang::EOpConstructF16Mat3x2:
2524 case glslang::EOpConstructF16Mat3x3:
2525 case glslang::EOpConstructF16Mat3x4:
2526 case glslang::EOpConstructF16Mat4x2:
2527 case glslang::EOpConstructF16Mat4x3:
2528 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002529 isMatrix = true;
2530 // fall through
2531 case glslang::EOpConstructFloat:
2532 case glslang::EOpConstructVec2:
2533 case glslang::EOpConstructVec3:
2534 case glslang::EOpConstructVec4:
2535 case glslang::EOpConstructDouble:
2536 case glslang::EOpConstructDVec2:
2537 case glslang::EOpConstructDVec3:
2538 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002539 case glslang::EOpConstructFloat16:
2540 case glslang::EOpConstructF16Vec2:
2541 case glslang::EOpConstructF16Vec3:
2542 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002543 case glslang::EOpConstructBool:
2544 case glslang::EOpConstructBVec2:
2545 case glslang::EOpConstructBVec3:
2546 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002547 case glslang::EOpConstructInt8:
2548 case glslang::EOpConstructI8Vec2:
2549 case glslang::EOpConstructI8Vec3:
2550 case glslang::EOpConstructI8Vec4:
2551 case glslang::EOpConstructUint8:
2552 case glslang::EOpConstructU8Vec2:
2553 case glslang::EOpConstructU8Vec3:
2554 case glslang::EOpConstructU8Vec4:
2555 case glslang::EOpConstructInt16:
2556 case glslang::EOpConstructI16Vec2:
2557 case glslang::EOpConstructI16Vec3:
2558 case glslang::EOpConstructI16Vec4:
2559 case glslang::EOpConstructUint16:
2560 case glslang::EOpConstructU16Vec2:
2561 case glslang::EOpConstructU16Vec3:
2562 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002563 case glslang::EOpConstructInt:
2564 case glslang::EOpConstructIVec2:
2565 case glslang::EOpConstructIVec3:
2566 case glslang::EOpConstructIVec4:
2567 case glslang::EOpConstructUint:
2568 case glslang::EOpConstructUVec2:
2569 case glslang::EOpConstructUVec3:
2570 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002571 case glslang::EOpConstructInt64:
2572 case glslang::EOpConstructI64Vec2:
2573 case glslang::EOpConstructI64Vec3:
2574 case glslang::EOpConstructI64Vec4:
2575 case glslang::EOpConstructUint64:
2576 case glslang::EOpConstructU64Vec2:
2577 case glslang::EOpConstructU64Vec3:
2578 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002579 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002580 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002581 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002582 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002583 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002584 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002585 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002586 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002587 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002588 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002589 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002590 else if (node->getOp() == glslang::EOpConstructStruct ||
2591 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2592 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002593 std::vector<spv::Id> constituents;
2594 for (int c = 0; c < (int)arguments.size(); ++c)
2595 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002596 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002597 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002598 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002599 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002600 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002601
2602 builder.clearAccessChain();
2603 builder.setAccessChainRValue(constructed);
2604
2605 return false;
2606 }
2607
2608 // These six are component-wise compares with component-wise results.
2609 // Forward on to createBinaryOperation(), requesting a vector result.
2610 case glslang::EOpLessThan:
2611 case glslang::EOpGreaterThan:
2612 case glslang::EOpLessThanEqual:
2613 case glslang::EOpGreaterThanEqual:
2614 case glslang::EOpVectorEqual:
2615 case glslang::EOpVectorNotEqual:
2616 {
2617 // Map the operation to a binary
2618 binOp = node->getOp();
2619 reduceComparison = false;
2620 switch (node->getOp()) {
2621 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2622 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2623 default: binOp = node->getOp(); break;
2624 }
2625
2626 break;
2627 }
2628 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002629 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002630 binOp = glslang::EOpMul;
2631 break;
2632 case glslang::EOpOuterProduct:
2633 // two vectors multiplied to make a matrix
2634 binOp = glslang::EOpOuterProduct;
2635 break;
2636 case glslang::EOpDot:
2637 {
qining25262b32016-05-06 17:25:16 -04002638 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002639 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002640 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002641 binOp = glslang::EOpMul;
2642 break;
2643 }
2644 case glslang::EOpMod:
2645 // when an aggregate, this is the floating-point mod built-in function,
2646 // which can be emitted by the one in createBinaryOperation()
2647 binOp = glslang::EOpMod;
2648 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002649
John Kessenich140f3df2015-06-26 16:58:36 -06002650 case glslang::EOpEmitVertex:
2651 case glslang::EOpEndPrimitive:
2652 case glslang::EOpBarrier:
2653 case glslang::EOpMemoryBarrier:
2654 case glslang::EOpMemoryBarrierAtomicCounter:
2655 case glslang::EOpMemoryBarrierBuffer:
2656 case glslang::EOpMemoryBarrierImage:
2657 case glslang::EOpMemoryBarrierShared:
2658 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002659 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002660 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002661 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002662 case glslang::EOpWorkgroupMemoryBarrier:
2663 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002664 case glslang::EOpSubgroupBarrier:
2665 case glslang::EOpSubgroupMemoryBarrier:
2666 case glslang::EOpSubgroupMemoryBarrierBuffer:
2667 case glslang::EOpSubgroupMemoryBarrierImage:
2668 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002669 noReturnValue = true;
2670 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2671 break;
2672
John Kessenich426394d2015-07-23 10:22:48 -06002673 case glslang::EOpAtomicAdd:
2674 case glslang::EOpAtomicMin:
2675 case glslang::EOpAtomicMax:
2676 case glslang::EOpAtomicAnd:
2677 case glslang::EOpAtomicOr:
2678 case glslang::EOpAtomicXor:
2679 case glslang::EOpAtomicExchange:
2680 case glslang::EOpAtomicCompSwap:
2681 atomic = true;
2682 break;
2683
John Kesseniche5eee8f2019-10-18 01:03:11 -06002684#ifndef GLSLANG_WEB
2685 case glslang::EOpAtomicStore:
2686 noReturnValue = true;
2687 // fallthrough
2688 case glslang::EOpAtomicLoad:
2689 atomic = true;
2690 break;
2691
John Kessenich0d0c6d32017-07-23 16:08:26 -06002692 case glslang::EOpAtomicCounterAdd:
2693 case glslang::EOpAtomicCounterSubtract:
2694 case glslang::EOpAtomicCounterMin:
2695 case glslang::EOpAtomicCounterMax:
2696 case glslang::EOpAtomicCounterAnd:
2697 case glslang::EOpAtomicCounterOr:
2698 case glslang::EOpAtomicCounterXor:
2699 case glslang::EOpAtomicCounterExchange:
2700 case glslang::EOpAtomicCounterCompSwap:
2701 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2702 builder.addCapability(spv::CapabilityAtomicStorageOps);
2703 atomic = true;
2704 break;
2705
Ian Romanickb3bd4022019-01-21 08:57:25 -08002706 case glslang::EOpAbsDifference:
2707 case glslang::EOpAddSaturate:
2708 case glslang::EOpSubSaturate:
2709 case glslang::EOpAverage:
2710 case glslang::EOpAverageRounded:
2711 case glslang::EOpMul32x16:
2712 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2713 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2714 binOp = node->getOp();
2715 break;
2716
Daniel Kochdb32b242020-03-17 20:42:47 -04002717 case glslang::EOpIgnoreIntersection:
2718 case glslang::EOpTerminateRay:
2719 case glslang::EOpTrace:
2720 case glslang::EOpExecuteCallable:
Chao Chen3c366992018-09-19 11:41:59 -07002721 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2722 noReturnValue = true;
2723 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04002724 case glslang::EOpRayQueryInitialize:
2725 case glslang::EOpRayQueryTerminate:
2726 case glslang::EOpRayQueryGenerateIntersection:
2727 case glslang::EOpRayQueryConfirmIntersection:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002728 builder.addExtension("SPV_KHR_ray_query");
2729 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
Neslisah Torosdagli7d37a682020-03-26 10:52:33 -04002730 builder.addExtension("SPV_KHR_variable_pointers");
2731 builder.addCapability(spv::CapabilityVariablePointers);
Torosdagli06c2eee2020-03-19 11:09:57 -04002732 noReturnValue = true;
2733 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002734 case glslang::EOpRayQueryProceed:
2735 case glslang::EOpRayQueryGetIntersectionType:
2736 case glslang::EOpRayQueryGetRayTMin:
2737 case glslang::EOpRayQueryGetRayFlags:
2738 case glslang::EOpRayQueryGetIntersectionT:
2739 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2740 case glslang::EOpRayQueryGetIntersectionInstanceId:
2741 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2742 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2743 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2744 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2745 case glslang::EOpRayQueryGetIntersectionFrontFace:
2746 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
2747 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2748 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2749 case glslang::EOpRayQueryGetWorldRayDirection:
2750 case glslang::EOpRayQueryGetWorldRayOrigin:
2751 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2752 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2753 builder.addExtension("SPV_KHR_ray_query");
2754 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
Neslisah Torosdagli7d37a682020-03-26 10:52:33 -04002755 builder.addExtension("SPV_KHR_variable_pointers");
2756 builder.addCapability(spv::CapabilityVariablePointers);
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002757 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002758 case glslang::EOpCooperativeMatrixLoad:
2759 case glslang::EOpCooperativeMatrixStore:
2760 noReturnValue = true;
2761 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002762 case glslang::EOpBeginInvocationInterlock:
2763 case glslang::EOpEndInvocationInterlock:
2764 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2765 noReturnValue = true;
2766 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002767#endif
Chao Chen3c366992018-09-19 11:41:59 -07002768
Jeff Bolz04d73732019-05-31 13:06:01 -05002769 case glslang::EOpDebugPrintf:
2770 noReturnValue = true;
2771 break;
2772
John Kessenich140f3df2015-06-26 16:58:36 -06002773 default:
2774 break;
2775 }
2776
2777 //
2778 // See if it maps to a regular operation.
2779 //
John Kessenich140f3df2015-06-26 16:58:36 -06002780 if (binOp != glslang::EOpNull) {
2781 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2782 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2783 assert(left && right);
2784
2785 builder.clearAccessChain();
2786 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002787 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002788
2789 builder.clearAccessChain();
2790 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002791 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002792
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002793 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002794 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002795 TranslateNoContractionDecoration(node->getType().getQualifier()),
2796 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002797 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002798 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002799 left->getType().getBasicType(), reduceComparison);
2800
2801 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002802 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002803 builder.clearAccessChain();
2804 builder.setAccessChainRValue(result);
2805
2806 return false;
2807 }
2808
John Kessenich426394d2015-07-23 10:22:48 -06002809 //
2810 // Create the list of operands.
2811 //
John Kessenich140f3df2015-06-26 16:58:36 -06002812 glslang::TIntermSequence& glslangOperands = node->getSequence();
2813 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002814 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002815 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002816 // special case l-value operands; there are just a few
2817 bool lvalue = false;
2818 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002819 case glslang::EOpModf:
2820 if (arg == 1)
2821 lvalue = true;
2822 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002823
Torosdagli06c2eee2020-03-19 11:09:57 -04002824 case glslang::EOpRayQueryInitialize:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002825 case glslang::EOpRayQueryTerminate:
2826 case glslang::EOpRayQueryConfirmIntersection:
2827 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04002828 case glslang::EOpRayQueryGenerateIntersection:
2829 case glslang::EOpRayQueryGetIntersectionType:
2830 case glslang::EOpRayQueryGetIntersectionT:
2831 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2832 case glslang::EOpRayQueryGetIntersectionInstanceId:
2833 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2834 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2835 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2836 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2837 case glslang::EOpRayQueryGetIntersectionFrontFace:
2838 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2839 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2840 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2841 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2842 if (arg == 0)
2843 lvalue = true;
2844 break;
2845
John Kesseniche5eee8f2019-10-18 01:03:11 -06002846 case glslang::EOpAtomicAdd:
2847 case glslang::EOpAtomicMin:
2848 case glslang::EOpAtomicMax:
2849 case glslang::EOpAtomicAnd:
2850 case glslang::EOpAtomicOr:
2851 case glslang::EOpAtomicXor:
2852 case glslang::EOpAtomicExchange:
2853 case glslang::EOpAtomicCompSwap:
2854 if (arg == 0)
2855 lvalue = true;
2856 break;
2857
John Kessenicha28f7a72019-08-06 07:00:58 -06002858#ifndef GLSLANG_WEB
2859 case glslang::EOpFrexp:
2860 if (arg == 1)
2861 lvalue = true;
2862 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002863 case glslang::EOpInterpolateAtSample:
2864 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002865 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002866 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002867 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002868
2869 // Does it need a swizzle inversion? If so, evaluation is inverted;
2870 // operate first on the swizzle base, then apply the swizzle.
John Kessenichbbbd9a22020-03-03 07:21:37 -07002871 // That is, we transform
2872 //
2873 // interpolate(v.zy) -> interpolate(v).zy
2874 //
John Kessenichecba76f2017-01-06 00:34:48 -07002875 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002876 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
John Kessenich8985fc92020-03-03 10:25:07 -07002877 invertedType = convertGlslangToSpvType(
2878 glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
John Kessenich8c8505c2016-07-26 12:50:38 -06002879 }
Rex Xu7a26c172015-12-08 17:12:09 +08002880 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002881 case glslang::EOpAtomicLoad:
2882 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002883 case glslang::EOpAtomicCounterAdd:
2884 case glslang::EOpAtomicCounterSubtract:
2885 case glslang::EOpAtomicCounterMin:
2886 case glslang::EOpAtomicCounterMax:
2887 case glslang::EOpAtomicCounterAnd:
2888 case glslang::EOpAtomicCounterOr:
2889 case glslang::EOpAtomicCounterXor:
2890 case glslang::EOpAtomicCounterExchange:
2891 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002892 if (arg == 0)
2893 lvalue = true;
2894 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002895 case glslang::EOpAddCarry:
2896 case glslang::EOpSubBorrow:
2897 if (arg == 2)
2898 lvalue = true;
2899 break;
2900 case glslang::EOpUMulExtended:
2901 case glslang::EOpIMulExtended:
2902 if (arg >= 2)
2903 lvalue = true;
2904 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002905 case glslang::EOpCooperativeMatrixLoad:
2906 if (arg == 0 || arg == 1)
2907 lvalue = true;
2908 break;
2909 case glslang::EOpCooperativeMatrixStore:
2910 if (arg == 1)
2911 lvalue = true;
2912 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002913#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002914 default:
2915 break;
2916 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002917 builder.clearAccessChain();
2918 if (invertedType != spv::NoType && arg == 0)
2919 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2920 else
2921 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002922
John Kessenichb9197c82019-08-11 07:41:45 -06002923#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002924 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2925 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2926
2927 if (arg == 1) {
2928 // fold "element" parameter into the access chain
2929 spv::Builder::AccessChain save = builder.getAccessChain();
2930 builder.clearAccessChain();
2931 glslangOperands[2]->traverse(this);
2932
2933 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2934
2935 builder.setAccessChain(save);
2936
2937 // Point to the first element of the array.
John Kessenich8985fc92020-03-03 10:25:07 -07002938 builder.accessChainPush(elementId,
2939 TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
2940 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002941
2942 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2943 unsigned int alignment = builder.getAccessChain().alignment;
2944
2945 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2946 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2947 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2948 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2949 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
John Kessenich8985fc92020-03-03 10:25:07 -07002950 if (builder.getStorageClass(builder.getAccessChain().base) ==
2951 spv::StorageClassPhysicalStorageBufferEXT) {
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002952 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2953 }
2954
2955 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2956
2957 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2958 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2959 }
2960
John Kessenich8985fc92020-03-03 10:25:07 -07002961 if (memoryAccess &
2962 (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2963 memoryAccessOperands.push_back(spv::IdImmediate(true,
2964 builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002965 }
2966 } else if (arg == 2) {
2967 continue;
2968 }
2969 }
John Kessenichb9197c82019-08-11 07:41:45 -06002970#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002971
John Kessenichbbbd9a22020-03-03 07:21:37 -07002972 // for l-values, pass the address, for r-values, pass the value
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002973 if (lvalue) {
John Kessenichbbbd9a22020-03-03 07:21:37 -07002974 if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
2975 // SPIR-V cannot represent an l-value containing a swizzle that doesn't
2976 // reduce to a simple access chain. So, we need a temporary vector to
2977 // receive the result, and must later swizzle that into the original
2978 // l-value.
2979 complexLvalue = builder.getAccessChain();
John Kessenich8985fc92020-03-03 10:25:07 -07002980 temporaryLvalue = builder.createVariable(spv::StorageClassFunction,
2981 builder.accessChainGetInferredType(), "swizzleTemp");
John Kessenichbbbd9a22020-03-03 07:21:37 -07002982 operands.push_back(temporaryLvalue);
2983 } else {
2984 operands.push_back(builder.accessChainGetLValue());
2985 }
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002986 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2987 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2988 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002989 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Torosdagli06c2eee2020-03-19 11:09:57 -04002990 glslang::TOperator glslangOp = node->getOp();
2991 if (arg == 1 &&
2992 (glslangOp == glslang::EOpRayQueryGetIntersectionType ||
2993 glslangOp == glslang::EOpRayQueryGetIntersectionT ||
2994 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceCustomIndex ||
2995 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceId ||
2996 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset ||
2997 glslangOp == glslang::EOpRayQueryGetIntersectionGeometryIndex ||
2998 glslangOp == glslang::EOpRayQueryGetIntersectionPrimitiveIndex ||
2999 glslangOp == glslang::EOpRayQueryGetIntersectionBarycentrics ||
3000 glslangOp == glslang::EOpRayQueryGetIntersectionFrontFace ||
3001 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayDirection ||
3002 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayOrigin ||
3003 glslangOp == glslang::EOpRayQueryGetIntersectionObjectToWorld ||
3004 glslangOp == glslang::EOpRayQueryGetIntersectionWorldToObject
3005 )) {
3006 bool cond = glslangOperands[arg]->getAsConstantUnion()->getConstArray()[0].getBConst();
3007 operands.push_back(builder.makeIntConstant(cond ? 1 : 0));
3008 }
3009 else {
3010 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
3011 }
3012
John Kesseniche485c7a2017-05-31 18:50:53 -06003013 }
John Kessenich140f3df2015-06-26 16:58:36 -06003014 }
John Kessenich426394d2015-07-23 10:22:48 -06003015
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003016 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06003017#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003018 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
3019 std::vector<spv::IdImmediate> idImmOps;
3020
3021 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3022 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3023 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3024 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3025 // get the pointee type
3026 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
3027 assert(builder.isCooperativeMatrixType(typeId));
3028 // do the op
3029 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
3030 // store the result to the pointer (out param 'm')
3031 builder.createStore(result, operands[0]);
3032 result = 0;
3033 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
3034 std::vector<spv::IdImmediate> idImmOps;
3035
3036 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3037 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
3038 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3039 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3040 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3041
3042 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
3043 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06003044 } else
3045#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06003046 if (atomic) {
3047 // Handle all atomics
John Kessenich8985fc92020-03-03 10:25:07 -07003048 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
3049 lvalueCoherentFlags);
Jeff Bolz04d73732019-05-31 13:06:01 -05003050 } else if (node->getOp() == glslang::EOpDebugPrintf) {
3051 if (!nonSemanticDebugPrintf) {
3052 nonSemanticDebugPrintf = builder.import("NonSemantic.DebugPrintf");
3053 }
3054 result = builder.createBuiltinCall(builder.makeVoidType(), nonSemanticDebugPrintf, spv::NonSemanticDebugPrintfDebugPrintf, operands);
3055 builder.addExtension(spv::E_SPV_KHR_non_semantic_info);
John Kesseniche5eee8f2019-10-18 01:03:11 -06003056 } else {
John Kessenich426394d2015-07-23 10:22:48 -06003057 // Pass through to generic operations.
3058 switch (glslangOperands.size()) {
3059 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06003060 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06003061 break;
3062 case 1:
John Kessenichead86222018-03-28 18:01:20 -06003063 {
3064 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06003065 TranslateNoContractionDecoration(node->getType().getQualifier()),
3066 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06003067 result = createUnaryOperation(
3068 node->getOp(), decorations,
3069 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003070 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06003071 }
John Kessenich426394d2015-07-23 10:22:48 -06003072 break;
3073 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06003074 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06003075 break;
3076 }
John Kessenichbbbd9a22020-03-03 07:21:37 -07003077 if (invertedType != spv::NoResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003078 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenichbbbd9a22020-03-03 07:21:37 -07003079 else if (temporaryLvalue != spv::NoResult) {
3080 builder.setAccessChain(complexLvalue);
3081 builder.accessChainStore(builder.createLoad(temporaryLvalue));
3082 }
John Kessenich140f3df2015-06-26 16:58:36 -06003083 }
3084
3085 if (noReturnValue)
3086 return false;
3087
3088 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04003089 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07003090 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06003091 } else {
3092 builder.clearAccessChain();
3093 builder.setAccessChainRValue(result);
3094 return false;
3095 }
3096}
3097
John Kessenich433e9ff2017-01-26 20:31:11 -07003098// This path handles both if-then-else and ?:
3099// The if-then-else has a node type of void, while
3100// ?: has either a void or a non-void node type
3101//
3102// Leaving the result, when not void:
3103// GLSL only has r-values as the result of a :?, but
3104// if we have an l-value, that can be more efficient if it will
3105// become the base of a complex r-value expression, because the
3106// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06003107bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
3108{
John Kessenich0c1e71a2019-01-10 18:23:06 +07003109 // see if OpSelect can handle it
3110 const auto isOpSelectable = [&]() {
3111 if (node->getBasicType() == glslang::EbtVoid)
3112 return false;
3113 // OpSelect can do all other types starting with SPV 1.4
3114 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
3115 // pre-1.4, only scalars and vectors can be handled
3116 if ((!node->getType().isScalar() && !node->getType().isVector()))
3117 return false;
3118 }
3119 return true;
3120 };
3121
John Kessenich4bee5312018-02-20 21:29:05 -07003122 // See if it simple and safe, or required, to execute both sides.
3123 // Crucially, side effects must be either semantically required or avoided,
3124 // and there are performance trade-offs.
3125 // Return true if required or a good idea (and safe) to execute both sides,
3126 // false otherwise.
3127 const auto bothSidesPolicy = [&]() -> bool {
3128 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07003129 if (node->getTrueBlock() == nullptr ||
3130 node->getFalseBlock() == nullptr)
3131 return false;
3132
John Kessenich4bee5312018-02-20 21:29:05 -07003133 // required? (unless we write additional code to look for side effects
3134 // and make performance trade-offs if none are present)
3135 if (!node->getShortCircuit())
3136 return true;
3137
3138 // if not required to execute both, decide based on performance/practicality...
3139
John Kessenich0c1e71a2019-01-10 18:23:06 +07003140 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07003141 return false;
3142
John Kessenich433e9ff2017-01-26 20:31:11 -07003143 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
3144 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
3145
3146 // return true if a single operand to ? : is okay for OpSelect
3147 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003148 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07003149 };
3150
3151 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
3152 operandOkay(node->getFalseBlock()->getAsTyped());
3153 };
3154
John Kessenich4bee5312018-02-20 21:29:05 -07003155 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
3156 // emit the condition before doing anything with selection
3157 node->getCondition()->traverse(this);
3158 spv::Id condition = accessChainLoad(node->getCondition()->getType());
3159
3160 // Find a way of executing both sides and selecting the right result.
3161 const auto executeBothSides = [&]() -> void {
3162 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07003163 node->getTrueBlock()->traverse(this);
3164 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3165 node->getFalseBlock()->traverse(this);
3166 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3167
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003168 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003169
John Kessenich4bee5312018-02-20 21:29:05 -07003170 // done if void
3171 if (node->getBasicType() == glslang::EbtVoid)
3172 return;
John Kesseniche434ad92017-03-30 10:09:28 -06003173
John Kessenich4bee5312018-02-20 21:29:05 -07003174 // emit code to select between trueValue and falseValue
3175
3176 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07003177 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07003178 // Emit OpSelect for this selection.
3179
3180 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07003181 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
3182 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07003183 condition = builder.smearScalar(spv::NoPrecision, condition,
3184 builder.makeVectorType(builder.makeBoolType(),
3185 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07003186 }
John Kessenich4bee5312018-02-20 21:29:05 -07003187
3188 // OpSelect
3189 result = builder.createTriOp(spv::OpSelect,
3190 convertGlslangToSpvType(node->getType()), condition,
3191 trueValue, falseValue);
3192
3193 builder.clearAccessChain();
3194 builder.setAccessChainRValue(result);
3195 } else {
3196 // We need control flow to select the result.
3197 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
3198 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
3199
3200 // Selection control:
3201 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3202
3203 // make an "if" based on the value created by the condition
3204 spv::Builder::If ifBuilder(condition, control, builder);
3205
3206 // emit the "then" statement
3207 builder.createStore(trueValue, result);
3208 ifBuilder.makeBeginElse();
3209 // emit the "else" statement
3210 builder.createStore(falseValue, result);
3211
3212 // finish off the control flow
3213 ifBuilder.makeEndIf();
3214
3215 builder.clearAccessChain();
3216 builder.setAccessChainLValue(result);
3217 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003218 };
3219
John Kessenich4bee5312018-02-20 21:29:05 -07003220 // Execute the one side needed, as per the condition
3221 const auto executeOneSide = [&]() {
3222 // Always emit control flow.
3223 if (node->getBasicType() != glslang::EbtVoid)
3224 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07003225
John Kessenich4bee5312018-02-20 21:29:05 -07003226 // Selection control:
3227 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3228
3229 // make an "if" based on the value created by the condition
3230 spv::Builder::If ifBuilder(condition, control, builder);
3231
3232 // emit the "then" statement
3233 if (node->getTrueBlock() != nullptr) {
3234 node->getTrueBlock()->traverse(this);
3235 if (result != spv::NoResult)
3236 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3237 }
3238
3239 if (node->getFalseBlock() != nullptr) {
3240 ifBuilder.makeBeginElse();
3241 // emit the "else" statement
3242 node->getFalseBlock()->traverse(this);
3243 if (result != spv::NoResult)
3244 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3245 }
3246
3247 // finish off the control flow
3248 ifBuilder.makeEndIf();
3249
3250 if (result != spv::NoResult) {
3251 builder.clearAccessChain();
3252 builder.setAccessChainLValue(result);
3253 }
3254 };
3255
3256 // Try for OpSelect (or a requirement to execute both sides)
3257 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003258 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3259 if (node->getType().getQualifier().isSpecConstant())
3260 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003261 executeBothSides();
3262 } else
3263 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003264
3265 return false;
3266}
3267
3268bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3269{
3270 // emit and get the condition before doing anything with switch
3271 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003272 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003273
Rex Xu57e65922017-07-04 23:23:40 +08003274 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003275 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003276
John Kessenich140f3df2015-06-26 16:58:36 -06003277 // browse the children to sort out code segments
3278 int defaultSegment = -1;
3279 std::vector<TIntermNode*> codeSegments;
3280 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3281 std::vector<int> caseValues;
3282 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3283 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3284 TIntermNode* child = *c;
3285 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003286 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003287 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003288 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich8985fc92020-03-03 10:25:07 -07003289 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()
3290 ->getConstArray()[0].getIConst());
John Kessenich140f3df2015-06-26 16:58:36 -06003291 } else
3292 codeSegments.push_back(child);
3293 }
3294
qining25262b32016-05-06 17:25:16 -04003295 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003296 // statements between the last case and the end of the switch statement
3297 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3298 (int)codeSegments.size() == defaultSegment)
3299 codeSegments.push_back(nullptr);
3300
3301 // make the switch statement
3302 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
John Kessenich8985fc92020-03-03 10:25:07 -07003303 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment,
3304 segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003305
3306 // emit all the code in the segments
3307 breakForLoop.push(false);
3308 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3309 builder.nextSwitchSegment(segmentBlocks, s);
3310 if (codeSegments[s])
3311 codeSegments[s]->traverse(this);
3312 else
3313 builder.addSwitchBreak();
3314 }
3315 breakForLoop.pop();
3316
3317 builder.endSwitch(segmentBlocks);
3318
3319 return false;
3320}
3321
3322void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3323{
3324 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003325 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003326
3327 builder.clearAccessChain();
3328 builder.setAccessChainRValue(constant);
3329}
3330
3331bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3332{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003333 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003334 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003335
3336 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003337 std::vector<unsigned int> operands;
3338 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003339
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003340 // Spec requires back edges to target header blocks, and every header block
3341 // must dominate its merge block. Make a header block first to ensure these
3342 // conditions are met. By definition, it will contain OpLoopMerge, followed
3343 // by a block-ending branch. But we don't want to put any other body/test
3344 // instructions in it, since the body/test may have arbitrary instructions,
3345 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003346 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003347 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003348 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003349 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003350 spv::Block& test = builder.makeNewBlock();
3351 builder.createBranch(&test);
3352
3353 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003354 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003355 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003356 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3357
3358 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003359 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003360 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003361 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003362 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003363 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003364
3365 builder.setBuildPoint(&blocks.continue_target);
3366 if (node->getTerminal())
3367 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003368 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003369 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003370 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003371 builder.createBranch(&blocks.body);
3372
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003373 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003374 builder.setBuildPoint(&blocks.body);
3375 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003376 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003377 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003378 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003379
3380 builder.setBuildPoint(&blocks.continue_target);
3381 if (node->getTerminal())
3382 node->getTerminal()->traverse(this);
3383 if (node->getTest()) {
3384 node->getTest()->traverse(this);
3385 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003386 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003387 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003388 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003389 // TODO: unless there was a break/return/discard instruction
3390 // somewhere in the body, this is an infinite loop, so we should
3391 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003392 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003393 }
John Kessenich140f3df2015-06-26 16:58:36 -06003394 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003395 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003396 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003397 return false;
3398}
3399
3400bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3401{
3402 if (node->getExpression())
3403 node->getExpression()->traverse(this);
3404
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003405 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003406
John Kessenich140f3df2015-06-26 16:58:36 -06003407 switch (node->getFlowOp()) {
3408 case glslang::EOpKill:
3409 builder.makeDiscard();
3410 break;
3411 case glslang::EOpBreak:
3412 if (breakForLoop.top())
3413 builder.createLoopExit();
3414 else
3415 builder.addSwitchBreak();
3416 break;
3417 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003418 builder.createLoopContinue();
3419 break;
3420 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003421 if (node->getExpression()) {
3422 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3423 spv::Id returnId = accessChainLoad(glslangReturnType);
3424 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3425 builder.clearAccessChain();
3426 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3427 builder.setAccessChainLValue(copyId);
3428 multiTypeStore(glslangReturnType, returnId);
3429 returnId = builder.createLoad(copyId);
3430 }
3431 builder.makeReturn(false, returnId);
3432 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003433 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003434
3435 builder.clearAccessChain();
3436 break;
3437
John Kessenichb9197c82019-08-11 07:41:45 -06003438#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003439 case glslang::EOpDemote:
3440 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3441 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3442 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3443 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003444#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003445
John Kessenich140f3df2015-06-26 16:58:36 -06003446 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003447 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003448 break;
3449 }
3450
3451 return false;
3452}
3453
John Kessenich9c14f772019-06-17 08:38:35 -06003454spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003455{
qining25262b32016-05-06 17:25:16 -04003456 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003457 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003458 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003459 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003460 spv::Id result = createSpvConstant(*node);
3461 if (result != spv::NoResult)
3462 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003463 }
3464
3465 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003466 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003467 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3468 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003469
John Kessenichb9197c82019-08-11 07:41:45 -06003470 const bool contains16BitType = node->getType().contains16BitFloat() ||
3471 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003472 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003473 switch (storageClass) {
3474 case spv::StorageClassInput:
3475 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003476 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003477 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003478 break;
John Kessenich18310872018-05-14 22:08:53 -06003479 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003480 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003481 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3482 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003483 else
3484 builder.addCapability(spv::CapabilityStorageUniform16);
3485 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003486#ifndef GLSLANG_WEB
3487 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003488 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003489 builder.addCapability(spv::CapabilityStoragePushConstant16);
3490 break;
John Kessenich18310872018-05-14 22:08:53 -06003491 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003492 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003493 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003494 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3495 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003496#endif
John Kessenich18310872018-05-14 22:08:53 -06003497 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003498 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003499 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003500 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003501 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003502 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003503 }
3504 }
Rex Xuf89ad982017-04-07 23:22:33 +08003505
John Kessenichb9197c82019-08-11 07:41:45 -06003506 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003507 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003508 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003509 builder.addCapability(spv::CapabilityStoragePushConstant8);
3510 } else if (storageClass == spv::StorageClassUniform) {
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::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003513 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003514 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003515 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003516 } else {
3517 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003518 }
3519 }
3520
John Kessenich140f3df2015-06-26 16:58:36 -06003521 const char* name = node->getName().c_str();
3522 if (glslang::IsAnonymous(name))
3523 name = "";
3524
3525 return builder.createVariable(storageClass, spvType, name);
3526}
3527
3528// Return type Id of the sampled type.
3529spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3530{
3531 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003532 case glslang::EbtInt: return builder.makeIntType(32);
3533 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003534 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003535#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003536 case glslang::EbtFloat16:
3537 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3538 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3539 return builder.makeFloatType(16);
3540#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003541 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003542 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003543 return builder.makeFloatType(32);
3544 }
3545}
3546
John Kessenich8c8505c2016-07-26 12:50:38 -06003547// If node is a swizzle operation, return the type that should be used if
3548// the swizzle base is first consumed by another operation, before the swizzle
3549// is applied.
3550spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3551{
John Kessenichecba76f2017-01-06 00:34:48 -07003552 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003553 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3554 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3555 else
3556 return spv::NoType;
3557}
3558
3559// When inverting a swizzle with a parent op, this function
3560// will apply the swizzle operation to a completed parent operation.
John Kessenich8985fc92020-03-03 10:25:07 -07003561spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
3562 spv::Id parentResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003563{
3564 std::vector<unsigned> swizzle;
3565 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3566 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3567}
3568
John Kessenich8c8505c2016-07-26 12:50:38 -06003569// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3570void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3571{
3572 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3573 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3574 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3575}
3576
John Kessenich3ac051e2015-12-20 11:29:16 -07003577// Convert from a glslang type to an SPV type, by calling into a
3578// recursive version of this function. This establishes the inherited
3579// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003580spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003581{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003582 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003583}
3584
3585// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003586// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003587// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003588spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003589 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3590 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003591{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003592 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003593
3594 switch (type.getBasicType()) {
3595 case glslang::EbtVoid:
3596 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003597 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003598 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003599 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003600 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3601 // a 32-bit int where non-0 means true.
3602 if (explicitLayout != glslang::ElpNone)
3603 spvType = builder.makeUintType(32);
3604 else
3605 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003606 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003607 case glslang::EbtInt:
3608 spvType = builder.makeIntType(32);
3609 break;
3610 case glslang::EbtUint:
3611 spvType = builder.makeUintType(32);
3612 break;
3613 case glslang::EbtFloat:
3614 spvType = builder.makeFloatType(32);
3615 break;
3616#ifndef GLSLANG_WEB
3617 case glslang::EbtDouble:
3618 spvType = builder.makeFloatType(64);
3619 break;
3620 case glslang::EbtFloat16:
3621 spvType = builder.makeFloatType(16);
3622 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003623 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003624 spvType = builder.makeIntType(8);
3625 break;
3626 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003627 spvType = builder.makeUintType(8);
3628 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003629 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003630 spvType = builder.makeIntType(16);
3631 break;
3632 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003633 spvType = builder.makeUintType(16);
3634 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003635 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003636 spvType = builder.makeIntType(64);
3637 break;
3638 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003639 spvType = builder.makeUintType(64);
3640 break;
John Kessenich426394d2015-07-23 10:22:48 -06003641 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003642 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003643 spvType = builder.makeUintType(32);
3644 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04003645 case glslang::EbtAccStruct:
3646 spvType = builder.makeAccelerationStructureType();
Chao Chenb50c02e2018-09-19 11:42:24 -07003647 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04003648 case glslang::EbtRayQuery:
3649 spvType = builder.makeRayQueryType();
3650 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003651 case glslang::EbtReference:
3652 {
3653 // Make the forward pointer, then recurse to convert the structure type, then
3654 // patch up the forward pointer with a real pointer type.
3655 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3656 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3657 forwardPointers[type.getReferentType()] = forwardId;
3658 }
3659 spvType = forwardPointers[type.getReferentType()];
3660 if (!forwardReferenceOnly) {
3661 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3662 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3663 forwardPointers[type.getReferentType()],
3664 referentType);
3665 }
3666 }
3667 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003668#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003669 case glslang::EbtSampler:
3670 {
3671 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003672 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003673 spvType = builder.makeSamplerType();
3674 } else {
3675 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003676 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3677 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3678 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3679 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003680 // already has both image and sampler, make the combined type
3681 spvType = builder.makeSampledImageType(spvType);
3682 }
John Kessenich55e7d112015-11-15 21:33:39 -07003683 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003684 }
John Kessenich140f3df2015-06-26 16:58:36 -06003685 break;
3686 case glslang::EbtStruct:
3687 case glslang::EbtBlock:
3688 {
3689 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003690 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003691
3692 // Try to share structs for different layouts, but not yet for other
3693 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003694 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003695 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003696 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003697 break;
3698
3699 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003700 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003701 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003702 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003703 }
3704 break;
Jeff Bolz04d73732019-05-31 13:06:01 -05003705 case glslang::EbtString:
3706 // no type used for OpString
3707 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003708 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003709 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003710 break;
3711 }
3712
3713 if (type.isMatrix())
3714 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3715 else {
3716 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3717 if (type.getVectorSize() > 1)
3718 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3719 }
3720
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003721 if (type.isCoopMat()) {
3722 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3723 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3724 if (type.getBasicType() == glslang::EbtFloat16)
3725 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003726 if (type.getBasicType() == glslang::EbtUint8 ||
3727 type.getBasicType() == glslang::EbtInt8) {
3728 builder.addCapability(spv::CapabilityInt8);
3729 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003730
3731 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3732 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3733 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3734
3735 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3736 }
3737
John Kessenich140f3df2015-06-26 16:58:36 -06003738 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003739 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3740
John Kessenichc9a80832015-09-12 12:17:44 -06003741 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003742 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003743 // We need to decorate array strides for types needing explicit layout, except blocks.
3744 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003745 // Use a dummy glslang type for querying internal strides of
3746 // arrays of arrays, but using just a one-dimensional array.
3747 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003748 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3749 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003750
3751 // Will compute the higher-order strides here, rather than making a whole
3752 // pile of types and doing repetitive recursion on their contents.
3753 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3754 }
John Kessenichf8842e52016-01-04 19:22:56 -07003755
3756 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003757 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003758 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003759 if (stride > 0)
3760 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003761 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003762 }
3763 } else {
3764 // single-dimensional array, and don't yet have stride
3765
John Kessenichf8842e52016-01-04 19:22:56 -07003766 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003767 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3768 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003769 }
John Kessenich31ed4832015-09-09 17:51:38 -06003770
John Kessenichead86222018-03-28 18:01:20 -06003771 // Do the outer dimension, which might not be known for a runtime-sized array.
3772 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3773 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003774 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003775 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003776#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003777 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003778 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003779 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3780 }
John Kessenichb9197c82019-08-11 07:41:45 -06003781#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003782 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003783 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003784 if (stride > 0)
3785 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003786 }
3787
3788 return spvType;
3789}
3790
John Kessenich0e737842017-03-24 18:38:16 -06003791// TODO: this functionality should exist at a higher level, in creating the AST
3792//
3793// Identify interface members that don't have their required extension turned on.
3794//
3795bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3796{
John Kessenicha28f7a72019-08-06 07:00:58 -06003797#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003798 auto& extensions = glslangIntermediate->getRequestedExtensions();
3799
Rex Xubcf291a2017-03-29 23:01:36 +08003800 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3801 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3802 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003803 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3804 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3805 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003806
3807 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3808 if (member.getFieldName() == "gl_ViewportMask" &&
3809 extensions.find("GL_NV_viewport_array2") == extensions.end())
3810 return true;
3811 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3812 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3813 return true;
3814 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3815 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3816 return true;
3817 }
3818#endif
John Kessenich0e737842017-03-24 18:38:16 -06003819
3820 return false;
3821};
3822
John Kessenich6090df02016-06-30 21:18:02 -06003823// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3824// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3825// Mutually recursive with convertGlslangToSpvType().
3826spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3827 const glslang::TTypeList* glslangMembers,
3828 glslang::TLayoutPacking explicitLayout,
3829 const glslang::TQualifier& qualifier)
3830{
3831 // Create a vector of struct types for SPIR-V to consume
3832 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07003833 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
3834 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003835 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003836 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3837 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3838 if (glslangMember.hiddenMember()) {
3839 ++memberDelta;
3840 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003841 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06003842 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003843 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003844 if (filterMember(glslangMember)) {
3845 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08003846 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003847 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003848 }
Roy05a5b532020-01-03 16:21:34 +08003849 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003850 }
John Kessenich6090df02016-06-30 21:18:02 -06003851 // modify just this child's view of the qualifier
3852 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3853 InheritQualifiers(memberQualifier, qualifier);
3854
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003855 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003856 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003857 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003858
3859 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003860 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3861 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003862
3863 // Make forward pointers for any pointer members, and create a list of members to
3864 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003865 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003866 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3867 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3868 }
3869 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003870 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3871 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003872 } else {
3873 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003874 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3875 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003876 }
John Kessenich6090df02016-06-30 21:18:02 -06003877 }
3878 }
3879
3880 // Make the SPIR-V type
3881 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003882 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003883 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3884
3885 // Decorate it
3886 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3887
John Kessenichd72f4882019-01-16 14:55:37 +07003888 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003889 auto it = deferredForwardPointers[i];
3890 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3891 }
3892
John Kessenich6090df02016-06-30 21:18:02 -06003893 return spvType;
3894}
3895
3896void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3897 const glslang::TTypeList* glslangMembers,
3898 glslang::TLayoutPacking explicitLayout,
3899 const glslang::TQualifier& qualifier,
3900 spv::Id spvType)
3901{
3902 // Name and decorate the non-hidden members
3903 int offset = -1;
3904 int locationOffset = 0; // for use within the members of this struct
3905 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3906 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3907 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003908 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08003909 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06003910 if (filterMember(glslangMember))
3911 continue;
3912 }
John Kessenich6090df02016-06-30 21:18:02 -06003913
3914 // modify just this child's view of the qualifier
3915 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3916 InheritQualifiers(memberQualifier, qualifier);
3917
3918 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003919 if (member < 0)
3920 continue;
3921
3922 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3923 builder.addMemberDecoration(spvType, member,
3924 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3925 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3926 // Add interpolation and auxiliary storage decorations only to
3927 // top-level members of Input and Output storage classes
3928 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3929 type.getQualifier().storage == glslang::EvqVaryingOut) {
3930 if (type.getBasicType() == glslang::EbtBlock ||
3931 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3932 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3933 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003934#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003935 addMeshNVDecoration(spvType, member, memberQualifier);
3936#endif
John Kessenich6090df02016-06-30 21:18:02 -06003937 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003938 }
3939 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003940
John Kessenichb9197c82019-08-11 07:41:45 -06003941#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003942 if (type.getBasicType() == glslang::EbtBlock &&
3943 qualifier.storage == glslang::EvqBuffer) {
3944 // Add memory decorations only to top-level members of shader storage block
3945 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003946 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003947 for (unsigned int i = 0; i < memory.size(); ++i)
3948 builder.addMemberDecoration(spvType, member, memory[i]);
3949 }
John Kessenichf8d1d742019-10-21 06:55:11 -06003950
John Kessenichb9197c82019-08-11 07:41:45 -06003951#endif
John Kessenich6090df02016-06-30 21:18:02 -06003952
John Kessenich5d610ee2018-03-07 18:05:55 -07003953 // Location assignment was already completed correctly by the front end,
3954 // just track whether a member needs to be decorated.
3955 // Ignore member locations if the container is an array, as that's
3956 // ill-specified and decisions have been made to not allow this.
3957 if (! type.isArray() && memberQualifier.hasLocation())
3958 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003959
John Kessenich5d610ee2018-03-07 18:05:55 -07003960 if (qualifier.hasLocation()) // track for upcoming inheritance
3961 locationOffset += glslangIntermediate->computeTypeLocationSize(
3962 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003963
John Kessenich5d610ee2018-03-07 18:05:55 -07003964 // component, XFB, others
3965 if (glslangMember.getQualifier().hasComponent())
3966 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3967 glslangMember.getQualifier().layoutComponent);
3968 if (glslangMember.getQualifier().hasXfbOffset())
3969 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3970 glslangMember.getQualifier().layoutXfbOffset);
3971 else if (explicitLayout != glslang::ElpNone) {
3972 // figure out what to do with offset, which is accumulating
3973 int nextOffset;
3974 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3975 if (offset >= 0)
3976 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3977 offset = nextOffset;
3978 }
John Kessenich6090df02016-06-30 21:18:02 -06003979
John Kessenich5d610ee2018-03-07 18:05:55 -07003980 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3981 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3982 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003983
John Kessenich5d610ee2018-03-07 18:05:55 -07003984 // built-in variable decorations
3985 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3986 if (builtIn != spv::BuiltInMax)
3987 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003988
John Kessenichb9197c82019-08-11 07:41:45 -06003989#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003990 // nonuniform
3991 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3992
John Kessenichead86222018-03-28 18:01:20 -06003993 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3994 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3995 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3996 memberQualifier.semanticName);
3997 }
3998
John Kessenich5d610ee2018-03-07 18:05:55 -07003999 if (builtIn == spv::BuiltInLayer) {
4000 // SPV_NV_viewport_array2 extension
4001 if (glslangMember.getQualifier().layoutViewportRelative){
4002 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
4003 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4004 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08004005 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004006 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
4007 builder.addMemberDecoration(spvType, member,
4008 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
4009 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
4010 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4011 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08004012 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004013 }
4014 if (glslangMember.getQualifier().layoutPassthrough) {
4015 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
4016 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
4017 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4018 }
chaoc771d89f2017-01-13 01:10:53 -08004019#endif
John Kessenich6090df02016-06-30 21:18:02 -06004020 }
4021
4022 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07004023 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
4024 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06004025}
4026
John Kessenich6c292d32016-02-15 20:58:50 -07004027// Turn the expression forming the array size into an id.
4028// This is not quite trivial, because of specialization constants.
4029// Sometimes, a raw constant is turned into an Id, and sometimes
4030// a specialization constant expression is.
4031spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
4032{
4033 // First, see if this is sized with a node, meaning a specialization constant:
4034 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
4035 if (specNode != nullptr) {
4036 builder.clearAccessChain();
4037 specNode->traverse(this);
4038 return accessChainLoad(specNode->getAsTyped()->getType());
4039 }
qining25262b32016-05-06 17:25:16 -04004040
John Kessenich6c292d32016-02-15 20:58:50 -07004041 // Otherwise, need a compile-time (front end) size, get it:
4042 int size = arraySizes.getDimSize(dim);
4043 assert(size > 0);
4044 return builder.makeUintConstant(size);
4045}
4046
John Kessenich103bef92016-02-08 21:38:15 -07004047// Wrap the builder's accessChainLoad to:
4048// - localize handling of RelaxedPrecision
4049// - use the SPIR-V inferred type instead of another conversion of the glslang type
4050// (avoids unnecessary work and possible type punning for structures)
4051// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07004052spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
4053{
John Kessenich103bef92016-02-08 21:38:15 -07004054 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004055
4056 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4057 coherentFlags |= TranslateCoherent(type);
4058
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004059 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004060 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004061
John Kessenich5611c6d2018-04-05 11:25:02 -06004062 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
John Kessenich8985fc92020-03-03 10:25:07 -07004063 TranslateNonUniformDecoration(type.getQualifier()),
4064 nominalTypeId,
4065 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
4066 TranslateMemoryScope(coherentFlags),
4067 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07004068
4069 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08004070 if (type.getBasicType() == glslang::EbtBool) {
4071 if (builder.isScalarType(nominalTypeId)) {
4072 // Conversion for bool
4073 spv::Id boolType = builder.makeBoolType();
4074 if (nominalTypeId != boolType)
4075 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
4076 } else if (builder.isVectorType(nominalTypeId)) {
4077 // Conversion for bvec
4078 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4079 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
4080 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07004081 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
4082 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004083 }
4084 }
John Kessenich103bef92016-02-08 21:38:15 -07004085
4086 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07004087}
4088
Rex Xu27253232016-02-23 17:51:09 +08004089// Wrap the builder's accessChainStore to:
4090// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06004091//
4092// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08004093void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
4094{
4095 // Need to convert to abstract types when necessary
4096 if (type.getBasicType() == glslang::EbtBool) {
4097 spv::Id nominalTypeId = builder.accessChainGetInferredType();
4098
4099 if (builder.isScalarType(nominalTypeId)) {
4100 // Conversion for bool
4101 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06004102 if (nominalTypeId != boolType) {
4103 // keep these outside arguments, for determinant order-of-evaluation
4104 spv::Id one = builder.makeUintConstant(1);
4105 spv::Id zero = builder.makeUintConstant(0);
4106 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
4107 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06004108 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08004109 } else if (builder.isVectorType(nominalTypeId)) {
4110 // Conversion for bvec
4111 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4112 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06004113 if (nominalTypeId != bvecType) {
4114 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06004115 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
4116 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
4117 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06004118 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06004119 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
4120 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004121 }
4122 }
4123
Jeff Bolz36831c92018-09-05 10:11:41 -05004124 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4125 coherentFlags |= TranslateCoherent(type);
4126
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004127 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004128 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004129
Jeff Bolz36831c92018-09-05 10:11:41 -05004130 builder.accessChainStore(rvalue,
John Kessenich8985fc92020-03-03 10:25:07 -07004131 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
4132 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004133 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08004134}
4135
John Kessenich4bf71552016-09-02 11:20:21 -06004136// For storing when types match at the glslang level, but not might match at the
4137// SPIR-V level.
4138//
4139// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004140// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004141// as in a member-decorated way.
4142//
4143// NOTE: This function can handle any store request; if it's not special it
4144// simplifies to a simple OpStore.
4145//
4146// Implicitly uses the existing builder.accessChain as the storage target.
4147void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4148{
John Kessenichb3e24e42016-09-11 12:33:43 -06004149 // we only do the complex path here if it's an aggregate
4150 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004151 accessChainStore(type, rValue);
4152 return;
4153 }
4154
John Kessenichb3e24e42016-09-11 12:33:43 -06004155 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004156 spv::Id rType = builder.getTypeId(rValue);
4157 spv::Id lValue = builder.accessChainGetLValue();
4158 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4159 if (lType == rType) {
4160 accessChainStore(type, rValue);
4161 return;
4162 }
4163
John Kessenichb3e24e42016-09-11 12:33:43 -06004164 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004165 // where the two types were the same type in GLSL. This requires member
4166 // by member copy, recursively.
4167
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004168 // SPIR-V 1.4 added an instruction to do help do this.
4169 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4170 // However, bool in uniform space is changed to int, so
4171 // OpCopyLogical does not work for that.
4172 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4173 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4174 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4175 if (lBool == rBool) {
4176 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4177 accessChainStore(type, logicalCopy);
4178 return;
4179 }
4180 }
4181
John Kessenichb3e24e42016-09-11 12:33:43 -06004182 // If an array, copy element by element.
4183 if (type.isArray()) {
4184 glslang::TType glslangElementType(type, 0);
4185 spv::Id elementRType = builder.getContainedTypeId(rType);
4186 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4187 // get the source member
4188 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004189
John Kessenichb3e24e42016-09-11 12:33:43 -06004190 // set up the target storage
4191 builder.clearAccessChain();
4192 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004193 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4194 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004195
John Kessenichb3e24e42016-09-11 12:33:43 -06004196 // store the member
4197 multiTypeStore(glslangElementType, elementRValue);
4198 }
4199 } else {
4200 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004201
John Kessenichb3e24e42016-09-11 12:33:43 -06004202 // loop over structure members
4203 const glslang::TTypeList& members = *type.getStruct();
4204 for (int m = 0; m < (int)members.size(); ++m) {
4205 const glslang::TType& glslangMemberType = *members[m].type;
4206
4207 // get the source member
4208 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4209 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4210
4211 // set up the target storage
4212 builder.clearAccessChain();
4213 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004214 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4215 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004216
4217 // store the member
4218 multiTypeStore(glslangMemberType, memberRValue);
4219 }
John Kessenich4bf71552016-09-02 11:20:21 -06004220 }
4221}
4222
John Kessenichf85e8062015-12-19 13:57:10 -07004223// Decide whether or not this type should be
4224// decorated with offsets and strides, and if so
4225// whether std140 or std430 rules should be applied.
4226glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004227{
John Kessenichf85e8062015-12-19 13:57:10 -07004228 // has to be a block
4229 if (type.getBasicType() != glslang::EbtBlock)
4230 return glslang::ElpNone;
4231
Chao Chen3c366992018-09-19 11:41:59 -07004232 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004233 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004234 type.getQualifier().storage != glslang::EvqBuffer &&
4235 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004236 return glslang::ElpNone;
4237
4238 // return the layout to use
4239 switch (type.getQualifier().layoutPacking) {
4240 case glslang::ElpStd140:
4241 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004242 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004243 return type.getQualifier().layoutPacking;
4244 default:
4245 return glslang::ElpNone;
4246 }
John Kessenich31ed4832015-09-09 17:51:38 -06004247}
4248
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004249// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004250int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4251 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004252{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004253 int size;
John Kessenich49987892015-12-29 17:11:44 -07004254 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004255 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4256 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004257
4258 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004259}
4260
John Kessenich49987892015-12-29 17:11:44 -07004261// 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 -07004262// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004263int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4264 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004265{
John Kessenich49987892015-12-29 17:11:44 -07004266 glslang::TType elementType;
4267 elementType.shallowCopy(matrixType);
4268 elementType.clearArraySizes();
4269
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004270 int size;
John Kessenich49987892015-12-29 17:11:44 -07004271 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004272 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4273 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004274
4275 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004276}
4277
John Kessenich5e4b1242015-08-06 22:53:06 -06004278// Given a member type of a struct, realign the current offset for it, and compute
4279// the next (not yet aligned) offset for the next member, which will get aligned
4280// on the next call.
4281// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4282// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4283// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004284void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4285 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004286{
4287 // this will get a positive value when deemed necessary
4288 nextOffset = -1;
4289
John Kessenich5e4b1242015-08-06 22:53:06 -06004290 // override anything in currentOffset with user-set offset
4291 if (memberType.getQualifier().hasOffset())
4292 currentOffset = memberType.getQualifier().layoutOffset;
4293
4294 // It could be that current linker usage in glslang updated all the layoutOffset,
4295 // in which case the following code does not matter. But, that's not quite right
4296 // once cross-compilation unit GLSL validation is done, as the original user
4297 // settings are needed in layoutOffset, and then the following will come into play.
4298
John Kessenichf85e8062015-12-19 13:57:10 -07004299 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004300 if (! memberType.getQualifier().hasOffset())
4301 currentOffset = -1;
4302
4303 return;
4304 }
4305
John Kessenichf85e8062015-12-19 13:57:10 -07004306 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004307 if (currentOffset < 0)
4308 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004309
John Kessenich5e4b1242015-08-06 22:53:06 -06004310 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4311 // but possibly not yet correctly aligned.
4312
4313 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004314 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004315 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4316 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004317
4318 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004319 // TODO: make this consistent in early phases of code:
4320 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4321 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4322 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004323 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004324 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004325 int dummySize;
4326 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4327 if (componentAlignment <= 4)
4328 memberAlignment = componentAlignment;
4329 }
4330
4331 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004332 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004333
4334 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004335 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4336 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004337 glslang::RoundToPow2(currentOffset, 16);
4338
John Kessenich5e4b1242015-08-06 22:53:06 -06004339 nextOffset = currentOffset + memberSize;
4340}
4341
David Netoa901ffe2016-06-08 14:11:40 +01004342void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004343{
David Netoa901ffe2016-06-08 14:11:40 +01004344 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4345 switch (glslangBuiltIn)
4346 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004347 case glslang::EbvPointSize:
4348#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004349 case glslang::EbvClipDistance:
4350 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004351 case glslang::EbvViewportMaskNV:
4352 case glslang::EbvSecondaryPositionNV:
4353 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004354 case glslang::EbvPositionPerViewNV:
4355 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004356 case glslang::EbvTaskCountNV:
4357 case glslang::EbvPrimitiveCountNV:
4358 case glslang::EbvPrimitiveIndicesNV:
4359 case glslang::EbvClipDistancePerViewNV:
4360 case glslang::EbvCullDistancePerViewNV:
4361 case glslang::EbvLayerPerViewNV:
4362 case glslang::EbvMeshViewCountNV:
4363 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004364#endif
David Netoa901ffe2016-06-08 14:11:40 +01004365 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4366 // Alternately, we could just call this for any glslang built-in, since the
4367 // capability already guards against duplicates.
4368 TranslateBuiltInDecoration(glslangBuiltIn, false);
4369 break;
4370 default:
4371 // Capabilities were already generated when the struct was declared.
4372 break;
4373 }
John Kessenichebb50532016-05-16 19:22:05 -06004374}
4375
John Kessenich6fccb3c2016-09-19 16:01:41 -06004376bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004377{
John Kessenicheee9d532016-09-19 18:09:30 -06004378 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004379}
4380
John Kessenichd41993d2017-09-10 15:21:05 -06004381// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004382// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4383// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004384bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004385{
John Kessenich6a14f782017-12-04 02:48:10 -07004386 assert(qualifier == glslang::EvqIn ||
4387 qualifier == glslang::EvqOut ||
4388 qualifier == glslang::EvqInOut ||
4389 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004390 return qualifier != glslang::EvqConstReadOnly;
4391}
4392
4393// Is parameter pass-by-original?
4394bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4395 bool implicitThisParam)
4396{
4397 if (implicitThisParam) // implicit this
4398 return true;
4399 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004400 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004401 return paramType.containsOpaque() || // sampler, etc.
4402 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4403}
4404
John Kessenich140f3df2015-06-26 16:58:36 -06004405// Make all the functions, skeletally, without actually visiting their bodies.
4406void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4407{
John Kessenich8985fc92020-03-03 10:25:07 -07004408 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4409 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004410 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4411 if (paramPrecision != spv::NoPrecision)
4412 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004413 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004414 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004415 // Original and non-writable params pass the pointer directly and
4416 // use restrict/aliased, others are stored to a pointer in Function
4417 // memory and use RestrictPointer/AliasedPointer.
4418 if (originalParam(type.getQualifier().storage, type, false) ||
4419 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004420 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4421 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004422 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004423 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4424 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004425 }
4426 }
John Kessenichfad62972017-07-18 02:35:46 -06004427 };
4428
John Kessenich140f3df2015-06-26 16:58:36 -06004429 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4430 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004431 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004432 continue;
4433
4434 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004435 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004436 //
qining25262b32016-05-06 17:25:16 -04004437 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004438 // function. What it is an address of varies:
4439 //
John Kessenich4bf71552016-09-02 11:20:21 -06004440 // - "in" parameters not marked as "const" can be written to without modifying the calling
4441 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004442 //
4443 // - "const in" parameters can just be the r-value, as no writes need occur.
4444 //
John Kessenich4bf71552016-09-02 11:20:21 -06004445 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4446 // 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 -06004447
4448 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004449 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004450 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4451
John Kessenich155d3512019-08-08 23:29:20 -06004452#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004453 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4454 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004455#else
4456 bool implicitThis = false;
4457#endif
John Kessenich37789792017-03-21 23:56:40 -06004458
John Kessenichfad62972017-07-18 02:35:46 -06004459 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004460 for (int p = 0; p < (int)parameters.size(); ++p) {
4461 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4462 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004463 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004464 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004465 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004466 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4467 else
John Kessenich4bf71552016-09-02 11:20:21 -06004468 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004469 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004470 paramTypes.push_back(typeId);
4471 }
4472
4473 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004474 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4475 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004476 glslFunction->getName().c_str(), paramTypes,
4477 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004478 if (implicitThis)
4479 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004480
4481 // Track function to emit/call later
4482 functionMap[glslFunction->getName().c_str()] = function;
4483
4484 // Set the parameter id's
4485 for (int p = 0; p < (int)parameters.size(); ++p) {
4486 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4487 // give a name too
4488 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004489
4490 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004491 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004492 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004493 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004494 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004495 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004496 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004497 }
4498 }
4499}
4500
4501// Process all the initializers, while skipping the functions and link objects
4502void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4503{
4504 builder.setBuildPoint(shaderEntry->getLastBlock());
4505 for (int i = 0; i < (int)initializers.size(); ++i) {
4506 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004507 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4508 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004509
4510 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004511 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004512 initializer->traverse(this);
4513 }
4514 }
4515}
4516
4517// Process all the functions, while skipping initializers.
4518void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4519{
4520 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4521 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004522 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004523 node->traverse(this);
4524 }
4525}
4526
4527void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4528{
qining25262b32016-05-06 17:25:16 -04004529 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004530 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004531 currentFunction = functionMap[node->getName().c_str()];
4532 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004533 builder.setBuildPoint(functionBlock);
4534}
4535
John Kessenich8985fc92020-03-03 10:25:07 -07004536void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4537 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004538{
Rex Xufc618912015-09-09 16:42:49 +08004539 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004540
4541 glslang::TSampler sampler = {};
4542 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004543#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004544 bool f16ShadowCompare = false;
4545#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004546 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004547 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4548 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004549#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004550 f16ShadowCompare = sampler.shadow &&
4551 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004552#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004553 }
4554
John Kessenich140f3df2015-06-26 16:58:36 -06004555 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4556 builder.clearAccessChain();
4557 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004558
John Kessenicha28f7a72019-08-06 07:00:58 -06004559#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004560 // Special case l-value operands
4561 bool lvalue = false;
4562 switch (node.getOp()) {
4563 case glslang::EOpImageAtomicAdd:
4564 case glslang::EOpImageAtomicMin:
4565 case glslang::EOpImageAtomicMax:
4566 case glslang::EOpImageAtomicAnd:
4567 case glslang::EOpImageAtomicOr:
4568 case glslang::EOpImageAtomicXor:
4569 case glslang::EOpImageAtomicExchange:
4570 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004571 case glslang::EOpImageAtomicLoad:
4572 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004573 if (i == 0)
4574 lvalue = true;
4575 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004576 case glslang::EOpSparseImageLoad:
4577 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4578 lvalue = true;
4579 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004580 case glslang::EOpSparseTexture:
4581 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4582 lvalue = true;
4583 break;
4584 case glslang::EOpSparseTextureClamp:
4585 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4586 lvalue = true;
4587 break;
4588 case glslang::EOpSparseTextureLod:
4589 case glslang::EOpSparseTextureOffset:
4590 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4591 lvalue = true;
4592 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004593 case glslang::EOpSparseTextureFetch:
4594 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4595 lvalue = true;
4596 break;
4597 case glslang::EOpSparseTextureFetchOffset:
4598 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4599 lvalue = true;
4600 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004601 case glslang::EOpSparseTextureLodOffset:
4602 case glslang::EOpSparseTextureGrad:
4603 case glslang::EOpSparseTextureOffsetClamp:
4604 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4605 lvalue = true;
4606 break;
4607 case glslang::EOpSparseTextureGradOffset:
4608 case glslang::EOpSparseTextureGradClamp:
4609 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4610 lvalue = true;
4611 break;
4612 case glslang::EOpSparseTextureGradOffsetClamp:
4613 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4614 lvalue = true;
4615 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004616 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004617 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4618 lvalue = true;
4619 break;
4620 case glslang::EOpSparseTextureGatherOffset:
4621 case glslang::EOpSparseTextureGatherOffsets:
4622 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4623 lvalue = true;
4624 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004625 case glslang::EOpSparseTextureGatherLod:
4626 if (i == 3)
4627 lvalue = true;
4628 break;
4629 case glslang::EOpSparseTextureGatherLodOffset:
4630 case glslang::EOpSparseTextureGatherLodOffsets:
4631 if (i == 4)
4632 lvalue = true;
4633 break;
Rex Xu129799a2017-07-05 17:23:28 +08004634 case glslang::EOpSparseImageLoadLod:
4635 if (i == 3)
4636 lvalue = true;
4637 break;
Chao Chen3a137962018-09-19 11:41:27 -07004638 case glslang::EOpImageSampleFootprintNV:
4639 if (i == 4)
4640 lvalue = true;
4641 break;
4642 case glslang::EOpImageSampleFootprintClampNV:
4643 case glslang::EOpImageSampleFootprintLodNV:
4644 if (i == 5)
4645 lvalue = true;
4646 break;
4647 case glslang::EOpImageSampleFootprintGradNV:
4648 if (i == 6)
4649 lvalue = true;
4650 break;
4651 case glslang::EOpImageSampleFootprintGradClampNV:
4652 if (i == 7)
4653 lvalue = true;
4654 break;
Rex Xufc618912015-09-09 16:42:49 +08004655 default:
4656 break;
4657 }
4658
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004659 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004660 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004661 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4662 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4663 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004664#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004665 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004666 }
4667}
4668
John Kessenichfc51d282015-08-19 13:34:18 -06004669void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004670{
John Kessenichfc51d282015-08-19 13:34:18 -06004671 builder.clearAccessChain();
4672 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004673 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004674}
John Kessenich140f3df2015-06-26 16:58:36 -06004675
John Kessenichfc51d282015-08-19 13:34:18 -06004676spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4677{
John Kesseniche485c7a2017-05-31 18:50:53 -06004678 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004679 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004680
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004681 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004682
John Kessenichfc51d282015-08-19 13:34:18 -06004683 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004684
John Kessenichf43c7392019-03-31 10:51:57 -06004685 const glslang::TType &imageType = node->getAsAggregate()
4686 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4687 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004688 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004689#ifdef GLSLANG_WEB
4690 const bool f16ShadowCompare = false;
4691#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004692 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004693 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4694 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004695#endif
4696
John Kessenichf43c7392019-03-31 10:51:57 -06004697 const auto signExtensionMask = [&]() {
4698 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4699 if (sampler.type == glslang::EbtUint)
4700 return spv::ImageOperandsZeroExtendMask;
4701 else if (sampler.type == glslang::EbtInt)
4702 return spv::ImageOperandsSignExtendMask;
4703 }
4704 return spv::ImageOperandsMaskNone;
4705 };
4706
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004707 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4708
John Kessenichfc51d282015-08-19 13:34:18 -06004709 std::vector<spv::Id> arguments;
4710 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004711 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004712 else
4713 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004714 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004715
4716 spv::Builder::TextureParameters params = { };
4717 params.sampler = arguments[0];
4718
Rex Xu04db3f52015-09-16 11:44:02 +08004719 glslang::TCrackedTextureOp cracked;
4720 node->crackTexture(sampler, cracked);
4721
amhagan05506bb2017-06-13 16:53:02 -04004722 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004723
John Kessenichfc51d282015-08-19 13:34:18 -06004724 // Check for queries
4725 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004726 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4727 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004728 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004729
John Kessenichfc51d282015-08-19 13:34:18 -06004730 switch (node->getOp()) {
4731 case glslang::EOpImageQuerySize:
4732 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004733 if (arguments.size() > 1) {
4734 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004735 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004736 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004737 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004738#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004739 case glslang::EOpImageQuerySamples:
4740 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004741 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004742 case glslang::EOpTextureQueryLod:
4743 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004744 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004745 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004746 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004747 case glslang::EOpSparseTexelsResident:
4748 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004749#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004750 default:
4751 assert(0);
4752 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004753 }
John Kessenich140f3df2015-06-26 16:58:36 -06004754 }
4755
LoopDawg4425f242018-02-18 11:40:01 -07004756 int components = node->getType().getVectorSize();
4757
4758 if (node->getOp() == glslang::EOpTextureFetch) {
4759 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4760 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4761 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4762 // here around e.g. which ones return scalars or other types.
4763 components = 4;
4764 }
4765
4766 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4767
4768 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4769
Rex Xufc618912015-09-09 16:42:49 +08004770 // Check for image functions other than queries
4771 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004772 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004773 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004774 spv::IdImmediate image = { true, *(opIt++) };
4775 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004776
4777 // Handle subpass operations
4778 // TODO: GLSL should change to have the "MS" only on the type rather than the
4779 // built-in function.
4780 if (cracked.subpass) {
4781 // add on the (0,0) coordinate
4782 spv::Id zero = builder.makeIntConstant(0);
4783 std::vector<spv::Id> comps;
4784 comps.push_back(zero);
4785 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004786 spv::IdImmediate coord = { true,
4787 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4788 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004789 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4790 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004791 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004792 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4793 }
4794 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004795 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004796 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004797 spv::IdImmediate imageOperand = { true, *(opIt++) };
4798 operands.push_back(imageOperand);
4799 }
John Kessenich6c292d32016-02-15 20:58:50 -07004800 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004801 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4802 builder.setPrecision(result, precision);
4803 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004804 }
4805
John Kessenich149afc32018-08-14 13:31:43 -06004806 spv::IdImmediate coord = { true, *(opIt++) };
4807 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004808 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004809 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004810 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004811 mask = mask | spv::ImageOperandsSampleMask;
4812 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004813 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004814 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4815 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004816 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004817 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004818 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4819 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004820 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004821 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004822 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4823 operands.push_back(imageOperands);
4824 }
4825 if (mask & spv::ImageOperandsSampleMask) {
4826 spv::IdImmediate imageOperand = { true, *opIt++ };
4827 operands.push_back(imageOperand);
4828 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004829 if (mask & spv::ImageOperandsLodMask) {
4830 spv::IdImmediate imageOperand = { true, *opIt++ };
4831 operands.push_back(imageOperand);
4832 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004833 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004834 spv::IdImmediate imageOperand = { true,
4835 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004836 operands.push_back(imageOperand);
4837 }
4838
John Kessenich149afc32018-08-14 13:31:43 -06004839 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004840 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004841
John Kessenich149afc32018-08-14 13:31:43 -06004842 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004843 builder.setPrecision(result[0], precision);
4844
4845 // If needed, add a conversion constructor to the proper size.
4846 if (components != node->getType().getVectorSize())
4847 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4848
4849 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004850 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004851
Jeff Bolz36831c92018-09-05 10:11:41 -05004852 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004853 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004854 spv::IdImmediate texel = { true, *(opIt + 1) };
4855 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004856 } else {
4857 spv::IdImmediate texel = { true, *opIt };
4858 operands.push_back(texel);
4859 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004860
4861 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004862 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004863 mask = mask | spv::ImageOperandsSampleMask;
4864 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004865 if (cracked.lod) {
4866 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4867 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4868 mask = mask | spv::ImageOperandsLodMask;
4869 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004870 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4871 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004872 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004873 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004874 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4875 operands.push_back(imageOperands);
4876 }
4877 if (mask & spv::ImageOperandsSampleMask) {
4878 spv::IdImmediate imageOperand = { true, *opIt++ };
4879 operands.push_back(imageOperand);
4880 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004881 if (mask & spv::ImageOperandsLodMask) {
4882 spv::IdImmediate imageOperand = { true, *opIt++ };
4883 operands.push_back(imageOperand);
4884 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004885 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004886 spv::IdImmediate imageOperand = { true,
4887 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004888 operands.push_back(imageOperand);
4889 }
4890
John Kessenich56bab042015-09-16 10:54:31 -06004891 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004892 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004893 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004894 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004895 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4896 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004897 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004898 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004899 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4900
Jeff Bolz36831c92018-09-05 10:11:41 -05004901 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004902 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004903 mask = mask | spv::ImageOperandsSampleMask;
4904 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004905 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004906 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4907 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4908
Jeff Bolz36831c92018-09-05 10:11:41 -05004909 mask = mask | spv::ImageOperandsLodMask;
4910 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004911 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4912 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004913 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004914 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004915 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004916 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004917 }
4918 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004919 spv::IdImmediate imageOperand = { true, *opIt++ };
4920 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004921 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004922 if (mask & spv::ImageOperandsLodMask) {
4923 spv::IdImmediate imageOperand = { true, *opIt++ };
4924 operands.push_back(imageOperand);
4925 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004926 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07004927 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
4928 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004929 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004930 }
4931
4932 // Create the return type that was a special structure
4933 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004934 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004935 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4936 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4937
4938 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4939
4940 // Decode the return type
4941 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4942 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004943 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004944 // Process image atomic operations
4945
4946 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4947 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004948 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004949 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004950 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004951
Jeff Bolz36831c92018-09-05 10:11:41 -05004952 spv::Id resultTypeId;
4953 // imageAtomicStore has a void return type so base the pointer type on
4954 // the type of the value operand.
4955 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08004956 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05004957 } else {
4958 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4959 }
John Kessenich56bab042015-09-16 10:54:31 -06004960 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Jeff Bolz39ffdaf2020-03-09 10:48:12 -05004961 if (imageType.getQualifier().nonUniform) {
4962 builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
4963 }
Rex Xufc618912015-09-09 16:42:49 +08004964
4965 std::vector<spv::Id> operands;
4966 operands.push_back(pointer);
4967 for (; opIt != arguments.end(); ++opIt)
4968 operands.push_back(*opIt);
4969
John Kessenich8985fc92020-03-03 10:25:07 -07004970 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
4971 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004972 }
4973 }
4974
John Kessenicha28f7a72019-08-06 07:00:58 -06004975#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004976 // Check for fragment mask functions other than queries
4977 if (cracked.fragMask) {
4978 assert(sampler.ms);
4979
4980 auto opIt = arguments.begin();
4981 std::vector<spv::Id> operands;
4982
4983 // Extract the image if necessary
4984 if (builder.isSampledImage(params.sampler))
4985 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4986
4987 operands.push_back(params.sampler);
4988 ++opIt;
4989
4990 if (sampler.isSubpass()) {
4991 // add on the (0,0) coordinate
4992 spv::Id zero = builder.makeIntConstant(0);
4993 std::vector<spv::Id> comps;
4994 comps.push_back(zero);
4995 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07004996 operands.push_back(builder.makeCompositeConstant(
4997 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04004998 }
4999
5000 for (; opIt != arguments.end(); ++opIt)
5001 operands.push_back(*opIt);
5002
5003 spv::Op fragMaskOp = spv::OpNop;
5004 if (node->getOp() == glslang::EOpFragmentMaskFetch)
5005 fragMaskOp = spv::OpFragmentMaskFetchAMD;
5006 else if (node->getOp() == glslang::EOpFragmentFetch)
5007 fragMaskOp = spv::OpFragmentFetchAMD;
5008
5009 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
5010 builder.addCapability(spv::CapabilityFragmentMaskAMD);
5011 return builder.createOp(fragMaskOp, resultType(), operands);
5012 }
5013#endif
5014
Rex Xufc618912015-09-09 16:42:49 +08005015 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08005016 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07005017 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005018 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08005019
John Kessenichfc51d282015-08-19 13:34:18 -06005020 // check for bias argument
5021 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08005022 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005023 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08005024 if (cracked.gather)
5025 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08005026
5027 if (f16ShadowCompare)
5028 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005029 if (cracked.offset)
5030 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08005031 else if (cracked.offsets)
5032 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005033 if (cracked.grad)
5034 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08005035 if (cracked.lodClamp)
5036 ++nonBiasArgCount;
5037 if (sparse)
5038 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07005039 if (imageFootprint)
5040 //Following three extra arguments
5041 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5042 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06005043 if ((int)arguments.size() > nonBiasArgCount)
5044 bias = true;
5045 }
5046
John Kessenicha5c33d62016-06-02 23:45:21 -06005047 // See if the sampler param should really be just the SPV image part
5048 if (cracked.fetch) {
5049 // a fetch needs to have the image extracted first
5050 if (builder.isSampledImage(params.sampler))
5051 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
5052 }
5053
John Kessenicha28f7a72019-08-06 07:00:58 -06005054#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08005055 if (cracked.gather) {
5056 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
5057 if (bias || cracked.lod ||
5058 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
5059 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08005060 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08005061 }
5062 }
5063#endif
5064
John Kessenichfc51d282015-08-19 13:34:18 -06005065 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07005066
John Kessenichfc51d282015-08-19 13:34:18 -06005067 params.coords = arguments[1];
5068 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07005069 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07005070
5071 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08005072 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005073 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08005074 ++extraArgs;
5075 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07005076 params.Dref = arguments[2];
5077 ++extraArgs;
5078 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06005079 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06005080 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06005081 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06005082 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06005083 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005084 dRefComp = builder.getNumComponents(params.coords) - 1;
5085 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07005086 params.Dref = builder.createCompositeExtract(params.coords,
5087 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06005088 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005089
5090 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06005091 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005092 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06005093 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06005094 } else if (glslangIntermediate->getStage() != EShLangFragment &&
5095 !(glslangIntermediate->getStage() == EShLangCompute &&
5096 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07005097 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
5098 noImplicitLod = true;
5099 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005100
5101 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005102 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005103 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08005104 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005105 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005106
5107 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06005108 if (cracked.grad) {
5109 params.gradX = arguments[2 + extraArgs];
5110 params.gradY = arguments[3 + extraArgs];
5111 extraArgs += 2;
5112 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005113
5114 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07005115 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06005116 params.offset = arguments[2 + extraArgs];
5117 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005118 } else if (cracked.offsets) {
5119 params.offsets = arguments[2 + extraArgs];
5120 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005121 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005122
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005123#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005124 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005125 if (cracked.lodClamp) {
5126 params.lodClamp = arguments[2 + extraArgs];
5127 ++extraArgs;
5128 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005129 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005130 if (sparse) {
5131 params.texelOut = arguments[2 + extraArgs];
5132 ++extraArgs;
5133 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005134 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005135 if (cracked.gather && ! sampler.shadow) {
5136 // default component is 0, if missing, otherwise an argument
5137 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005138 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005139 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005140 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005141 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005142 }
Chao Chen3a137962018-09-19 11:41:27 -07005143 spv::Id resultStruct = spv::NoResult;
5144 if (imageFootprint) {
5145 //Following three extra arguments
5146 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5147 params.granularity = arguments[2 + extraArgs];
5148 params.coarse = arguments[3 + extraArgs];
5149 resultStruct = arguments[4 + extraArgs];
5150 extraArgs += 3;
5151 }
5152#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005153 // bias
5154 if (bias) {
5155 params.bias = arguments[2 + extraArgs];
5156 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005157 }
John Kessenichfc51d282015-08-19 13:34:18 -06005158
John Kessenicha28f7a72019-08-06 07:00:58 -06005159#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005160 if (imageFootprint) {
5161 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5162 builder.addCapability(spv::CapabilityImageFootprintNV);
5163
5164
5165 //resultStructType(OpenGL type) contains 5 elements:
5166 //struct gl_TextureFootprint2DNV {
5167 // uvec2 anchor;
5168 // uvec2 offset;
5169 // uvec2 mask;
5170 // uint lod;
5171 // uint granularity;
5172 //};
5173 //or
5174 //struct gl_TextureFootprint3DNV {
5175 // uvec3 anchor;
5176 // uvec3 offset;
5177 // uvec2 mask;
5178 // uint lod;
5179 // uint granularity;
5180 //};
5181 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5182 assert(builder.isStructType(resultStructType));
5183
5184 //resType (SPIR-V type) contains 6 elements:
5185 //Member 0 must be a Boolean type scalar(LOD),
5186 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5187 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5188 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5189 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5190 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5191 std::vector<spv::Id> members;
5192 members.push_back(resultType());
5193 for (int i = 0; i < 5; i++) {
5194 members.push_back(builder.getContainedTypeId(resultStructType, i));
5195 }
5196 spv::Id resType = builder.makeStructType(members, "ResType");
5197
5198 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005199 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5200 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005201
5202 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5203 for (int i = 0; i < 5; i++) {
5204 builder.clearAccessChain();
5205 builder.setAccessChainLValue(resultStruct);
5206
5207 //Accessing to a struct we created, no coherent flag is set
5208 spv::Builder::AccessChain::CoherentFlags flags;
5209 flags.clear();
5210
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005211 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005212 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
5213 i+1));
Chao Chen3a137962018-09-19 11:41:27 -07005214 }
5215 return builder.createCompositeExtract(res, resultType(), 0);
5216 }
5217#endif
5218
John Kessenich65336482016-06-16 14:06:26 -06005219 // projective component (might not to move)
5220 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5221 // are divided by the last component of P."
5222 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5223 // unused components will appear after all used components."
5224 if (cracked.proj) {
5225 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5226 int projTargetComp;
5227 switch (sampler.dim) {
5228 case glslang::Esd1D: projTargetComp = 1; break;
5229 case glslang::Esd2D: projTargetComp = 2; break;
5230 case glslang::EsdRect: projTargetComp = 2; break;
5231 default: projTargetComp = projSourceComp; break;
5232 }
5233 // copy the projective coordinate if we have to
5234 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005235 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005236 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005237 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005238 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005239 }
5240 }
5241
John Kessenichf8d1d742019-10-21 06:55:11 -06005242#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005243 // nonprivate
5244 if (imageType.getQualifier().nonprivate) {
5245 params.nonprivate = true;
5246 }
5247
5248 // volatile
5249 if (imageType.getQualifier().volatil) {
5250 params.volatil = true;
5251 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005252#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005253
St0fFa1184dd2018-04-09 21:08:14 +02005254 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005255 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5256 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005257 );
LoopDawg4425f242018-02-18 11:40:01 -07005258
5259 if (components != node->getType().getVectorSize())
5260 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5261
5262 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005263}
5264
5265spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5266{
5267 // Grab the function's pointer from the previously created function
5268 spv::Function* function = functionMap[node->getName().c_str()];
5269 if (! function)
5270 return 0;
5271
5272 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5273 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5274
5275 // See comments in makeFunctions() for details about the semantics for parameter passing.
5276 //
5277 // These imply we need a four step process:
5278 // 1. Evaluate the arguments
5279 // 2. Allocate and make copies of in, out, and inout arguments
5280 // 3. Make the call
5281 // 4. Copy back the results
5282
John Kessenichd3ed90b2018-05-04 11:43:03 -06005283 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005284 std::vector<spv::Builder::AccessChain> lValues;
5285 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005286 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005287 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005288 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005289 // build l-value
5290 builder.clearAccessChain();
5291 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005292 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005293 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005294 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005295 // save l-value
5296 lValues.push_back(builder.getAccessChain());
5297 } else {
5298 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005299 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005300 }
5301 }
5302
5303 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5304 // copy the original into that space.
5305 //
5306 // Also, build up the list of actual arguments to pass in for the call
5307 int lValueCount = 0;
5308 int rValueCount = 0;
5309 std::vector<spv::Id> spvArgs;
5310 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5311 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005312 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005313 builder.setAccessChain(lValues[lValueCount]);
5314 arg = builder.accessChainGetLValue();
5315 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005316 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005317 // need space to hold the copy
John Kessenich8985fc92020-03-03 10:25:07 -07005318 arg = builder.createVariable(spv::StorageClassFunction,
5319 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005320 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5321 // need to copy the input into output space
5322 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005323 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005324 builder.clearAccessChain();
5325 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005326 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005327 }
5328 ++lValueCount;
5329 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005330 // process r-value, which involves a copy for a type mismatch
5331 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5332 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5333 builder.clearAccessChain();
5334 builder.setAccessChainLValue(argCopy);
5335 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5336 arg = builder.createLoad(argCopy);
5337 } else
5338 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005339 ++rValueCount;
5340 }
5341 spvArgs.push_back(arg);
5342 }
5343
5344 // 3. Make the call.
5345 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005346 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005347
5348 // 4. Copy back out an "out" arguments.
5349 lValueCount = 0;
5350 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005351 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005352 ++lValueCount;
5353 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005354 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5355 spv::Id copy = builder.createLoad(spvArgs[a]);
5356 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005357 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005358 }
5359 ++lValueCount;
5360 }
5361 }
5362
5363 return result;
5364}
5365
5366// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005367spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005368 spv::Id typeId, spv::Id left, spv::Id right,
5369 glslang::TBasicType typeProxy, bool reduceComparison)
5370{
John Kessenich66011cb2018-03-06 16:12:04 -07005371 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5372 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005373 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005374
5375 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005376 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005377 bool comparison = false;
5378
5379 switch (op) {
5380 case glslang::EOpAdd:
5381 case glslang::EOpAddAssign:
5382 if (isFloat)
5383 binOp = spv::OpFAdd;
5384 else
5385 binOp = spv::OpIAdd;
5386 break;
5387 case glslang::EOpSub:
5388 case glslang::EOpSubAssign:
5389 if (isFloat)
5390 binOp = spv::OpFSub;
5391 else
5392 binOp = spv::OpISub;
5393 break;
5394 case glslang::EOpMul:
5395 case glslang::EOpMulAssign:
5396 if (isFloat)
5397 binOp = spv::OpFMul;
5398 else
5399 binOp = spv::OpIMul;
5400 break;
5401 case glslang::EOpVectorTimesScalar:
5402 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005403 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005404 if (builder.isVector(right))
5405 std::swap(left, right);
5406 assert(builder.isScalar(right));
5407 needMatchingVectors = false;
5408 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005409 } else if (isFloat)
5410 binOp = spv::OpFMul;
5411 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005412 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005413 break;
5414 case glslang::EOpVectorTimesMatrix:
5415 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005416 binOp = spv::OpVectorTimesMatrix;
5417 break;
5418 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005419 binOp = spv::OpMatrixTimesVector;
5420 break;
5421 case glslang::EOpMatrixTimesScalar:
5422 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005423 binOp = spv::OpMatrixTimesScalar;
5424 break;
5425 case glslang::EOpMatrixTimesMatrix:
5426 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005427 binOp = spv::OpMatrixTimesMatrix;
5428 break;
5429 case glslang::EOpOuterProduct:
5430 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005431 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005432 break;
5433
5434 case glslang::EOpDiv:
5435 case glslang::EOpDivAssign:
5436 if (isFloat)
5437 binOp = spv::OpFDiv;
5438 else if (isUnsigned)
5439 binOp = spv::OpUDiv;
5440 else
5441 binOp = spv::OpSDiv;
5442 break;
5443 case glslang::EOpMod:
5444 case glslang::EOpModAssign:
5445 if (isFloat)
5446 binOp = spv::OpFMod;
5447 else if (isUnsigned)
5448 binOp = spv::OpUMod;
5449 else
5450 binOp = spv::OpSMod;
5451 break;
5452 case glslang::EOpRightShift:
5453 case glslang::EOpRightShiftAssign:
5454 if (isUnsigned)
5455 binOp = spv::OpShiftRightLogical;
5456 else
5457 binOp = spv::OpShiftRightArithmetic;
5458 break;
5459 case glslang::EOpLeftShift:
5460 case glslang::EOpLeftShiftAssign:
5461 binOp = spv::OpShiftLeftLogical;
5462 break;
5463 case glslang::EOpAnd:
5464 case glslang::EOpAndAssign:
5465 binOp = spv::OpBitwiseAnd;
5466 break;
5467 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005468 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005469 binOp = spv::OpLogicalAnd;
5470 break;
5471 case glslang::EOpInclusiveOr:
5472 case glslang::EOpInclusiveOrAssign:
5473 binOp = spv::OpBitwiseOr;
5474 break;
5475 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005476 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005477 binOp = spv::OpLogicalOr;
5478 break;
5479 case glslang::EOpExclusiveOr:
5480 case glslang::EOpExclusiveOrAssign:
5481 binOp = spv::OpBitwiseXor;
5482 break;
5483 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005484 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005485 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005486 break;
5487
Ian Romanickb3bd4022019-01-21 08:57:25 -08005488 case glslang::EOpAbsDifference:
5489 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5490 break;
5491
5492 case glslang::EOpAddSaturate:
5493 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5494 break;
5495
5496 case glslang::EOpSubSaturate:
5497 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5498 break;
5499
5500 case glslang::EOpAverage:
5501 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5502 break;
5503
5504 case glslang::EOpAverageRounded:
5505 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5506 break;
5507
5508 case glslang::EOpMul32x16:
5509 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5510 break;
5511
John Kessenich140f3df2015-06-26 16:58:36 -06005512 case glslang::EOpLessThan:
5513 case glslang::EOpGreaterThan:
5514 case glslang::EOpLessThanEqual:
5515 case glslang::EOpGreaterThanEqual:
5516 case glslang::EOpEqual:
5517 case glslang::EOpNotEqual:
5518 case glslang::EOpVectorEqual:
5519 case glslang::EOpVectorNotEqual:
5520 comparison = true;
5521 break;
5522 default:
5523 break;
5524 }
5525
John Kessenich7c1aa102015-10-15 13:29:11 -06005526 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005527 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005528 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005529 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5530 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005531 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005532
5533 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005534 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005535 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005536
qining25262b32016-05-06 17:25:16 -04005537 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005538 decorations.addNoContraction(builder, result);
5539 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005540 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005541 }
5542
5543 if (! comparison)
5544 return 0;
5545
John Kessenich7c1aa102015-10-15 13:29:11 -06005546 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005547
John Kessenich4583b612016-08-07 19:14:22 -06005548 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005549 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5550 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005551 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005552 return result;
5553 }
John Kessenich140f3df2015-06-26 16:58:36 -06005554
5555 switch (op) {
5556 case glslang::EOpLessThan:
5557 if (isFloat)
5558 binOp = spv::OpFOrdLessThan;
5559 else if (isUnsigned)
5560 binOp = spv::OpULessThan;
5561 else
5562 binOp = spv::OpSLessThan;
5563 break;
5564 case glslang::EOpGreaterThan:
5565 if (isFloat)
5566 binOp = spv::OpFOrdGreaterThan;
5567 else if (isUnsigned)
5568 binOp = spv::OpUGreaterThan;
5569 else
5570 binOp = spv::OpSGreaterThan;
5571 break;
5572 case glslang::EOpLessThanEqual:
5573 if (isFloat)
5574 binOp = spv::OpFOrdLessThanEqual;
5575 else if (isUnsigned)
5576 binOp = spv::OpULessThanEqual;
5577 else
5578 binOp = spv::OpSLessThanEqual;
5579 break;
5580 case glslang::EOpGreaterThanEqual:
5581 if (isFloat)
5582 binOp = spv::OpFOrdGreaterThanEqual;
5583 else if (isUnsigned)
5584 binOp = spv::OpUGreaterThanEqual;
5585 else
5586 binOp = spv::OpSGreaterThanEqual;
5587 break;
5588 case glslang::EOpEqual:
5589 case glslang::EOpVectorEqual:
5590 if (isFloat)
5591 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005592 else if (isBool)
5593 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005594 else
5595 binOp = spv::OpIEqual;
5596 break;
5597 case glslang::EOpNotEqual:
5598 case glslang::EOpVectorNotEqual:
5599 if (isFloat)
5600 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005601 else if (isBool)
5602 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005603 else
5604 binOp = spv::OpINotEqual;
5605 break;
5606 default:
5607 break;
5608 }
5609
qining25262b32016-05-06 17:25:16 -04005610 if (binOp != spv::OpNop) {
5611 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005612 decorations.addNoContraction(builder, result);
5613 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005614 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005615 }
John Kessenich140f3df2015-06-26 16:58:36 -06005616
5617 return 0;
5618}
5619
John Kessenich04bb8a02015-12-12 12:28:14 -07005620//
5621// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5622// These can be any of:
5623//
5624// matrix * scalar
5625// scalar * matrix
5626// matrix * matrix linear algebraic
5627// matrix * vector
5628// vector * matrix
5629// matrix * matrix componentwise
5630// matrix op matrix op in {+, -, /}
5631// matrix op scalar op in {+, -, /}
5632// scalar op matrix op in {+, -, /}
5633//
John Kessenichead86222018-03-28 18:01:20 -06005634spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5635 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005636{
5637 bool firstClass = true;
5638
5639 // First, handle first-class matrix operations (* and matrix/scalar)
5640 switch (op) {
5641 case spv::OpFDiv:
5642 if (builder.isMatrix(left) && builder.isScalar(right)) {
5643 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005644 spv::Id resultType = builder.getTypeId(right);
5645 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005646 op = spv::OpMatrixTimesScalar;
5647 } else
5648 firstClass = false;
5649 break;
5650 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005651 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005652 std::swap(left, right);
5653 assert(builder.isScalar(right));
5654 break;
5655 case spv::OpVectorTimesMatrix:
5656 assert(builder.isVector(left));
5657 assert(builder.isMatrix(right));
5658 break;
5659 case spv::OpMatrixTimesVector:
5660 assert(builder.isMatrix(left));
5661 assert(builder.isVector(right));
5662 break;
5663 case spv::OpMatrixTimesMatrix:
5664 assert(builder.isMatrix(left));
5665 assert(builder.isMatrix(right));
5666 break;
5667 default:
5668 firstClass = false;
5669 break;
5670 }
5671
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005672 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5673 firstClass = true;
5674
qining25262b32016-05-06 17:25:16 -04005675 if (firstClass) {
5676 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005677 decorations.addNoContraction(builder, result);
5678 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005679 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005680 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005681
LoopDawg592860c2016-06-09 08:57:35 -06005682 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005683 // The result type of all of them is the same type as the (a) matrix operand.
5684 // The algorithm is to:
5685 // - break the matrix(es) into vectors
5686 // - smear any scalar to a vector
5687 // - do vector operations
5688 // - make a matrix out the vector results
5689 switch (op) {
5690 case spv::OpFAdd:
5691 case spv::OpFSub:
5692 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005693 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005694 case spv::OpFMul:
5695 {
5696 // one time set up...
5697 bool leftMat = builder.isMatrix(left);
5698 bool rightMat = builder.isMatrix(right);
5699 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5700 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5701 spv::Id scalarType = builder.getScalarTypeId(typeId);
5702 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5703 std::vector<spv::Id> results;
5704 spv::Id smearVec = spv::NoResult;
5705 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005706 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005707 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005708 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005709
5710 // do each vector op
5711 for (unsigned int c = 0; c < numCols; ++c) {
5712 std::vector<unsigned int> indexes;
5713 indexes.push_back(c);
5714 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5715 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005716 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005717 decorations.addNoContraction(builder, result);
5718 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005719 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005720 }
5721
5722 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005723 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005724 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005725 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005726 }
5727 default:
5728 assert(0);
5729 return spv::NoResult;
5730 }
5731}
5732
John Kessenichead86222018-03-28 18:01:20 -06005733spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005734 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005735{
5736 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005737 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005738 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005739 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5740 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005741
5742 switch (op) {
5743 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005744 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005745 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005746 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005747 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005748 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005749 unaryOp = spv::OpSNegate;
5750 break;
5751
5752 case glslang::EOpLogicalNot:
5753 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005754 unaryOp = spv::OpLogicalNot;
5755 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005756 case glslang::EOpBitwiseNot:
5757 unaryOp = spv::OpNot;
5758 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005759
John Kessenich140f3df2015-06-26 16:58:36 -06005760 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005761 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005762 break;
5763 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005764 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005765 break;
5766 case glslang::EOpTranspose:
5767 unaryOp = spv::OpTranspose;
5768 break;
5769
5770 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005771 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005772 break;
5773 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005774 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005775 break;
5776 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005777 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005778 break;
5779 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005780 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005781 break;
5782 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005783 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005784 break;
5785 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005786 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005787 break;
5788 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005789 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005790 break;
5791 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005792 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005793 break;
5794
5795 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005796 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005797 break;
5798 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005799 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005800 break;
5801 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005802 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005803 break;
5804 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005805 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005806 break;
5807 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005808 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005809 break;
5810 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005811 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005812 break;
5813
5814 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005815 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005816 break;
5817 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005818 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005819 break;
5820
5821 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005822 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005823 break;
5824 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005825 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005826 break;
5827 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005828 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005829 break;
5830 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005831 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005832 break;
5833 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005834 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005835 break;
5836 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005837 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005838 break;
5839
5840 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005841 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005842 break;
5843 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005844 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005845 break;
5846 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005847 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005848 break;
5849 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005850 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005851 break;
5852 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005853 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005854 break;
5855 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005856 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005857 break;
5858
5859 case glslang::EOpIsNan:
5860 unaryOp = spv::OpIsNan;
5861 break;
5862 case glslang::EOpIsInf:
5863 unaryOp = spv::OpIsInf;
5864 break;
LoopDawg592860c2016-06-09 08:57:35 -06005865 case glslang::EOpIsFinite:
5866 unaryOp = spv::OpIsFinite;
5867 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005868
Rex Xucbc426e2015-12-15 16:03:10 +08005869 case glslang::EOpFloatBitsToInt:
5870 case glslang::EOpFloatBitsToUint:
5871 case glslang::EOpIntBitsToFloat:
5872 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005873 case glslang::EOpDoubleBitsToInt64:
5874 case glslang::EOpDoubleBitsToUint64:
5875 case glslang::EOpInt64BitsToDouble:
5876 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005877 case glslang::EOpFloat16BitsToInt16:
5878 case glslang::EOpFloat16BitsToUint16:
5879 case glslang::EOpInt16BitsToFloat16:
5880 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005881 unaryOp = spv::OpBitcast;
5882 break;
5883
John Kessenich140f3df2015-06-26 16:58:36 -06005884 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005885 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005886 break;
5887 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005888 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005889 break;
5890 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005891 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005892 break;
5893 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005894 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005895 break;
5896 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005897 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005898 break;
5899 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005900 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005901 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005902#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005903 case glslang::EOpPackSnorm4x8:
5904 libCall = spv::GLSLstd450PackSnorm4x8;
5905 break;
5906 case glslang::EOpUnpackSnorm4x8:
5907 libCall = spv::GLSLstd450UnpackSnorm4x8;
5908 break;
5909 case glslang::EOpPackUnorm4x8:
5910 libCall = spv::GLSLstd450PackUnorm4x8;
5911 break;
5912 case glslang::EOpUnpackUnorm4x8:
5913 libCall = spv::GLSLstd450UnpackUnorm4x8;
5914 break;
5915 case glslang::EOpPackDouble2x32:
5916 libCall = spv::GLSLstd450PackDouble2x32;
5917 break;
5918 case glslang::EOpUnpackDouble2x32:
5919 libCall = spv::GLSLstd450UnpackDouble2x32;
5920 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005921#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005922
Rex Xu8ff43de2016-04-22 16:51:45 +08005923 case glslang::EOpPackInt2x32:
5924 case glslang::EOpUnpackInt2x32:
5925 case glslang::EOpPackUint2x32:
5926 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005927 case glslang::EOpPack16:
5928 case glslang::EOpPack32:
5929 case glslang::EOpPack64:
5930 case glslang::EOpUnpack32:
5931 case glslang::EOpUnpack16:
5932 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005933 case glslang::EOpPackInt2x16:
5934 case glslang::EOpUnpackInt2x16:
5935 case glslang::EOpPackUint2x16:
5936 case glslang::EOpUnpackUint2x16:
5937 case glslang::EOpPackInt4x16:
5938 case glslang::EOpUnpackInt4x16:
5939 case glslang::EOpPackUint4x16:
5940 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005941 case glslang::EOpPackFloat2x16:
5942 case glslang::EOpUnpackFloat2x16:
5943 unaryOp = spv::OpBitcast;
5944 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005945
John Kessenich140f3df2015-06-26 16:58:36 -06005946 case glslang::EOpDPdx:
5947 unaryOp = spv::OpDPdx;
5948 break;
5949 case glslang::EOpDPdy:
5950 unaryOp = spv::OpDPdy;
5951 break;
5952 case glslang::EOpFwidth:
5953 unaryOp = spv::OpFwidth;
5954 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005955
John Kessenich140f3df2015-06-26 16:58:36 -06005956 case glslang::EOpAny:
5957 unaryOp = spv::OpAny;
5958 break;
5959 case glslang::EOpAll:
5960 unaryOp = spv::OpAll;
5961 break;
5962
5963 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005964 if (isFloat)
5965 libCall = spv::GLSLstd450FAbs;
5966 else
5967 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005968 break;
5969 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005970 if (isFloat)
5971 libCall = spv::GLSLstd450FSign;
5972 else
5973 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005974 break;
5975
John Kessenicha28f7a72019-08-06 07:00:58 -06005976#ifndef GLSLANG_WEB
5977 case glslang::EOpDPdxFine:
5978 unaryOp = spv::OpDPdxFine;
5979 break;
5980 case glslang::EOpDPdyFine:
5981 unaryOp = spv::OpDPdyFine;
5982 break;
5983 case glslang::EOpFwidthFine:
5984 unaryOp = spv::OpFwidthFine;
5985 break;
5986 case glslang::EOpDPdxCoarse:
5987 unaryOp = spv::OpDPdxCoarse;
5988 break;
5989 case glslang::EOpDPdyCoarse:
5990 unaryOp = spv::OpDPdyCoarse;
5991 break;
5992 case glslang::EOpFwidthCoarse:
5993 unaryOp = spv::OpFwidthCoarse;
5994 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04005995 case glslang::EOpRayQueryProceed:
5996 unaryOp = spv::OpRayQueryProceedKHR;
5997 break;
5998 case glslang::EOpRayQueryGetRayTMin:
5999 unaryOp = spv::OpRayQueryGetRayTMinKHR;
6000 break;
6001 case glslang::EOpRayQueryGetRayFlags:
6002 unaryOp = spv::OpRayQueryGetRayFlagsKHR;
6003 break;
6004 case glslang::EOpRayQueryGetWorldRayOrigin:
6005 unaryOp = spv::OpRayQueryGetWorldRayOriginKHR;
6006 break;
6007 case glslang::EOpRayQueryGetWorldRayDirection:
6008 unaryOp = spv::OpRayQueryGetWorldRayDirectionKHR;
6009 break;
6010 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
6011 unaryOp = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
6012 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006013 case glslang::EOpInterpolateAtCentroid:
6014 if (typeProxy == glslang::EbtFloat16)
6015 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6016 libCall = spv::GLSLstd450InterpolateAtCentroid;
6017 break;
John Kessenichfc51d282015-08-19 13:34:18 -06006018 case glslang::EOpAtomicCounterIncrement:
6019 case glslang::EOpAtomicCounterDecrement:
6020 case glslang::EOpAtomicCounter:
6021 {
6022 // Handle all of the atomics in one place, in createAtomicOperation()
6023 std::vector<spv::Id> operands;
6024 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006025 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06006026 }
6027
John Kessenichfc51d282015-08-19 13:34:18 -06006028 case glslang::EOpBitFieldReverse:
6029 unaryOp = spv::OpBitReverse;
6030 break;
6031 case glslang::EOpBitCount:
6032 unaryOp = spv::OpBitCount;
6033 break;
6034 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006035 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006036 break;
6037 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006038 if (isUnsigned)
6039 libCall = spv::GLSLstd450FindUMsb;
6040 else
6041 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006042 break;
6043
Ian Romanickb3bd4022019-01-21 08:57:25 -08006044 case glslang::EOpCountLeadingZeros:
6045 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6046 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6047 unaryOp = spv::OpUCountLeadingZerosINTEL;
6048 break;
6049
6050 case glslang::EOpCountTrailingZeros:
6051 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6052 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6053 unaryOp = spv::OpUCountTrailingZerosINTEL;
6054 break;
6055
Rex Xu574ab042016-04-14 16:53:07 +08006056 case glslang::EOpBallot:
6057 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006058 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006059 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08006060 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08006061 case glslang::EOpMinInvocations:
6062 case glslang::EOpMaxInvocations:
6063 case glslang::EOpAddInvocations:
6064 case glslang::EOpMinInvocationsNonUniform:
6065 case glslang::EOpMaxInvocationsNonUniform:
6066 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006067 case glslang::EOpMinInvocationsInclusiveScan:
6068 case glslang::EOpMaxInvocationsInclusiveScan:
6069 case glslang::EOpAddInvocationsInclusiveScan:
6070 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6071 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6072 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6073 case glslang::EOpMinInvocationsExclusiveScan:
6074 case glslang::EOpMaxInvocationsExclusiveScan:
6075 case glslang::EOpAddInvocationsExclusiveScan:
6076 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6077 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6078 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08006079 {
6080 std::vector<spv::Id> operands;
6081 operands.push_back(operand);
6082 return createInvocationsOperation(op, typeId, operands, typeProxy);
6083 }
John Kessenich66011cb2018-03-06 16:12:04 -07006084 case glslang::EOpSubgroupAll:
6085 case glslang::EOpSubgroupAny:
6086 case glslang::EOpSubgroupAllEqual:
6087 case glslang::EOpSubgroupBroadcastFirst:
6088 case glslang::EOpSubgroupBallot:
6089 case glslang::EOpSubgroupInverseBallot:
6090 case glslang::EOpSubgroupBallotBitCount:
6091 case glslang::EOpSubgroupBallotInclusiveBitCount:
6092 case glslang::EOpSubgroupBallotExclusiveBitCount:
6093 case glslang::EOpSubgroupBallotFindLSB:
6094 case glslang::EOpSubgroupBallotFindMSB:
6095 case glslang::EOpSubgroupAdd:
6096 case glslang::EOpSubgroupMul:
6097 case glslang::EOpSubgroupMin:
6098 case glslang::EOpSubgroupMax:
6099 case glslang::EOpSubgroupAnd:
6100 case glslang::EOpSubgroupOr:
6101 case glslang::EOpSubgroupXor:
6102 case glslang::EOpSubgroupInclusiveAdd:
6103 case glslang::EOpSubgroupInclusiveMul:
6104 case glslang::EOpSubgroupInclusiveMin:
6105 case glslang::EOpSubgroupInclusiveMax:
6106 case glslang::EOpSubgroupInclusiveAnd:
6107 case glslang::EOpSubgroupInclusiveOr:
6108 case glslang::EOpSubgroupInclusiveXor:
6109 case glslang::EOpSubgroupExclusiveAdd:
6110 case glslang::EOpSubgroupExclusiveMul:
6111 case glslang::EOpSubgroupExclusiveMin:
6112 case glslang::EOpSubgroupExclusiveMax:
6113 case glslang::EOpSubgroupExclusiveAnd:
6114 case glslang::EOpSubgroupExclusiveOr:
6115 case glslang::EOpSubgroupExclusiveXor:
6116 case glslang::EOpSubgroupQuadSwapHorizontal:
6117 case glslang::EOpSubgroupQuadSwapVertical:
6118 case glslang::EOpSubgroupQuadSwapDiagonal: {
6119 std::vector<spv::Id> operands;
6120 operands.push_back(operand);
6121 return createSubgroupOperation(op, typeId, operands, typeProxy);
6122 }
Rex Xu9d93a232016-05-05 12:30:44 +08006123 case glslang::EOpMbcnt:
6124 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6125 libCall = spv::MbcntAMD;
6126 break;
6127
6128 case glslang::EOpCubeFaceIndex:
6129 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6130 libCall = spv::CubeFaceIndexAMD;
6131 break;
6132
6133 case glslang::EOpCubeFaceCoord:
6134 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6135 libCall = spv::CubeFaceCoordAMD;
6136 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006137 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006138 unaryOp = spv::OpGroupNonUniformPartitionNV;
6139 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006140 case glslang::EOpConstructReference:
6141 unaryOp = spv::OpBitcast;
6142 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006143#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006144
6145 case glslang::EOpCopyObject:
6146 unaryOp = spv::OpCopyObject;
6147 break;
6148
John Kessenich140f3df2015-06-26 16:58:36 -06006149 default:
6150 return 0;
6151 }
6152
6153 spv::Id id;
6154 if (libCall >= 0) {
6155 std::vector<spv::Id> args;
6156 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006157 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006158 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006159 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006160 }
John Kessenich140f3df2015-06-26 16:58:36 -06006161
John Kessenichb9197c82019-08-11 07:41:45 -06006162 decorations.addNoContraction(builder, id);
6163 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006164 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006165}
6166
John Kessenich7a53f762016-01-20 11:19:27 -07006167// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006168spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6169 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006170{
6171 // Handle unary operations vector by vector.
6172 // The result type is the same type as the original type.
6173 // The algorithm is to:
6174 // - break the matrix into vectors
6175 // - apply the operation to each vector
6176 // - make a matrix out the vector results
6177
6178 // get the types sorted out
6179 int numCols = builder.getNumColumns(operand);
6180 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006181 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6182 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006183 std::vector<spv::Id> results;
6184
6185 // do each vector op
6186 for (int c = 0; c < numCols; ++c) {
6187 std::vector<unsigned int> indexes;
6188 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006189 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6190 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006191 decorations.addNoContraction(builder, destVec);
6192 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006193 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006194 }
6195
6196 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006197 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006198 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006199 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006200}
6201
John Kessenichad7645f2018-06-04 19:11:25 -06006202// For converting integers where both the bitwidth and the signedness could
6203// change, but only do the width change here. The caller is still responsible
6204// for the signedness conversion.
6205spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006206{
John Kessenichad7645f2018-06-04 19:11:25 -06006207 // Get the result type width, based on the type to convert to.
6208 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006209 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006210 case glslang::EOpConvInt16ToUint8:
6211 case glslang::EOpConvIntToUint8:
6212 case glslang::EOpConvInt64ToUint8:
6213 case glslang::EOpConvUint16ToInt8:
6214 case glslang::EOpConvUintToInt8:
6215 case glslang::EOpConvUint64ToInt8:
6216 width = 8;
6217 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006218 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006219 case glslang::EOpConvIntToUint16:
6220 case glslang::EOpConvInt64ToUint16:
6221 case glslang::EOpConvUint8ToInt16:
6222 case glslang::EOpConvUintToInt16:
6223 case glslang::EOpConvUint64ToInt16:
6224 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006225 break;
6226 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006227 case glslang::EOpConvInt16ToUint:
6228 case glslang::EOpConvInt64ToUint:
6229 case glslang::EOpConvUint8ToInt:
6230 case glslang::EOpConvUint16ToInt:
6231 case glslang::EOpConvUint64ToInt:
6232 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006233 break;
6234 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006235 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006236 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006237 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006238 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006239 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006240 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006241 break;
6242
6243 default:
6244 assert(false && "Default missing");
6245 break;
6246 }
6247
John Kessenichad7645f2018-06-04 19:11:25 -06006248 // Get the conversion operation and result type,
6249 // based on the target width, but the source type.
6250 spv::Id type = spv::NoType;
6251 spv::Op convOp = spv::OpNop;
6252 switch(op) {
6253 case glslang::EOpConvInt8ToUint16:
6254 case glslang::EOpConvInt8ToUint:
6255 case glslang::EOpConvInt8ToUint64:
6256 case glslang::EOpConvInt16ToUint8:
6257 case glslang::EOpConvInt16ToUint:
6258 case glslang::EOpConvInt16ToUint64:
6259 case glslang::EOpConvIntToUint8:
6260 case glslang::EOpConvIntToUint16:
6261 case glslang::EOpConvIntToUint64:
6262 case glslang::EOpConvInt64ToUint8:
6263 case glslang::EOpConvInt64ToUint16:
6264 case glslang::EOpConvInt64ToUint:
6265 convOp = spv::OpSConvert;
6266 type = builder.makeIntType(width);
6267 break;
6268 default:
6269 convOp = spv::OpUConvert;
6270 type = builder.makeUintType(width);
6271 break;
6272 }
6273
John Kessenich66011cb2018-03-06 16:12:04 -07006274 if (vectorSize > 0)
6275 type = builder.makeVectorType(type, vectorSize);
6276
John Kessenichad7645f2018-06-04 19:11:25 -06006277 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006278}
6279
John Kessenichead86222018-03-28 18:01:20 -06006280spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6281 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006282{
6283 spv::Op convOp = spv::OpNop;
6284 spv::Id zero = 0;
6285 spv::Id one = 0;
6286
6287 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6288
6289 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006290 case glslang::EOpConvIntToBool:
6291 case glslang::EOpConvUintToBool:
6292 zero = builder.makeUintConstant(0);
6293 zero = makeSmearedConstant(zero, vectorSize);
6294 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006295 case glslang::EOpConvFloatToBool:
6296 zero = builder.makeFloatConstant(0.0F);
6297 zero = makeSmearedConstant(zero, vectorSize);
6298 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006299 case glslang::EOpConvBoolToFloat:
6300 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006301 zero = builder.makeFloatConstant(0.0F);
6302 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006303 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006304
John Kessenich140f3df2015-06-26 16:58:36 -06006305 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006306 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006307#ifndef GLSLANG_WEB
6308 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006309 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006310 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006311 } else
6312#endif
6313 {
6314 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006315 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006316 }
Rex Xucabbb782017-03-24 13:41:14 +08006317
John Kessenich140f3df2015-06-26 16:58:36 -06006318 convOp = spv::OpSelect;
6319 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006320
John Kessenich140f3df2015-06-26 16:58:36 -06006321 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006322 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006323#ifndef GLSLANG_WEB
6324 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006325 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006326 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006327 } else
6328#endif
6329 {
6330 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006331 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006332 }
Rex Xucabbb782017-03-24 13:41:14 +08006333
John Kessenich140f3df2015-06-26 16:58:36 -06006334 convOp = spv::OpSelect;
6335 break;
6336
John Kessenich66011cb2018-03-06 16:12:04 -07006337 case glslang::EOpConvInt8ToFloat16:
6338 case glslang::EOpConvInt8ToFloat:
6339 case glslang::EOpConvInt8ToDouble:
6340 case glslang::EOpConvInt16ToFloat16:
6341 case glslang::EOpConvInt16ToFloat:
6342 case glslang::EOpConvInt16ToDouble:
6343 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006344 case glslang::EOpConvIntToFloat:
6345 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006346 case glslang::EOpConvInt64ToFloat:
6347 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006348 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006349 convOp = spv::OpConvertSToF;
6350 break;
6351
John Kessenich66011cb2018-03-06 16:12:04 -07006352 case glslang::EOpConvUint8ToFloat16:
6353 case glslang::EOpConvUint8ToFloat:
6354 case glslang::EOpConvUint8ToDouble:
6355 case glslang::EOpConvUint16ToFloat16:
6356 case glslang::EOpConvUint16ToFloat:
6357 case glslang::EOpConvUint16ToDouble:
6358 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006359 case glslang::EOpConvUintToFloat:
6360 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006361 case glslang::EOpConvUint64ToFloat:
6362 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006363 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006364 convOp = spv::OpConvertUToF;
6365 break;
6366
John Kessenich66011cb2018-03-06 16:12:04 -07006367 case glslang::EOpConvFloat16ToInt8:
6368 case glslang::EOpConvFloatToInt8:
6369 case glslang::EOpConvDoubleToInt8:
6370 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006371 case glslang::EOpConvFloatToInt16:
6372 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006373 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006374 case glslang::EOpConvFloatToInt:
6375 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006376 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006377 case glslang::EOpConvFloatToInt64:
6378 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006379 convOp = spv::OpConvertFToS;
6380 break;
6381
John Kessenich66011cb2018-03-06 16:12:04 -07006382 case glslang::EOpConvUint8ToInt8:
6383 case glslang::EOpConvInt8ToUint8:
6384 case glslang::EOpConvUint16ToInt16:
6385 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006386 case glslang::EOpConvUintToInt:
6387 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006388 case glslang::EOpConvUint64ToInt64:
6389 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006390 if (builder.isInSpecConstCodeGenMode()) {
6391 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006392#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006393 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6394 zero = builder.makeUint8Constant(0);
6395 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006396 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006397 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6398 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006399 } else
6400#endif
6401 {
Rex Xucabbb782017-03-24 13:41:14 +08006402 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006403 }
qining189b2032016-04-12 23:16:20 -04006404 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006405 // Use OpIAdd, instead of OpBitcast to do the conversion when
6406 // generating for OpSpecConstantOp instruction.
6407 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6408 }
6409 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006410 convOp = spv::OpBitcast;
6411 break;
6412
John Kessenich66011cb2018-03-06 16:12:04 -07006413 case glslang::EOpConvFloat16ToUint8:
6414 case glslang::EOpConvFloatToUint8:
6415 case glslang::EOpConvDoubleToUint8:
6416 case glslang::EOpConvFloat16ToUint16:
6417 case glslang::EOpConvFloatToUint16:
6418 case glslang::EOpConvDoubleToUint16:
6419 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006420 case glslang::EOpConvFloatToUint:
6421 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006422 case glslang::EOpConvFloatToUint64:
6423 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006424 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006425 convOp = spv::OpConvertFToU;
6426 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006427
John Kessenich39697cd2019-08-08 10:35:51 -06006428#ifndef GLSLANG_WEB
6429 case glslang::EOpConvInt8ToBool:
6430 case glslang::EOpConvUint8ToBool:
6431 zero = builder.makeUint8Constant(0);
6432 zero = makeSmearedConstant(zero, vectorSize);
6433 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6434 case glslang::EOpConvInt16ToBool:
6435 case glslang::EOpConvUint16ToBool:
6436 zero = builder.makeUint16Constant(0);
6437 zero = makeSmearedConstant(zero, vectorSize);
6438 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6439 case glslang::EOpConvInt64ToBool:
6440 case glslang::EOpConvUint64ToBool:
6441 zero = builder.makeUint64Constant(0);
6442 zero = makeSmearedConstant(zero, vectorSize);
6443 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6444 case glslang::EOpConvDoubleToBool:
6445 zero = builder.makeDoubleConstant(0.0);
6446 zero = makeSmearedConstant(zero, vectorSize);
6447 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6448 case glslang::EOpConvFloat16ToBool:
6449 zero = builder.makeFloat16Constant(0.0F);
6450 zero = makeSmearedConstant(zero, vectorSize);
6451 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6452 case glslang::EOpConvBoolToDouble:
6453 convOp = spv::OpSelect;
6454 zero = builder.makeDoubleConstant(0.0);
6455 one = builder.makeDoubleConstant(1.0);
6456 break;
6457 case glslang::EOpConvBoolToFloat16:
6458 convOp = spv::OpSelect;
6459 zero = builder.makeFloat16Constant(0.0F);
6460 one = builder.makeFloat16Constant(1.0F);
6461 break;
6462 case glslang::EOpConvBoolToInt8:
6463 zero = builder.makeInt8Constant(0);
6464 one = builder.makeInt8Constant(1);
6465 convOp = spv::OpSelect;
6466 break;
6467 case glslang::EOpConvBoolToUint8:
6468 zero = builder.makeUint8Constant(0);
6469 one = builder.makeUint8Constant(1);
6470 convOp = spv::OpSelect;
6471 break;
6472 case glslang::EOpConvBoolToInt16:
6473 zero = builder.makeInt16Constant(0);
6474 one = builder.makeInt16Constant(1);
6475 convOp = spv::OpSelect;
6476 break;
6477 case glslang::EOpConvBoolToUint16:
6478 zero = builder.makeUint16Constant(0);
6479 one = builder.makeUint16Constant(1);
6480 convOp = spv::OpSelect;
6481 break;
6482 case glslang::EOpConvDoubleToFloat:
6483 case glslang::EOpConvFloatToDouble:
6484 case glslang::EOpConvDoubleToFloat16:
6485 case glslang::EOpConvFloat16ToDouble:
6486 case glslang::EOpConvFloatToFloat16:
6487 case glslang::EOpConvFloat16ToFloat:
6488 convOp = spv::OpFConvert;
6489 if (builder.isMatrixType(destType))
6490 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6491 break;
6492
John Kessenich66011cb2018-03-06 16:12:04 -07006493 case glslang::EOpConvInt8ToInt16:
6494 case glslang::EOpConvInt8ToInt:
6495 case glslang::EOpConvInt8ToInt64:
6496 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006497 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006498 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006499 case glslang::EOpConvIntToInt8:
6500 case glslang::EOpConvIntToInt16:
6501 case glslang::EOpConvIntToInt64:
6502 case glslang::EOpConvInt64ToInt8:
6503 case glslang::EOpConvInt64ToInt16:
6504 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006505 convOp = spv::OpSConvert;
6506 break;
6507
John Kessenich66011cb2018-03-06 16:12:04 -07006508 case glslang::EOpConvUint8ToUint16:
6509 case glslang::EOpConvUint8ToUint:
6510 case glslang::EOpConvUint8ToUint64:
6511 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006512 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006513 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006514 case glslang::EOpConvUintToUint8:
6515 case glslang::EOpConvUintToUint16:
6516 case glslang::EOpConvUintToUint64:
6517 case glslang::EOpConvUint64ToUint8:
6518 case glslang::EOpConvUint64ToUint16:
6519 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006520 convOp = spv::OpUConvert;
6521 break;
6522
John Kessenich66011cb2018-03-06 16:12:04 -07006523 case glslang::EOpConvInt8ToUint16:
6524 case glslang::EOpConvInt8ToUint:
6525 case glslang::EOpConvInt8ToUint64:
6526 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006527 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006528 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006529 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006530 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006531 case glslang::EOpConvIntToUint64:
6532 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006533 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006534 case glslang::EOpConvInt64ToUint:
6535 case glslang::EOpConvUint8ToInt16:
6536 case glslang::EOpConvUint8ToInt:
6537 case glslang::EOpConvUint8ToInt64:
6538 case glslang::EOpConvUint16ToInt8:
6539 case glslang::EOpConvUint16ToInt:
6540 case glslang::EOpConvUint16ToInt64:
6541 case glslang::EOpConvUintToInt8:
6542 case glslang::EOpConvUintToInt16:
6543 case glslang::EOpConvUintToInt64:
6544 case glslang::EOpConvUint64ToInt8:
6545 case glslang::EOpConvUint64ToInt16:
6546 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006547 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006548 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006549
6550 if (builder.isInSpecConstCodeGenMode()) {
6551 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006552 switch(op) {
6553 case glslang::EOpConvInt16ToUint8:
6554 case glslang::EOpConvIntToUint8:
6555 case glslang::EOpConvInt64ToUint8:
6556 case glslang::EOpConvUint16ToInt8:
6557 case glslang::EOpConvUintToInt8:
6558 case glslang::EOpConvUint64ToInt8:
6559 zero = builder.makeUint8Constant(0);
6560 break;
6561 case glslang::EOpConvInt8ToUint16:
6562 case glslang::EOpConvIntToUint16:
6563 case glslang::EOpConvInt64ToUint16:
6564 case glslang::EOpConvUint8ToInt16:
6565 case glslang::EOpConvUintToInt16:
6566 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006567 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006568 break;
6569 case glslang::EOpConvInt8ToUint:
6570 case glslang::EOpConvInt16ToUint:
6571 case glslang::EOpConvInt64ToUint:
6572 case glslang::EOpConvUint8ToInt:
6573 case glslang::EOpConvUint16ToInt:
6574 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006575 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006576 break;
6577 case glslang::EOpConvInt8ToUint64:
6578 case glslang::EOpConvInt16ToUint64:
6579 case glslang::EOpConvIntToUint64:
6580 case glslang::EOpConvUint8ToInt64:
6581 case glslang::EOpConvUint16ToInt64:
6582 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006583 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006584 break;
6585 default:
6586 assert(false && "Default missing");
6587 break;
6588 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006589 zero = makeSmearedConstant(zero, vectorSize);
6590 // Use OpIAdd, instead of OpBitcast to do the conversion when
6591 // generating for OpSpecConstantOp instruction.
6592 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6593 }
6594 // For normal run-time conversion instruction, use OpBitcast.
6595 convOp = spv::OpBitcast;
6596 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006597 case glslang::EOpConvUint64ToPtr:
6598 convOp = spv::OpConvertUToPtr;
6599 break;
6600 case glslang::EOpConvPtrToUint64:
6601 convOp = spv::OpConvertPtrToU;
6602 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006603 case glslang::EOpConvPtrToUvec2:
6604 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006605 if (builder.isVector(operand))
6606 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6607 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006608 convOp = spv::OpBitcast;
6609 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006610#endif
6611
John Kessenich140f3df2015-06-26 16:58:36 -06006612 default:
6613 break;
6614 }
6615
6616 spv::Id result = 0;
6617 if (convOp == spv::OpNop)
6618 return result;
6619
6620 if (convOp == spv::OpSelect) {
6621 zero = makeSmearedConstant(zero, vectorSize);
6622 one = makeSmearedConstant(one, vectorSize);
6623 result = builder.createTriOp(convOp, destType, operand, one, zero);
6624 } else
6625 result = builder.createUnaryOp(convOp, destType, operand);
6626
John Kessenichead86222018-03-28 18:01:20 -06006627 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006628 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006629 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006630}
6631
6632spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6633{
6634 if (vectorSize == 0)
6635 return constant;
6636
6637 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6638 std::vector<spv::Id> components;
6639 for (int c = 0; c < vectorSize; ++c)
6640 components.push_back(constant);
6641 return builder.makeCompositeConstant(vectorTypeId, components);
6642}
6643
John Kessenich426394d2015-07-23 10:22:48 -06006644// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006645spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6646 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6647 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006648{
6649 spv::Op opCode = spv::OpNop;
6650
6651 switch (op) {
6652 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006653 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006654 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006655 opCode = spv::OpAtomicIAdd;
6656 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006657 case glslang::EOpAtomicCounterSubtract:
6658 opCode = spv::OpAtomicISub;
6659 break;
John Kessenich426394d2015-07-23 10:22:48 -06006660 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006661 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006662 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006663 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6664 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006665 break;
6666 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006667 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006668 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006669 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6670 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006671 break;
6672 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006673 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006674 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006675 opCode = spv::OpAtomicAnd;
6676 break;
6677 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006678 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006679 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006680 opCode = spv::OpAtomicOr;
6681 break;
6682 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006683 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006684 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006685 opCode = spv::OpAtomicXor;
6686 break;
6687 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006688 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006689 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006690 opCode = spv::OpAtomicExchange;
6691 break;
6692 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006693 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006694 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006695 opCode = spv::OpAtomicCompareExchange;
6696 break;
6697 case glslang::EOpAtomicCounterIncrement:
6698 opCode = spv::OpAtomicIIncrement;
6699 break;
6700 case glslang::EOpAtomicCounterDecrement:
6701 opCode = spv::OpAtomicIDecrement;
6702 break;
6703 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006704 case glslang::EOpImageAtomicLoad:
6705 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006706 opCode = spv::OpAtomicLoad;
6707 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006708 case glslang::EOpAtomicStore:
6709 case glslang::EOpImageAtomicStore:
6710 opCode = spv::OpAtomicStore;
6711 break;
John Kessenich426394d2015-07-23 10:22:48 -06006712 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006713 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006714 break;
6715 }
6716
Rex Xue8fe8b02017-09-26 15:42:56 +08006717 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6718 builder.addCapability(spv::CapabilityInt64Atomics);
6719
John Kessenich426394d2015-07-23 10:22:48 -06006720 // Sort out the operands
6721 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006722 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006723 // - compare-exchange swaps the value and comparator
6724 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006725 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006726 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6727 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6728 spv::Id scopeId;
6729 if (glslangIntermediate->usingVulkanMemoryModel()) {
6730 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6731 } else {
6732 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6733 }
6734 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006735 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6736 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006737 spv::MemorySemanticsVolatileMask :
6738 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006739 spv::Id semanticsId2 = semanticsId;
6740
6741 pointerId = operands[0];
6742 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6743 // no additional operands
6744 } else if (opCode == spv::OpAtomicCompareExchange) {
6745 compareId = operands[1];
6746 valueId = operands[2];
6747 if (operands.size() > 3) {
6748 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006749 semanticsId = builder.makeUintConstant(
6750 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6751 semanticsId2 = builder.makeUintConstant(
6752 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006753 }
6754 } else if (opCode == spv::OpAtomicLoad) {
6755 if (operands.size() > 1) {
6756 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006757 semanticsId = builder.makeUintConstant(
6758 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006759 }
6760 } else {
6761 // atomic store or RMW
6762 valueId = operands[1];
6763 if (operands.size() > 2) {
6764 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006765 semanticsId = builder.makeUintConstant
6766 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006767 }
Rex Xu04db3f52015-09-16 11:44:02 +08006768 }
John Kessenich426394d2015-07-23 10:22:48 -06006769
Jeff Bolz36831c92018-09-05 10:11:41 -05006770 // Check for capabilities
6771 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006772 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6773 spv::MemorySemanticsMakeVisibleKHRMask |
6774 spv::MemorySemanticsOutputMemoryKHRMask |
6775 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006776 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6777 }
John Kessenich426394d2015-07-23 10:22:48 -06006778
Jeff Bolz36831c92018-09-05 10:11:41 -05006779 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6780 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6781 }
John Kessenich48d6e792017-10-06 21:21:48 -06006782
Jeff Bolz36831c92018-09-05 10:11:41 -05006783 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6784 spvAtomicOperands.push_back(pointerId);
6785 spvAtomicOperands.push_back(scopeId);
6786 spvAtomicOperands.push_back(semanticsId);
6787 if (opCode == spv::OpAtomicCompareExchange) {
6788 spvAtomicOperands.push_back(semanticsId2);
6789 spvAtomicOperands.push_back(valueId);
6790 spvAtomicOperands.push_back(compareId);
6791 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6792 spvAtomicOperands.push_back(valueId);
6793 }
John Kessenich48d6e792017-10-06 21:21:48 -06006794
Jeff Bolz36831c92018-09-05 10:11:41 -05006795 if (opCode == spv::OpAtomicStore) {
6796 builder.createNoResultOp(opCode, spvAtomicOperands);
6797 return 0;
6798 } else {
6799 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6800
6801 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6802 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6803 if (op == glslang::EOpAtomicCounterDecrement)
6804 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6805
6806 return resultId;
6807 }
John Kessenich426394d2015-07-23 10:22:48 -06006808}
6809
John Kessenich91cef522016-05-05 16:45:40 -06006810// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07006811spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
6812 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006813{
John Kessenich66011cb2018-03-06 16:12:04 -07006814 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6815 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006816
Rex Xu51596642016-09-21 18:56:12 +08006817 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006818 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006819 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6820
chaocf200da82016-12-20 12:44:35 -08006821 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6822 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006823 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6824 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006825 } else if (op == glslang::EOpAnyInvocation ||
6826 op == glslang::EOpAllInvocations ||
6827 op == glslang::EOpAllInvocationsEqual) {
6828 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6829 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006830 } else {
6831 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006832 if (op == glslang::EOpMinInvocationsNonUniform ||
6833 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006834 op == glslang::EOpAddInvocationsNonUniform ||
6835 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6836 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6837 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6838 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6839 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6840 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006841 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006842
Rex Xu430ef402016-10-14 17:22:23 +08006843 switch (op) {
6844 case glslang::EOpMinInvocations:
6845 case glslang::EOpMaxInvocations:
6846 case glslang::EOpAddInvocations:
6847 case glslang::EOpMinInvocationsNonUniform:
6848 case glslang::EOpMaxInvocationsNonUniform:
6849 case glslang::EOpAddInvocationsNonUniform:
6850 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006851 break;
6852 case glslang::EOpMinInvocationsInclusiveScan:
6853 case glslang::EOpMaxInvocationsInclusiveScan:
6854 case glslang::EOpAddInvocationsInclusiveScan:
6855 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6856 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6857 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6858 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006859 break;
6860 case glslang::EOpMinInvocationsExclusiveScan:
6861 case glslang::EOpMaxInvocationsExclusiveScan:
6862 case glslang::EOpAddInvocationsExclusiveScan:
6863 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6864 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6865 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6866 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006867 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006868 default:
6869 break;
Rex Xu430ef402016-10-14 17:22:23 +08006870 }
John Kessenich149afc32018-08-14 13:31:43 -06006871 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6872 spvGroupOperands.push_back(scope);
6873 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006874 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006875 spvGroupOperands.push_back(groupOp);
6876 }
Rex Xu51596642016-09-21 18:56:12 +08006877 }
6878
John Kessenich149afc32018-08-14 13:31:43 -06006879 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6880 spv::IdImmediate op = { true, *opIt };
6881 spvGroupOperands.push_back(op);
6882 }
John Kessenich91cef522016-05-05 16:45:40 -06006883
6884 switch (op) {
6885 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006886 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006887 break;
John Kessenich91cef522016-05-05 16:45:40 -06006888 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006889 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006890 break;
John Kessenich91cef522016-05-05 16:45:40 -06006891 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006892 opCode = spv::OpSubgroupAllEqualKHR;
6893 break;
Rex Xu51596642016-09-21 18:56:12 +08006894 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006895 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006896 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006897 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006898 break;
6899 case glslang::EOpReadFirstInvocation:
6900 opCode = spv::OpSubgroupFirstInvocationKHR;
6901 break;
6902 case glslang::EOpBallot:
6903 {
6904 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6905 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6906 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6907 //
6908 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6909 //
6910 spv::Id uintType = builder.makeUintType(32);
6911 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6912 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6913
6914 std::vector<spv::Id> components;
6915 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6916 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6917
6918 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6919 return builder.createUnaryOp(spv::OpBitcast, typeId,
6920 builder.createCompositeConstruct(uvec2Type, components));
6921 }
6922
Rex Xu9d93a232016-05-05 12:30:44 +08006923 case glslang::EOpMinInvocations:
6924 case glslang::EOpMaxInvocations:
6925 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006926 case glslang::EOpMinInvocationsInclusiveScan:
6927 case glslang::EOpMaxInvocationsInclusiveScan:
6928 case glslang::EOpAddInvocationsInclusiveScan:
6929 case glslang::EOpMinInvocationsExclusiveScan:
6930 case glslang::EOpMaxInvocationsExclusiveScan:
6931 case glslang::EOpAddInvocationsExclusiveScan:
6932 if (op == glslang::EOpMinInvocations ||
6933 op == glslang::EOpMinInvocationsInclusiveScan ||
6934 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006935 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006936 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006937 else {
6938 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006939 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006940 else
Rex Xu51596642016-09-21 18:56:12 +08006941 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006942 }
Rex Xu430ef402016-10-14 17:22:23 +08006943 } else if (op == glslang::EOpMaxInvocations ||
6944 op == glslang::EOpMaxInvocationsInclusiveScan ||
6945 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006946 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006947 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006948 else {
6949 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006950 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006951 else
Rex Xu51596642016-09-21 18:56:12 +08006952 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006953 }
6954 } else {
6955 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006956 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006957 else
Rex Xu51596642016-09-21 18:56:12 +08006958 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006959 }
6960
Rex Xu2bbbe062016-08-23 15:41:05 +08006961 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006962 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006963
6964 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006965 case glslang::EOpMinInvocationsNonUniform:
6966 case glslang::EOpMaxInvocationsNonUniform:
6967 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006968 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6969 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6970 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6971 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6972 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6973 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6974 if (op == glslang::EOpMinInvocationsNonUniform ||
6975 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6976 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006977 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006978 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006979 else {
6980 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006981 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006982 else
Rex Xu51596642016-09-21 18:56:12 +08006983 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006984 }
6985 }
Rex Xu430ef402016-10-14 17:22:23 +08006986 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6987 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6988 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006989 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006990 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006991 else {
6992 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006993 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006994 else
Rex Xu51596642016-09-21 18:56:12 +08006995 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006996 }
6997 }
6998 else {
6999 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007000 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007001 else
Rex Xu51596642016-09-21 18:56:12 +08007002 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007003 }
7004
Rex Xu2bbbe062016-08-23 15:41:05 +08007005 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007006 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007007
7008 break;
John Kessenich91cef522016-05-05 16:45:40 -06007009 default:
7010 logger->missingFunctionality("invocation operation");
7011 return spv::NoResult;
7012 }
Rex Xu51596642016-09-21 18:56:12 +08007013
7014 assert(opCode != spv::OpNop);
7015 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06007016}
7017
Rex Xu2bbbe062016-08-23 15:41:05 +08007018// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06007019spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
7020 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08007021{
7022 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
7023 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08007024 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08007025 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07007026 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
7027 op == spv::OpGroupSMinNonUniformAMD ||
7028 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
7029 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08007030 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
7031
7032 // Handle group invocation operations scalar by scalar.
7033 // The result type is the same type as the original type.
7034 // The algorithm is to:
7035 // - break the vector into scalars
7036 // - apply the operation to each scalar
7037 // - make a vector out the scalar results
7038
7039 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08007040 int numComponents = builder.getNumComponents(operands[0]);
7041 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08007042 std::vector<spv::Id> results;
7043
7044 // do each scalar op
7045 for (int comp = 0; comp < numComponents; ++comp) {
7046 std::vector<unsigned int> indexes;
7047 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06007048 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
7049 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08007050 if (op == spv::OpSubgroupReadInvocationKHR) {
7051 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007052 spv::IdImmediate operand = { true, operands[1] };
7053 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08007054 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06007055 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7056 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08007057 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007058 spv::IdImmediate operand = { true, operands[1] };
7059 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08007060 } else {
John Kessenich149afc32018-08-14 13:31:43 -06007061 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7062 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06007063 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007064 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08007065 spvGroupOperands.push_back(scalar);
7066 }
Rex Xu2bbbe062016-08-23 15:41:05 +08007067
Rex Xub7072052016-09-26 15:53:40 +08007068 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08007069 }
7070
7071 // put the pieces together
7072 return builder.createCompositeConstruct(typeId, results);
7073}
Rex Xu2bbbe062016-08-23 15:41:05 +08007074
John Kessenich66011cb2018-03-06 16:12:04 -07007075// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06007076spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
7077 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07007078{
7079 // Add the required capabilities.
7080 switch (op) {
7081 case glslang::EOpSubgroupElect:
7082 builder.addCapability(spv::CapabilityGroupNonUniform);
7083 break;
7084 case glslang::EOpSubgroupAll:
7085 case glslang::EOpSubgroupAny:
7086 case glslang::EOpSubgroupAllEqual:
7087 builder.addCapability(spv::CapabilityGroupNonUniform);
7088 builder.addCapability(spv::CapabilityGroupNonUniformVote);
7089 break;
7090 case glslang::EOpSubgroupBroadcast:
7091 case glslang::EOpSubgroupBroadcastFirst:
7092 case glslang::EOpSubgroupBallot:
7093 case glslang::EOpSubgroupInverseBallot:
7094 case glslang::EOpSubgroupBallotBitExtract:
7095 case glslang::EOpSubgroupBallotBitCount:
7096 case glslang::EOpSubgroupBallotInclusiveBitCount:
7097 case glslang::EOpSubgroupBallotExclusiveBitCount:
7098 case glslang::EOpSubgroupBallotFindLSB:
7099 case glslang::EOpSubgroupBallotFindMSB:
7100 builder.addCapability(spv::CapabilityGroupNonUniform);
7101 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
7102 break;
7103 case glslang::EOpSubgroupShuffle:
7104 case glslang::EOpSubgroupShuffleXor:
7105 builder.addCapability(spv::CapabilityGroupNonUniform);
7106 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
7107 break;
7108 case glslang::EOpSubgroupShuffleUp:
7109 case glslang::EOpSubgroupShuffleDown:
7110 builder.addCapability(spv::CapabilityGroupNonUniform);
7111 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
7112 break;
7113 case glslang::EOpSubgroupAdd:
7114 case glslang::EOpSubgroupMul:
7115 case glslang::EOpSubgroupMin:
7116 case glslang::EOpSubgroupMax:
7117 case glslang::EOpSubgroupAnd:
7118 case glslang::EOpSubgroupOr:
7119 case glslang::EOpSubgroupXor:
7120 case glslang::EOpSubgroupInclusiveAdd:
7121 case glslang::EOpSubgroupInclusiveMul:
7122 case glslang::EOpSubgroupInclusiveMin:
7123 case glslang::EOpSubgroupInclusiveMax:
7124 case glslang::EOpSubgroupInclusiveAnd:
7125 case glslang::EOpSubgroupInclusiveOr:
7126 case glslang::EOpSubgroupInclusiveXor:
7127 case glslang::EOpSubgroupExclusiveAdd:
7128 case glslang::EOpSubgroupExclusiveMul:
7129 case glslang::EOpSubgroupExclusiveMin:
7130 case glslang::EOpSubgroupExclusiveMax:
7131 case glslang::EOpSubgroupExclusiveAnd:
7132 case glslang::EOpSubgroupExclusiveOr:
7133 case glslang::EOpSubgroupExclusiveXor:
7134 builder.addCapability(spv::CapabilityGroupNonUniform);
7135 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
7136 break;
7137 case glslang::EOpSubgroupClusteredAdd:
7138 case glslang::EOpSubgroupClusteredMul:
7139 case glslang::EOpSubgroupClusteredMin:
7140 case glslang::EOpSubgroupClusteredMax:
7141 case glslang::EOpSubgroupClusteredAnd:
7142 case glslang::EOpSubgroupClusteredOr:
7143 case glslang::EOpSubgroupClusteredXor:
7144 builder.addCapability(spv::CapabilityGroupNonUniform);
7145 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7146 break;
7147 case glslang::EOpSubgroupQuadBroadcast:
7148 case glslang::EOpSubgroupQuadSwapHorizontal:
7149 case glslang::EOpSubgroupQuadSwapVertical:
7150 case glslang::EOpSubgroupQuadSwapDiagonal:
7151 builder.addCapability(spv::CapabilityGroupNonUniform);
7152 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7153 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007154 case glslang::EOpSubgroupPartitionedAdd:
7155 case glslang::EOpSubgroupPartitionedMul:
7156 case glslang::EOpSubgroupPartitionedMin:
7157 case glslang::EOpSubgroupPartitionedMax:
7158 case glslang::EOpSubgroupPartitionedAnd:
7159 case glslang::EOpSubgroupPartitionedOr:
7160 case glslang::EOpSubgroupPartitionedXor:
7161 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7162 case glslang::EOpSubgroupPartitionedInclusiveMul:
7163 case glslang::EOpSubgroupPartitionedInclusiveMin:
7164 case glslang::EOpSubgroupPartitionedInclusiveMax:
7165 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7166 case glslang::EOpSubgroupPartitionedInclusiveOr:
7167 case glslang::EOpSubgroupPartitionedInclusiveXor:
7168 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7169 case glslang::EOpSubgroupPartitionedExclusiveMul:
7170 case glslang::EOpSubgroupPartitionedExclusiveMin:
7171 case glslang::EOpSubgroupPartitionedExclusiveMax:
7172 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7173 case glslang::EOpSubgroupPartitionedExclusiveOr:
7174 case glslang::EOpSubgroupPartitionedExclusiveXor:
7175 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7176 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7177 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007178 default: assert(0 && "Unhandled subgroup operation!");
7179 }
7180
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007181
7182 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7183 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007184 const bool isBool = typeProxy == glslang::EbtBool;
7185
7186 spv::Op opCode = spv::OpNop;
7187
7188 // Figure out which opcode to use.
7189 switch (op) {
7190 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7191 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7192 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7193 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7194 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7195 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7196 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7197 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7198 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7199 case glslang::EOpSubgroupBallotBitCount:
7200 case glslang::EOpSubgroupBallotInclusiveBitCount:
7201 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7202 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7203 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7204 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7205 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7206 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7207 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7208 case glslang::EOpSubgroupAdd:
7209 case glslang::EOpSubgroupInclusiveAdd:
7210 case glslang::EOpSubgroupExclusiveAdd:
7211 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007212 case glslang::EOpSubgroupPartitionedAdd:
7213 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7214 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007215 if (isFloat) {
7216 opCode = spv::OpGroupNonUniformFAdd;
7217 } else {
7218 opCode = spv::OpGroupNonUniformIAdd;
7219 }
7220 break;
7221 case glslang::EOpSubgroupMul:
7222 case glslang::EOpSubgroupInclusiveMul:
7223 case glslang::EOpSubgroupExclusiveMul:
7224 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007225 case glslang::EOpSubgroupPartitionedMul:
7226 case glslang::EOpSubgroupPartitionedInclusiveMul:
7227 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007228 if (isFloat) {
7229 opCode = spv::OpGroupNonUniformFMul;
7230 } else {
7231 opCode = spv::OpGroupNonUniformIMul;
7232 }
7233 break;
7234 case glslang::EOpSubgroupMin:
7235 case glslang::EOpSubgroupInclusiveMin:
7236 case glslang::EOpSubgroupExclusiveMin:
7237 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007238 case glslang::EOpSubgroupPartitionedMin:
7239 case glslang::EOpSubgroupPartitionedInclusiveMin:
7240 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007241 if (isFloat) {
7242 opCode = spv::OpGroupNonUniformFMin;
7243 } else if (isUnsigned) {
7244 opCode = spv::OpGroupNonUniformUMin;
7245 } else {
7246 opCode = spv::OpGroupNonUniformSMin;
7247 }
7248 break;
7249 case glslang::EOpSubgroupMax:
7250 case glslang::EOpSubgroupInclusiveMax:
7251 case glslang::EOpSubgroupExclusiveMax:
7252 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007253 case glslang::EOpSubgroupPartitionedMax:
7254 case glslang::EOpSubgroupPartitionedInclusiveMax:
7255 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007256 if (isFloat) {
7257 opCode = spv::OpGroupNonUniformFMax;
7258 } else if (isUnsigned) {
7259 opCode = spv::OpGroupNonUniformUMax;
7260 } else {
7261 opCode = spv::OpGroupNonUniformSMax;
7262 }
7263 break;
7264 case glslang::EOpSubgroupAnd:
7265 case glslang::EOpSubgroupInclusiveAnd:
7266 case glslang::EOpSubgroupExclusiveAnd:
7267 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007268 case glslang::EOpSubgroupPartitionedAnd:
7269 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7270 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007271 if (isBool) {
7272 opCode = spv::OpGroupNonUniformLogicalAnd;
7273 } else {
7274 opCode = spv::OpGroupNonUniformBitwiseAnd;
7275 }
7276 break;
7277 case glslang::EOpSubgroupOr:
7278 case glslang::EOpSubgroupInclusiveOr:
7279 case glslang::EOpSubgroupExclusiveOr:
7280 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007281 case glslang::EOpSubgroupPartitionedOr:
7282 case glslang::EOpSubgroupPartitionedInclusiveOr:
7283 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007284 if (isBool) {
7285 opCode = spv::OpGroupNonUniformLogicalOr;
7286 } else {
7287 opCode = spv::OpGroupNonUniformBitwiseOr;
7288 }
7289 break;
7290 case glslang::EOpSubgroupXor:
7291 case glslang::EOpSubgroupInclusiveXor:
7292 case glslang::EOpSubgroupExclusiveXor:
7293 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007294 case glslang::EOpSubgroupPartitionedXor:
7295 case glslang::EOpSubgroupPartitionedInclusiveXor:
7296 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007297 if (isBool) {
7298 opCode = spv::OpGroupNonUniformLogicalXor;
7299 } else {
7300 opCode = spv::OpGroupNonUniformBitwiseXor;
7301 }
7302 break;
7303 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7304 case glslang::EOpSubgroupQuadSwapHorizontal:
7305 case glslang::EOpSubgroupQuadSwapVertical:
7306 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7307 default: assert(0 && "Unhandled subgroup operation!");
7308 }
7309
John Kessenich149afc32018-08-14 13:31:43 -06007310 // get the right Group Operation
7311 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007312 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007313 default:
7314 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007315 case glslang::EOpSubgroupBallotBitCount:
7316 case glslang::EOpSubgroupAdd:
7317 case glslang::EOpSubgroupMul:
7318 case glslang::EOpSubgroupMin:
7319 case glslang::EOpSubgroupMax:
7320 case glslang::EOpSubgroupAnd:
7321 case glslang::EOpSubgroupOr:
7322 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007323 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007324 break;
7325 case glslang::EOpSubgroupBallotInclusiveBitCount:
7326 case glslang::EOpSubgroupInclusiveAdd:
7327 case glslang::EOpSubgroupInclusiveMul:
7328 case glslang::EOpSubgroupInclusiveMin:
7329 case glslang::EOpSubgroupInclusiveMax:
7330 case glslang::EOpSubgroupInclusiveAnd:
7331 case glslang::EOpSubgroupInclusiveOr:
7332 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007333 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007334 break;
7335 case glslang::EOpSubgroupBallotExclusiveBitCount:
7336 case glslang::EOpSubgroupExclusiveAdd:
7337 case glslang::EOpSubgroupExclusiveMul:
7338 case glslang::EOpSubgroupExclusiveMin:
7339 case glslang::EOpSubgroupExclusiveMax:
7340 case glslang::EOpSubgroupExclusiveAnd:
7341 case glslang::EOpSubgroupExclusiveOr:
7342 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007343 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007344 break;
7345 case glslang::EOpSubgroupClusteredAdd:
7346 case glslang::EOpSubgroupClusteredMul:
7347 case glslang::EOpSubgroupClusteredMin:
7348 case glslang::EOpSubgroupClusteredMax:
7349 case glslang::EOpSubgroupClusteredAnd:
7350 case glslang::EOpSubgroupClusteredOr:
7351 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007352 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007353 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007354 case glslang::EOpSubgroupPartitionedAdd:
7355 case glslang::EOpSubgroupPartitionedMul:
7356 case glslang::EOpSubgroupPartitionedMin:
7357 case glslang::EOpSubgroupPartitionedMax:
7358 case glslang::EOpSubgroupPartitionedAnd:
7359 case glslang::EOpSubgroupPartitionedOr:
7360 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007361 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007362 break;
7363 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7364 case glslang::EOpSubgroupPartitionedInclusiveMul:
7365 case glslang::EOpSubgroupPartitionedInclusiveMin:
7366 case glslang::EOpSubgroupPartitionedInclusiveMax:
7367 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7368 case glslang::EOpSubgroupPartitionedInclusiveOr:
7369 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007370 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007371 break;
7372 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7373 case glslang::EOpSubgroupPartitionedExclusiveMul:
7374 case glslang::EOpSubgroupPartitionedExclusiveMin:
7375 case glslang::EOpSubgroupPartitionedExclusiveMax:
7376 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7377 case glslang::EOpSubgroupPartitionedExclusiveOr:
7378 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007379 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007380 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007381 }
7382
John Kessenich149afc32018-08-14 13:31:43 -06007383 // build the instruction
7384 std::vector<spv::IdImmediate> spvGroupOperands;
7385
7386 // Every operation begins with the Execution Scope operand.
7387 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7388 spvGroupOperands.push_back(executionScope);
7389
7390 // Next, for all operations that use a Group Operation, push that as an operand.
7391 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007392 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007393 spvGroupOperands.push_back(groupOperand);
7394 }
7395
John Kessenich66011cb2018-03-06 16:12:04 -07007396 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007397 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7398 spv::IdImmediate operand = { true, *opIt };
7399 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007400 }
7401
7402 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007403 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007404 switch (op) {
7405 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007406 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7407 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7408 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7409 }
7410 if (directionId != spv::NoResult) {
7411 spv::IdImmediate direction = { true, directionId };
7412 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007413 }
7414
7415 return builder.createOp(opCode, typeId, spvGroupOperands);
7416}
7417
John Kessenich8985fc92020-03-03 10:25:07 -07007418spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7419 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007420{
John Kessenich66011cb2018-03-06 16:12:04 -07007421 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7422 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007423
John Kessenich140f3df2015-06-26 16:58:36 -06007424 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007425 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007426 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007427 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007428 spv::Id typeId0 = 0;
7429 if (consumedOperands > 0)
7430 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007431 spv::Id typeId1 = 0;
7432 if (consumedOperands > 1)
7433 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007434 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007435
7436 switch (op) {
7437 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007438 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007439 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007440 else if (isUnsigned)
7441 libCall = spv::GLSLstd450UMin;
7442 else
7443 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007444 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007445 break;
7446 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007447 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007448 break;
7449 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007450 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007451 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007452 else if (isUnsigned)
7453 libCall = spv::GLSLstd450UMax;
7454 else
7455 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007456 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007457 break;
7458 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007459 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007460 break;
7461 case glslang::EOpDot:
7462 opCode = spv::OpDot;
7463 break;
7464 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007465 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007466 break;
7467
7468 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007469 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007470 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007471 else if (isUnsigned)
7472 libCall = spv::GLSLstd450UClamp;
7473 else
7474 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007475 builder.promoteScalar(precision, operands.front(), operands[1]);
7476 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007477 break;
7478 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007479 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7480 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007481 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007482 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007483 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007484 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007485 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007486 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007487 break;
7488 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007489 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007490 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007491 break;
7492 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007493 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007494 builder.promoteScalar(precision, operands[0], operands[2]);
7495 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007496 break;
7497
7498 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007499 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007500 break;
7501 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007502 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007503 break;
7504 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007505 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007506 break;
7507 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007508 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007509 break;
7510 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007511 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007512 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007513 case glslang::EOpBarrier:
7514 {
7515 // This is for the extended controlBarrier function, with four operands.
7516 // The unextended barrier() goes through createNoArgOperation.
7517 assert(operands.size() == 4);
7518 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7519 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7520 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007521 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7522 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007523 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7524 spv::MemorySemanticsMakeVisibleKHRMask |
7525 spv::MemorySemanticsOutputMemoryKHRMask |
7526 spv::MemorySemanticsVolatileMask)) {
7527 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7528 }
John Kessenich8985fc92020-03-03 10:25:07 -07007529 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7530 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007531 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7532 }
7533 return 0;
7534 }
7535 break;
7536 case glslang::EOpMemoryBarrier:
7537 {
7538 // This is for the extended memoryBarrier function, with three operands.
7539 // The unextended memoryBarrier() goes through createNoArgOperation.
7540 assert(operands.size() == 3);
7541 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7542 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7543 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7544 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7545 spv::MemorySemanticsMakeVisibleKHRMask |
7546 spv::MemorySemanticsOutputMemoryKHRMask |
7547 spv::MemorySemanticsVolatileMask)) {
7548 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7549 }
7550 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7551 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7552 }
7553 return 0;
7554 }
7555 break;
7556
John Kessenicha28f7a72019-08-06 07:00:58 -06007557#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007558 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007559 if (typeProxy == glslang::EbtFloat16)
7560 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007561 libCall = spv::GLSLstd450InterpolateAtSample;
7562 break;
7563 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007564 if (typeProxy == glslang::EbtFloat16)
7565 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007566 libCall = spv::GLSLstd450InterpolateAtOffset;
7567 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007568 case glslang::EOpAddCarry:
7569 opCode = spv::OpIAddCarry;
7570 typeId = builder.makeStructResultType(typeId0, typeId0);
7571 consumedOperands = 2;
7572 break;
7573 case glslang::EOpSubBorrow:
7574 opCode = spv::OpISubBorrow;
7575 typeId = builder.makeStructResultType(typeId0, typeId0);
7576 consumedOperands = 2;
7577 break;
7578 case glslang::EOpUMulExtended:
7579 opCode = spv::OpUMulExtended;
7580 typeId = builder.makeStructResultType(typeId0, typeId0);
7581 consumedOperands = 2;
7582 break;
7583 case glslang::EOpIMulExtended:
7584 opCode = spv::OpSMulExtended;
7585 typeId = builder.makeStructResultType(typeId0, typeId0);
7586 consumedOperands = 2;
7587 break;
7588 case glslang::EOpBitfieldExtract:
7589 if (isUnsigned)
7590 opCode = spv::OpBitFieldUExtract;
7591 else
7592 opCode = spv::OpBitFieldSExtract;
7593 break;
7594 case glslang::EOpBitfieldInsert:
7595 opCode = spv::OpBitFieldInsert;
7596 break;
7597
7598 case glslang::EOpFma:
7599 libCall = spv::GLSLstd450Fma;
7600 break;
7601 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007602 {
7603 libCall = spv::GLSLstd450FrexpStruct;
7604 assert(builder.isPointerType(typeId1));
7605 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007606 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007607 if (width == 16)
7608 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7609 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007610 if (builder.getNumComponents(operands[0]) == 1)
7611 frexpIntType = builder.makeIntegerType(width, true);
7612 else
John Kessenich8985fc92020-03-03 10:25:07 -07007613 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7614 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007615 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7616 consumedOperands = 1;
7617 }
John Kessenich55e7d112015-11-15 21:33:39 -07007618 break;
7619 case glslang::EOpLdexp:
7620 libCall = spv::GLSLstd450Ldexp;
7621 break;
7622
Rex Xu574ab042016-04-14 16:53:07 +08007623 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007624 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007625
John Kessenich66011cb2018-03-06 16:12:04 -07007626 case glslang::EOpSubgroupBroadcast:
7627 case glslang::EOpSubgroupBallotBitExtract:
7628 case glslang::EOpSubgroupShuffle:
7629 case glslang::EOpSubgroupShuffleXor:
7630 case glslang::EOpSubgroupShuffleUp:
7631 case glslang::EOpSubgroupShuffleDown:
7632 case glslang::EOpSubgroupClusteredAdd:
7633 case glslang::EOpSubgroupClusteredMul:
7634 case glslang::EOpSubgroupClusteredMin:
7635 case glslang::EOpSubgroupClusteredMax:
7636 case glslang::EOpSubgroupClusteredAnd:
7637 case glslang::EOpSubgroupClusteredOr:
7638 case glslang::EOpSubgroupClusteredXor:
7639 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007640 case glslang::EOpSubgroupPartitionedAdd:
7641 case glslang::EOpSubgroupPartitionedMul:
7642 case glslang::EOpSubgroupPartitionedMin:
7643 case glslang::EOpSubgroupPartitionedMax:
7644 case glslang::EOpSubgroupPartitionedAnd:
7645 case glslang::EOpSubgroupPartitionedOr:
7646 case glslang::EOpSubgroupPartitionedXor:
7647 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7648 case glslang::EOpSubgroupPartitionedInclusiveMul:
7649 case glslang::EOpSubgroupPartitionedInclusiveMin:
7650 case glslang::EOpSubgroupPartitionedInclusiveMax:
7651 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7652 case glslang::EOpSubgroupPartitionedInclusiveOr:
7653 case glslang::EOpSubgroupPartitionedInclusiveXor:
7654 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7655 case glslang::EOpSubgroupPartitionedExclusiveMul:
7656 case glslang::EOpSubgroupPartitionedExclusiveMin:
7657 case glslang::EOpSubgroupPartitionedExclusiveMax:
7658 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7659 case glslang::EOpSubgroupPartitionedExclusiveOr:
7660 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007661 return createSubgroupOperation(op, typeId, operands, typeProxy);
7662
Rex Xu9d93a232016-05-05 12:30:44 +08007663 case glslang::EOpSwizzleInvocations:
7664 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7665 libCall = spv::SwizzleInvocationsAMD;
7666 break;
7667 case glslang::EOpSwizzleInvocationsMasked:
7668 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7669 libCall = spv::SwizzleInvocationsMaskedAMD;
7670 break;
7671 case glslang::EOpWriteInvocation:
7672 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7673 libCall = spv::WriteInvocationAMD;
7674 break;
7675
7676 case glslang::EOpMin3:
7677 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7678 if (isFloat)
7679 libCall = spv::FMin3AMD;
7680 else {
7681 if (isUnsigned)
7682 libCall = spv::UMin3AMD;
7683 else
7684 libCall = spv::SMin3AMD;
7685 }
7686 break;
7687 case glslang::EOpMax3:
7688 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7689 if (isFloat)
7690 libCall = spv::FMax3AMD;
7691 else {
7692 if (isUnsigned)
7693 libCall = spv::UMax3AMD;
7694 else
7695 libCall = spv::SMax3AMD;
7696 }
7697 break;
7698 case glslang::EOpMid3:
7699 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7700 if (isFloat)
7701 libCall = spv::FMid3AMD;
7702 else {
7703 if (isUnsigned)
7704 libCall = spv::UMid3AMD;
7705 else
7706 libCall = spv::SMid3AMD;
7707 }
7708 break;
7709
7710 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007711 if (typeProxy == glslang::EbtFloat16)
7712 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007713 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7714 libCall = spv::InterpolateAtVertexAMD;
7715 break;
Chao Chen3c366992018-09-19 11:41:59 -07007716
Daniel Kochdb32b242020-03-17 20:42:47 -04007717 case glslang::EOpReportIntersection:
Chao Chenb50c02e2018-09-19 11:42:24 -07007718 typeId = builder.makeBoolType();
Daniel Kochdb32b242020-03-17 20:42:47 -04007719 opCode = spv::OpReportIntersectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007720 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04007721 case glslang::EOpTrace:
Daniel Kochdb32b242020-03-17 20:42:47 -04007722 builder.createNoResultOp(spv::OpTraceRayKHR, operands);
Ashwin Leleff1783d2018-10-22 16:41:44 -07007723 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04007724 case glslang::EOpExecuteCallable:
Daniel Kochdb32b242020-03-17 20:42:47 -04007725 builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007726 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007727
7728 case glslang::EOpRayQueryInitialize:
Torosdagli06c2eee2020-03-19 11:09:57 -04007729 builder.createNoResultOp(spv::OpRayQueryInitializeKHR, operands);
7730 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007731 case glslang::EOpRayQueryTerminate:
Torosdagli06c2eee2020-03-19 11:09:57 -04007732 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operands);
7733 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007734 case glslang::EOpRayQueryGenerateIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007735 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR, operands);
7736 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007737 case glslang::EOpRayQueryConfirmIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007738 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operands);
7739 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007740 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04007741 typeId = builder.makeBoolType();
7742 opCode = spv::OpRayQueryProceedKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007743 break;
7744 case glslang::EOpRayQueryGetIntersectionType:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007745 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007746 opCode = spv::OpRayQueryGetIntersectionTypeKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007747 break;
7748 case glslang::EOpRayQueryGetRayTMin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007749 typeId = builder.makeFloatType(32);
7750 opCode = spv::OpRayQueryGetRayTMinKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007751 break;
7752 case glslang::EOpRayQueryGetRayFlags:
Torosdagli06c2eee2020-03-19 11:09:57 -04007753 typeId = builder.makeIntType(32);
7754 opCode = spv::OpRayQueryGetRayFlagsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007755 break;
7756 case glslang::EOpRayQueryGetIntersectionT:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007757 typeId = builder.makeFloatType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007758 opCode = spv::OpRayQueryGetIntersectionTKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007759 break;
7760 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007761 typeId = builder.makeIntType(32);
7762 opCode = spv::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007763 break;
7764 case glslang::EOpRayQueryGetIntersectionInstanceId:
Torosdagli06c2eee2020-03-19 11:09:57 -04007765 typeId = builder.makeIntType(32);
7766 opCode = spv::OpRayQueryGetIntersectionInstanceIdKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007767 break;
7768 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
Torosdagli06c2eee2020-03-19 11:09:57 -04007769 typeId = builder.makeIntType(32);
7770 opCode = spv::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007771 break;
7772 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007773 typeId = builder.makeIntType(32);
7774 opCode = spv::OpRayQueryGetIntersectionGeometryIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007775 break;
7776 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007777 typeId = builder.makeIntType(32);
7778 opCode = spv::OpRayQueryGetIntersectionPrimitiveIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007779 break;
7780 case glslang::EOpRayQueryGetIntersectionBarycentrics:
Torosdagli06c2eee2020-03-19 11:09:57 -04007781 typeId = builder.makeVectorType(builder.makeFloatType(32), 2);
7782 opCode = spv::OpRayQueryGetIntersectionBarycentricsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007783 break;
7784 case glslang::EOpRayQueryGetIntersectionFrontFace:
Torosdagli06c2eee2020-03-19 11:09:57 -04007785 typeId = builder.makeBoolType();
7786 opCode = spv::OpRayQueryGetIntersectionFrontFaceKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007787 break;
7788 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
Torosdagli06c2eee2020-03-19 11:09:57 -04007789 typeId = builder.makeBoolType();
7790 opCode = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007791 break;
7792 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007793 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7794 opCode = spv::OpRayQueryGetIntersectionObjectRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007795 break;
7796 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007797 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7798 opCode = spv::OpRayQueryGetIntersectionObjectRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007799 break;
7800 case glslang::EOpRayQueryGetWorldRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007801 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7802 opCode = spv::OpRayQueryGetWorldRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007803 break;
7804 case glslang::EOpRayQueryGetWorldRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007805 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7806 opCode = spv::OpRayQueryGetWorldRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007807 break;
7808 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
Torosdagli06c2eee2020-03-19 11:09:57 -04007809 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007810 opCode = spv::OpRayQueryGetIntersectionObjectToWorldKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007811 break;
7812 case glslang::EOpRayQueryGetIntersectionWorldToObject:
Torosdagli06c2eee2020-03-19 11:09:57 -04007813 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007814 opCode = spv::OpRayQueryGetIntersectionWorldToObjectKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007815 break;
Chao Chen3c366992018-09-19 11:41:59 -07007816 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7817 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7818 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007819 case glslang::EOpCooperativeMatrixMulAdd:
7820 opCode = spv::OpCooperativeMatrixMulAddNV;
7821 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007822#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007823 default:
7824 return 0;
7825 }
7826
7827 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007828 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007829 // Use an extended instruction from the standard library.
7830 // Construct the call arguments, without modifying the original operands vector.
7831 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7832 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007833 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007834 } else if (opCode == spv::OpDot && !isFloat) {
7835 // int dot(int, int)
7836 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7837 const int componentCount = builder.getNumComponents(operands[0]);
7838 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7839 builder.setPrecision(mulOp, precision);
7840 id = builder.createCompositeExtract(mulOp, typeId, 0);
7841 for (int i = 1; i < componentCount; ++i) {
7842 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07007843 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01007844 }
John Kessenich2359bd02015-12-06 19:29:11 -07007845 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007846 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007847 case 0:
7848 // should all be handled by visitAggregate and createNoArgOperation
7849 assert(0);
7850 return 0;
7851 case 1:
7852 // should all be handled by createUnaryOperation
7853 assert(0);
7854 return 0;
7855 case 2:
7856 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7857 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007858 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007859 // anything 3 or over doesn't have l-value operands, so all should be consumed
7860 assert(consumedOperands == operands.size());
7861 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007862 break;
7863 }
7864 }
7865
John Kessenichb9197c82019-08-11 07:41:45 -06007866#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007867 // Decode the return types that were structures
7868 switch (op) {
7869 case glslang::EOpAddCarry:
7870 case glslang::EOpSubBorrow:
7871 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7872 id = builder.createCompositeExtract(id, typeId0, 0);
7873 break;
7874 case glslang::EOpUMulExtended:
7875 case glslang::EOpIMulExtended:
7876 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7877 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7878 break;
7879 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007880 {
7881 assert(operands.size() == 2);
7882 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7883 // "exp" is floating-point type (from HLSL intrinsic)
7884 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7885 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7886 builder.createStore(member1, operands[1]);
7887 } else
7888 // "exp" is integer type (from GLSL built-in function)
7889 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7890 id = builder.createCompositeExtract(id, typeId0, 0);
7891 }
John Kessenich55e7d112015-11-15 21:33:39 -07007892 break;
7893 default:
7894 break;
7895 }
John Kessenichb9197c82019-08-11 07:41:45 -06007896#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007897
John Kessenich32cfd492016-02-02 12:37:46 -07007898 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007899}
7900
Rex Xu9d93a232016-05-05 12:30:44 +08007901// Intrinsics with no arguments (or no return value, and no precision).
7902spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007903{
Jeff Bolz36831c92018-09-05 10:11:41 -05007904 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07007905 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
7906 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007907
7908 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007909 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007910 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007911 if (glslangIntermediate->usingVulkanMemoryModel()) {
7912 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7913 spv::MemorySemanticsOutputMemoryKHRMask |
7914 spv::MemorySemanticsAcquireReleaseMask);
7915 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7916 } else {
7917 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7918 }
John Kessenich82979362017-12-11 04:02:24 -07007919 } else {
7920 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7921 spv::MemorySemanticsWorkgroupMemoryMask |
7922 spv::MemorySemanticsAcquireReleaseMask);
7923 }
John Kessenich140f3df2015-06-26 16:58:36 -06007924 return 0;
7925 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007926 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7927 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007928 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007929 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007930 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7931 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007932 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007933 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007934 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7935 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007936 return 0;
7937 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007938 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7939 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007940 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007941#ifndef GLSLANG_WEB
7942 case glslang::EOpMemoryBarrierAtomicCounter:
7943 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7944 spv::MemorySemanticsAcquireReleaseMask);
7945 return 0;
7946 case glslang::EOpMemoryBarrierImage:
7947 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7948 spv::MemorySemanticsAcquireReleaseMask);
7949 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007950 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007951 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007952 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007953 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007954 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007955 case glslang::EOpDeviceMemoryBarrier:
7956 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7957 spv::MemorySemanticsImageMemoryMask |
7958 spv::MemorySemanticsAcquireReleaseMask);
7959 return 0;
7960 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7961 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7962 spv::MemorySemanticsImageMemoryMask |
7963 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007964 return 0;
7965 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007966 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7967 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007968 return 0;
7969 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007970 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7971 spv::MemorySemanticsWorkgroupMemoryMask |
7972 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007973 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007974 case glslang::EOpSubgroupBarrier:
7975 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7976 spv::MemorySemanticsAcquireReleaseMask);
7977 return spv::NoResult;
7978 case glslang::EOpSubgroupMemoryBarrier:
7979 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7980 spv::MemorySemanticsAcquireReleaseMask);
7981 return spv::NoResult;
7982 case glslang::EOpSubgroupMemoryBarrierBuffer:
7983 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7984 spv::MemorySemanticsAcquireReleaseMask);
7985 return spv::NoResult;
7986 case glslang::EOpSubgroupMemoryBarrierImage:
7987 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7988 spv::MemorySemanticsAcquireReleaseMask);
7989 return spv::NoResult;
7990 case glslang::EOpSubgroupMemoryBarrierShared:
7991 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7992 spv::MemorySemanticsAcquireReleaseMask);
7993 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06007994
7995 case glslang::EOpEmitVertex:
7996 builder.createNoResultOp(spv::OpEmitVertex);
7997 return 0;
7998 case glslang::EOpEndPrimitive:
7999 builder.createNoResultOp(spv::OpEndPrimitive);
8000 return 0;
8001
John Kessenich66011cb2018-03-06 16:12:04 -07008002 case glslang::EOpSubgroupElect: {
8003 std::vector<spv::Id> operands;
8004 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
8005 }
Rex Xu9d93a232016-05-05 12:30:44 +08008006 case glslang::EOpTime:
8007 {
8008 std::vector<spv::Id> args; // Dummy arguments
8009 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
8010 return builder.setPrecision(id, precision);
8011 }
Daniel Kochdb32b242020-03-17 20:42:47 -04008012 case glslang::EOpIgnoreIntersection:
8013 builder.createNoResultOp(spv::OpIgnoreIntersectionKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008014 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04008015 case glslang::EOpTerminateRay:
8016 builder.createNoResultOp(spv::OpTerminateRayKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008017 return 0;
Torosdagli06c2eee2020-03-19 11:09:57 -04008018 case glslang::EOpRayQueryInitialize:
8019 builder.createNoResultOp(spv::OpRayQueryInitializeKHR);
8020 return 0;
8021 case glslang::EOpRayQueryTerminate:
8022 builder.createNoResultOp(spv::OpRayQueryTerminateKHR);
8023 return 0;
8024 case glslang::EOpRayQueryGenerateIntersection:
8025 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR);
8026 return 0;
8027 case glslang::EOpRayQueryConfirmIntersection:
8028 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR);
8029 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05008030 case glslang::EOpBeginInvocationInterlock:
8031 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
8032 return 0;
8033 case glslang::EOpEndInvocationInterlock:
8034 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
8035 return 0;
8036
Jeff Bolzba6170b2019-07-01 09:23:23 -05008037 case glslang::EOpIsHelperInvocation:
8038 {
8039 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08008040 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
8041 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
8042 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05008043 }
8044
amhagan91fb0092019-07-10 21:14:38 -04008045 case glslang::EOpReadClockSubgroupKHR: {
8046 std::vector<spv::Id> args;
8047 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
8048 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8049 builder.addCapability(spv::CapabilityShaderClockKHR);
8050 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8051 }
8052
8053 case glslang::EOpReadClockDeviceKHR: {
8054 std::vector<spv::Id> args;
8055 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
8056 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8057 builder.addCapability(spv::CapabilityShaderClockKHR);
8058 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8059 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06008060#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008061 default:
John Kessenich155d3512019-08-08 23:29:20 -06008062 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008063 }
John Kessenich155d3512019-08-08 23:29:20 -06008064
8065 logger->missingFunctionality("unknown operation with no arguments");
8066
8067 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008068}
8069
8070spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
8071{
John Kessenich2f273362015-07-18 22:34:27 -06008072 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06008073 spv::Id id;
8074 if (symbolValues.end() != iter) {
8075 id = iter->second;
8076 return id;
8077 }
8078
8079 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06008080 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
Daniel Kochdb32b242020-03-17 20:42:47 -04008081 auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06008082 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06008083 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06008084 if (forcedType.second != spv::NoType)
8085 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06008086
Rex Xuc884b4a2016-06-29 15:03:44 +08008087 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008088 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
8089 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
8090 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06008091#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008092 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06008093 if (symbol->getQualifier().hasComponent())
8094 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
8095 if (symbol->getQualifier().hasIndex())
8096 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07008097#endif
John Kessenich6c292d32016-02-15 20:58:50 -07008098 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07008099 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06008100 // atomic counters use this:
8101 if (symbol->getQualifier().hasOffset())
8102 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008103 }
8104
scygan2c864272016-05-18 18:09:17 +02008105 if (symbol->getQualifier().hasLocation())
8106 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07008107 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07008108 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07008109 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06008110 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07008111 }
John Kessenich140f3df2015-06-26 16:58:36 -06008112 if (symbol->getQualifier().hasSet())
8113 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07008114 else if (IsDescriptorResource(symbol->getType())) {
8115 // default to 0
8116 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
8117 }
John Kessenich140f3df2015-06-26 16:58:36 -06008118 if (symbol->getQualifier().hasBinding())
8119 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06008120 else if (IsDescriptorResource(symbol->getType())) {
8121 // default to 0
8122 builder.addDecoration(id, spv::DecorationBinding, 0);
8123 }
John Kessenich6c292d32016-02-15 20:58:50 -07008124 if (symbol->getQualifier().hasAttachment())
8125 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06008126 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07008127 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07008128 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008129 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07008130 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
8131 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
8132 builder.addDecoration(id, spv::DecorationXfbStride, stride);
8133 }
8134 if (symbol->getQualifier().hasXfbOffset())
8135 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008136 }
8137
John Kessenichb9197c82019-08-11 07:41:45 -06008138 // add built-in variable decoration
8139 if (builtIn != spv::BuiltInMax) {
8140 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
8141 }
8142
8143#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08008144 if (symbol->getType().isImage()) {
8145 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07008146 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
8147 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08008148 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07008149 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08008150 }
8151
John Kessenich5611c6d2018-04-05 11:25:02 -06008152 // nonuniform
8153 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
8154
chaoc0ad6a4e2016-12-19 16:29:34 -08008155 if (builtIn == spv::BuiltInSampleMask) {
8156 spv::Decoration decoration;
8157 // GL_NV_sample_mask_override_coverage extension
8158 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08008159 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08008160 else
8161 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07008162 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08008163 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07008164 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08008165 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
8166 }
8167 }
chaoc771d89f2017-01-13 01:10:53 -08008168 else if (builtIn == spv::BuiltInLayer) {
8169 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06008170 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008171 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08008172 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
8173 builder.addExtension(spv::E_SPV_NV_viewport_array2);
8174 }
John Kessenichb41bff62017-08-11 13:07:17 -06008175 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008176 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
8177 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08008178 builder.addCapability(spv::CapabilityShaderStereoViewNV);
8179 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
8180 }
8181 }
8182
chaoc6e5acae2016-12-20 13:28:52 -08008183 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008184 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08008185 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08008186 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
8187 }
Chao Chen9eada4b2018-09-19 11:39:56 -07008188 if (symbol->getQualifier().pervertexNV) {
8189 builder.addDecoration(id, spv::DecorationPerVertexNV);
8190 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
8191 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
8192 }
chaoc0ad6a4e2016-12-19 16:29:34 -08008193
John Kessenich5d610ee2018-03-07 18:05:55 -07008194 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
8195 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
8196 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
8197 symbol->getType().getQualifier().semanticName);
8198 }
8199
John Kessenich7015bd62019-08-01 03:28:08 -06008200 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07008201 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
8202 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008203 }
John Kessenichb9197c82019-08-11 07:41:45 -06008204#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008205
John Kessenich140f3df2015-06-26 16:58:36 -06008206 return id;
8207}
8208
John Kessenicha28f7a72019-08-06 07:00:58 -06008209#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008210// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
8211void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
8212{
8213 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07008214 if (qualifier.perPrimitiveNV) {
8215 // Need to add capability/extension for fragment shader.
8216 // Mesh shader already adds this by default.
8217 if (glslangIntermediate->getStage() == EShLangFragment) {
8218 builder.addCapability(spv::CapabilityMeshShadingNV);
8219 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8220 }
Chao Chen3c366992018-09-19 11:41:59 -07008221 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008222 }
Chao Chen3c366992018-09-19 11:41:59 -07008223 if (qualifier.perViewNV)
8224 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
8225 if (qualifier.perTaskNV)
8226 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
8227 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07008228 if (qualifier.perPrimitiveNV) {
8229 // Need to add capability/extension for fragment shader.
8230 // Mesh shader already adds this by default.
8231 if (glslangIntermediate->getStage() == EShLangFragment) {
8232 builder.addCapability(spv::CapabilityMeshShadingNV);
8233 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8234 }
Chao Chen3c366992018-09-19 11:41:59 -07008235 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008236 }
Chao Chen3c366992018-09-19 11:41:59 -07008237 if (qualifier.perViewNV)
8238 builder.addDecoration(id, spv::DecorationPerViewNV);
8239 if (qualifier.perTaskNV)
8240 builder.addDecoration(id, spv::DecorationPerTaskNV);
8241 }
8242}
8243#endif
8244
John Kessenich55e7d112015-11-15 21:33:39 -07008245// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008246// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008247//
8248// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8249//
8250// Recursively walk the nodes. The nodes form a tree whose leaves are
8251// regular constants, which themselves are trees that createSpvConstant()
8252// recursively walks. So, this function walks the "top" of the tree:
8253// - emit specialization constant-building instructions for specConstant
8254// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008255spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008256{
John Kessenich7cc0e282016-03-20 00:46:02 -06008257 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008258
qining4f4bb812016-04-03 23:55:17 -04008259 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008260 if (! node.getQualifier().specConstant) {
8261 // hand off to the non-spec-constant path
8262 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8263 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008264 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8265 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8266 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008267 }
8268
8269 // We now know we have a specialization constant to build
8270
John Kessenichd94c0032016-05-30 19:29:40 -06008271 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008272 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8273 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8274 std::vector<spv::Id> dimConstId;
8275 for (int dim = 0; dim < 3; ++dim) {
8276 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8277 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008278 if (specConst) {
8279 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8280 glslangIntermediate->getLocalSizeSpecId(dim));
8281 }
qining4f4bb812016-04-03 23:55:17 -04008282 }
8283 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8284 }
8285
8286 // An AST node labelled as specialization constant should be a symbol node.
8287 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8288 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008289 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008290 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008291 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8292 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8293 // will set the builder into spec constant op instruction generating mode.
8294 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008295 result = accessChainLoad(sub_tree->getType());
8296 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008297 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008298 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008299 } else {
8300 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008301 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008302 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008303 builder.addName(result, sn->getName().c_str());
8304 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008305 }
qining4f4bb812016-04-03 23:55:17 -04008306
8307 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8308 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008309 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008310 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008311}
8312
John Kessenich140f3df2015-06-26 16:58:36 -06008313// Use 'consts' as the flattened glslang source of scalar constants to recursively
8314// build the aggregate SPIR-V constant.
8315//
8316// If there are not enough elements present in 'consts', 0 will be substituted;
8317// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8318//
John Kessenich8985fc92020-03-03 10:25:07 -07008319spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8320 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008321{
8322 // vector of constants for SPIR-V
8323 std::vector<spv::Id> spvConsts;
8324
8325 // Type is used for struct and array constants
8326 spv::Id typeId = convertGlslangToSpvType(glslangType);
8327
8328 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008329 glslang::TType elementType(glslangType, 0);
8330 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008331 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008332 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008333 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008334 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008335 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008336 } else if (glslangType.isCoopMat()) {
8337 glslang::TType componentType(glslangType.getBasicType());
8338 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008339 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008340 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8341 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008342 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008343 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008344 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8345 bool zero = nextConst >= consts.size();
8346 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008347 case glslang::EbtInt:
8348 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8349 break;
8350 case glslang::EbtUint:
8351 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8352 break;
8353 case glslang::EbtFloat:
8354 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8355 break;
8356 case glslang::EbtBool:
8357 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8358 break;
8359#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008360 case glslang::EbtInt8:
8361 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8362 break;
8363 case glslang::EbtUint8:
8364 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8365 break;
8366 case glslang::EbtInt16:
8367 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8368 break;
8369 case glslang::EbtUint16:
8370 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8371 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008372 case glslang::EbtInt64:
8373 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8374 break;
8375 case glslang::EbtUint64:
8376 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8377 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008378 case glslang::EbtDouble:
8379 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8380 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008381 case glslang::EbtFloat16:
8382 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8383 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008384#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008385 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008386 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008387 break;
8388 }
8389 ++nextConst;
8390 }
8391 } else {
8392 // we have a non-aggregate (scalar) constant
8393 bool zero = nextConst >= consts.size();
8394 spv::Id scalar = 0;
8395 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008396 case glslang::EbtInt:
8397 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8398 break;
8399 case glslang::EbtUint:
8400 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8401 break;
8402 case glslang::EbtFloat:
8403 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8404 break;
8405 case glslang::EbtBool:
8406 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8407 break;
8408#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008409 case glslang::EbtInt8:
8410 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8411 break;
8412 case glslang::EbtUint8:
8413 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8414 break;
8415 case glslang::EbtInt16:
8416 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8417 break;
8418 case glslang::EbtUint16:
8419 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8420 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008421 case glslang::EbtInt64:
8422 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8423 break;
8424 case glslang::EbtUint64:
8425 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8426 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008427 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008428 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008429 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008430 case glslang::EbtFloat16:
8431 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8432 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008433 case glslang::EbtReference:
8434 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8435 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8436 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008437#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008438 case glslang::EbtString:
8439 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8440 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008441 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008442 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008443 break;
8444 }
8445 ++nextConst;
8446 return scalar;
8447 }
8448
8449 return builder.makeCompositeConstant(typeId, spvConsts);
8450}
8451
John Kessenich7c1aa102015-10-15 13:29:11 -06008452// Return true if the node is a constant or symbol whose reading has no
8453// non-trivial observable cost or effect.
8454bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8455{
8456 // don't know what this is
8457 if (node == nullptr)
8458 return false;
8459
8460 // a constant is safe
8461 if (node->getAsConstantUnion() != nullptr)
8462 return true;
8463
8464 // not a symbol means non-trivial
8465 if (node->getAsSymbolNode() == nullptr)
8466 return false;
8467
8468 // a symbol, depends on what's being read
8469 switch (node->getType().getQualifier().storage) {
8470 case glslang::EvqTemporary:
8471 case glslang::EvqGlobal:
8472 case glslang::EvqIn:
8473 case glslang::EvqInOut:
8474 case glslang::EvqConst:
8475 case glslang::EvqConstReadOnly:
8476 case glslang::EvqUniform:
8477 return true;
8478 default:
8479 return false;
8480 }
qining25262b32016-05-06 17:25:16 -04008481}
John Kessenich7c1aa102015-10-15 13:29:11 -06008482
8483// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008484// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008485// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008486// Return true if trivial.
8487bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8488{
8489 if (node == nullptr)
8490 return false;
8491
John Kessenich84cc15f2017-05-24 16:44:47 -06008492 // count non scalars as trivial, as well as anything coming from HLSL
8493 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008494 return true;
8495
John Kessenich7c1aa102015-10-15 13:29:11 -06008496 // symbols and constants are trivial
8497 if (isTrivialLeaf(node))
8498 return true;
8499
8500 // otherwise, it needs to be a simple operation or one or two leaf nodes
8501
8502 // not a simple operation
8503 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8504 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8505 if (binaryNode == nullptr && unaryNode == nullptr)
8506 return false;
8507
8508 // not on leaf nodes
8509 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8510 return false;
8511
8512 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8513 return false;
8514 }
8515
8516 switch (node->getAsOperator()->getOp()) {
8517 case glslang::EOpLogicalNot:
8518 case glslang::EOpConvIntToBool:
8519 case glslang::EOpConvUintToBool:
8520 case glslang::EOpConvFloatToBool:
8521 case glslang::EOpConvDoubleToBool:
8522 case glslang::EOpEqual:
8523 case glslang::EOpNotEqual:
8524 case glslang::EOpLessThan:
8525 case glslang::EOpGreaterThan:
8526 case glslang::EOpLessThanEqual:
8527 case glslang::EOpGreaterThanEqual:
8528 case glslang::EOpIndexDirect:
8529 case glslang::EOpIndexDirectStruct:
8530 case glslang::EOpLogicalXor:
8531 case glslang::EOpAny:
8532 case glslang::EOpAll:
8533 return true;
8534 default:
8535 return false;
8536 }
8537}
8538
8539// Emit short-circuiting code, where 'right' is never evaluated unless
8540// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008541spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8542 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008543{
8544 spv::Id boolTypeId = builder.makeBoolType();
8545
8546 // emit left operand
8547 builder.clearAccessChain();
8548 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008549 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008550
8551 // Operands to accumulate OpPhi operands
8552 std::vector<spv::Id> phiOperands;
8553 // accumulate left operand's phi information
8554 phiOperands.push_back(leftId);
8555 phiOperands.push_back(builder.getBuildPoint()->getId());
8556
8557 // Make the two kinds of operation symmetric with a "!"
8558 // || => emit "if (! left) result = right"
8559 // && => emit "if ( left) result = right"
8560 //
8561 // TODO: this runtime "not" for || could be avoided by adding functionality
8562 // to 'builder' to have an "else" without an "then"
8563 if (op == glslang::EOpLogicalOr)
8564 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8565
8566 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008567 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008568
8569 // emit right operand as the "then" part of the "if"
8570 builder.clearAccessChain();
8571 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008572 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008573
8574 // accumulate left operand's phi information
8575 phiOperands.push_back(rightId);
8576 phiOperands.push_back(builder.getBuildPoint()->getId());
8577
8578 // finish the "if"
8579 ifBuilder.makeEndIf();
8580
8581 // phi together the two results
8582 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8583}
8584
John Kessenicha28f7a72019-08-06 07:00:58 -06008585#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008586// Return type Id of the imported set of extended instructions corresponds to the name.
8587// Import this set if it has not been imported yet.
8588spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8589{
8590 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8591 return extBuiltinMap[name];
8592 else {
Rex Xu51596642016-09-21 18:56:12 +08008593 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008594 spv::Id extBuiltins = builder.import(name);
8595 extBuiltinMap[name] = extBuiltins;
8596 return extBuiltins;
8597 }
8598}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008599#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008600
John Kessenich140f3df2015-06-26 16:58:36 -06008601}; // end anonymous namespace
8602
8603namespace glslang {
8604
John Kessenich68d78fd2015-07-12 19:28:10 -06008605void GetSpirvVersion(std::string& version)
8606{
John Kessenich9e55f632015-07-15 10:03:39 -06008607 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008608 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008609 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008610 version = buf;
8611}
8612
John Kessenicha372a3e2017-11-02 22:32:14 -06008613// For low-order part of the generator's magic number. Bump up
8614// when there is a change in the style (e.g., if SSA form changes,
8615// or a different instruction sequence to do something gets used).
8616int GetSpirvGeneratorVersion()
8617{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008618 // return 1; // start
8619 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008620 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008621 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008622 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008623 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8624 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008625 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
8626 return 8; // switch to new dead block eliminator; use OpUnreachable
John Kessenicha372a3e2017-11-02 22:32:14 -06008627}
8628
John Kessenich140f3df2015-06-26 16:58:36 -06008629// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008630void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008631{
8632 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008633 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008634 if (out.fail())
8635 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008636 for (int i = 0; i < (int)spirv.size(); ++i) {
8637 unsigned int word = spirv[i];
8638 out.write((const char*)&word, 4);
8639 }
8640 out.close();
8641}
8642
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008643// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008644void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008645{
John Kessenich155d3512019-08-08 23:29:20 -06008646#ifndef GLSLANG_WEB
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008647 std::ofstream out;
8648 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008649 if (out.fail())
8650 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008651 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008652 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008653 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008654 if (varName != nullptr) {
8655 out << "\t #pragma once" << std::endl;
8656 out << "const uint32_t " << varName << "[] = {" << std::endl;
8657 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008658 const int WORDS_PER_LINE = 8;
8659 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8660 out << "\t";
8661 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8662 const unsigned int word = spirv[i + j];
8663 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8664 if (i + j + 1 < (int)spirv.size()) {
8665 out << ",";
8666 }
8667 }
8668 out << std::endl;
8669 }
Flavio15017db2017-02-15 14:29:33 -08008670 if (varName != nullptr) {
8671 out << "};";
8672 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008673 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008674#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008675}
8676
John Kessenich140f3df2015-06-26 16:58:36 -06008677//
8678// Set up the glslang traversal
8679//
John Kessenich4e11b612018-08-30 16:56:59 -06008680void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008681{
Lei Zhang17535f72016-05-04 15:55:59 -04008682 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008683 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008684}
8685
John Kessenich4e11b612018-08-30 16:56:59 -06008686void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008687 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008688{
John Kessenich140f3df2015-06-26 16:58:36 -06008689 TIntermNode* root = intermediate.getTreeRoot();
8690
8691 if (root == 0)
8692 return;
8693
John Kessenich4e11b612018-08-30 16:56:59 -06008694 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008695 if (options == nullptr)
8696 options = &defaultOptions;
8697
John Kessenich4e11b612018-08-30 16:56:59 -06008698 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008699
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008700 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008701 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008702 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008703 it.dumpSpv(spirv);
8704
GregFfb03a552018-03-29 11:49:14 -06008705#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008706 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8707 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008708 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8709 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008710 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008711 prelegalization = false;
8712 }
John Kessenich717c80a2018-08-23 15:17:10 -06008713
John Kessenich4e11b612018-08-30 16:56:59 -06008714 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008715 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008716
John Kessenich717c80a2018-08-23 15:17:10 -06008717 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008718 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008719
GregFcd1f1692017-09-21 18:40:22 -06008720#endif
8721
John Kessenich4e11b612018-08-30 16:56:59 -06008722 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008723}
8724
8725}; // end namespace glslang