blob: 87a2830d07c4fbbd40e3a5a84e7d41f7bf5d5fef [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
John Kessenich56364b62020-03-01 04:51:40 -07003// Copyright (C) 2015-2020 Google, Inc.
John Kessenich66011cb2018-03-06 16:12:04 -07004// Copyright (C) 2017 ARM Limited.
Torosdagli06c2eee2020-03-19 11:09:57 -04005// Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06006//
John Kessenich927608b2017-01-06 12:34:14 -07007// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06008//
John Kessenich927608b2017-01-06 12:34:14 -07009// Redistribution and use in source and binary forms, with or without
10// modification, are permitted provided that the following conditions
11// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060012//
13// Redistributions of source code must retain the above copyright
14// notice, this list of conditions and the following disclaimer.
15//
16// Redistributions in binary form must reproduce the above
17// copyright notice, this list of conditions and the following
18// disclaimer in the documentation and/or other materials provided
19// with the distribution.
20//
21// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
22// contributors may be used to endorse or promote products derived
23// from this software without specific prior written permission.
24//
John Kessenich927608b2017-01-06 12:34:14 -070025// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
28// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
29// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
30// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
31// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
32// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
33// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060037
38//
John Kessenich140f3df2015-06-26 16:58:36 -060039// Visit the nodes in the glslang intermediate tree representation to
40// translate them to SPIR-V.
41//
42
John Kessenich5e4b1242015-08-06 22:53:06 -060043#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060044#include "GlslangToSpv.h"
45#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060046namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080047 #include "GLSL.std.450.h"
48 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070049 #include "GLSL.ext.EXT.h"
Rex Xu51596642016-09-21 18:56:12 +080050 #include "GLSL.ext.AMD.h"
chaoc0ad6a4e2016-12-19 16:29:34 -080051 #include "GLSL.ext.NV.h"
Jeff Bolz04d73732019-05-31 13:06:01 -050052 #include "NonSemanticDebugPrintf.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
qining4c912612016-04-01 10:35:16 -040071namespace {
72class SpecConstantOpModeGuard {
73public:
74 SpecConstantOpModeGuard(spv::Builder* builder)
75 : builder_(builder) {
76 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040077 }
78 ~SpecConstantOpModeGuard() {
79 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
80 : builder_->setToNormalCodeGenMode();
81 }
qining40887662016-04-03 22:20:42 -040082 void turnOnSpecConstantOpMode() {
83 builder_->setToSpecConstCodeGenMode();
84 }
qining4c912612016-04-01 10:35:16 -040085
86private:
87 spv::Builder* builder_;
88 bool previous_flag_;
89};
John Kessenichead86222018-03-28 18:01:20 -060090
91struct OpDecorations {
John Kessenichb9197c82019-08-11 07:41:45 -060092 public:
93 OpDecorations(spv::Decoration precision, spv::Decoration noContraction, spv::Decoration nonUniform) :
94 precision(precision)
95#ifndef GLSLANG_WEB
96 ,
97 noContraction(noContraction),
98 nonUniform(nonUniform)
99#endif
100 { }
101
John Kessenichead86222018-03-28 18:01:20 -0600102 spv::Decoration precision;
John Kessenichb9197c82019-08-11 07:41:45 -0600103
104#ifdef GLSLANG_WEB
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400105 void addNoContraction(spv::Builder&, spv::Id) const { }
106 void addNonUniform(spv::Builder&, spv::Id) const { }
John Kessenichb9197c82019-08-11 07:41:45 -0600107#else
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400108 void addNoContraction(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, noContraction); }
109 void addNonUniform(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, nonUniform); }
John Kessenichb9197c82019-08-11 07:41:45 -0600110 protected:
111 spv::Decoration noContraction;
112 spv::Decoration nonUniform;
113#endif
114
John Kessenichead86222018-03-28 18:01:20 -0600115};
116
117} // namespace
qining4c912612016-04-01 10:35:16 -0400118
John Kessenich140f3df2015-06-26 16:58:36 -0600119//
120// The main holder of information for translating glslang to SPIR-V.
121//
122// Derives from the AST walking base class.
123//
124class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
125public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700126 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
127 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700128 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600129
130 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
131 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
132 void visitConstantUnion(glslang::TIntermConstantUnion*);
133 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
134 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
135 void visitSymbol(glslang::TIntermSymbol* symbol);
136 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
137 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
138 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
139
John Kessenichfca82622016-11-26 13:23:20 -0700140 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700141 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600142
143protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700144 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
145 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
146
Rex Xu17ff3432016-10-14 17:41:45 +0800147 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800148 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600149 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500150 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
151 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
152 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
153 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100154 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700155 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700156 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
157 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700158 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600159 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600160 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich9c14f772019-06-17 08:38:35 -0600161 spv::Id createSpvVariable(const glslang::TIntermSymbol*, spv::Id forcedType);
John Kessenich140f3df2015-06-26 16:58:36 -0600162 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600163 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
164 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
165 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600166 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600167 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600168 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600169 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600170 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
171 glslang::TLayoutPacking, const glslang::TQualifier&);
172 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
173 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700174 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700175 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800176 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600177 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700178 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700179 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
180 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700181 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
182 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100183 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600184
John Kessenich6fccb3c2016-09-19 16:01:41 -0600185 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600186 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600187 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600188 void makeFunctions(const glslang::TIntermSequence&);
189 void makeGlobalInitializers(const glslang::TIntermSequence&);
190 void visitFunctions(const glslang::TIntermSequence&);
191 void handleFunctionEntry(const glslang::TIntermAggregate* node);
John Kessenich8985fc92020-03-03 10:25:07 -0700192 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
193 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -0600194 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
195 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600196 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
197
John Kessenichead86222018-03-28 18:01:20 -0600198 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
199 glslang::TBasicType typeProxy, bool reduceComparison = true);
200 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
201 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
John Kessenich8985fc92020-03-03 10:25:07 -0700202 glslang::TBasicType typeProxy,
203 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -0600204 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
205 glslang::TBasicType typeProxy);
206 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
207 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600208 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600209 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
John Kessenich8985fc92020-03-03 10:25:07 -0700210 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId,
211 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
212 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
213 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands,
214 glslang::TBasicType typeProxy);
215 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
216 spv::Id typeId, std::vector<spv::Id>& operands);
217 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands,
218 glslang::TBasicType typeProxy);
219 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId,
220 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800221 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600222 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700223 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
qining08408382016-03-21 09:51:37 -0400224 spv::Id createSpvConstant(const glslang::TIntermTyped&);
John Kessenich8985fc92020-03-03 10:25:07 -0700225 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&,
226 int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600227 bool isTrivialLeaf(const glslang::TIntermTyped* node);
228 bool isTrivial(const glslang::TIntermTyped* node);
229 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800230 spv::Id getExtBuiltins(const char* name);
Daniel Kochdb32b242020-03-17 20:42:47 -0400231 std::pair<spv::Id, spv::Id> getForcedType(glslang::TBuiltInVariable builtIn, const glslang::TType&);
John Kessenich9c14f772019-06-17 08:38:35 -0600232 spv::Id translateForcedType(spv::Id object);
Jeff Bolz53134492019-06-25 13:31:10 -0500233 spv::Id createCompositeConstruct(spv::Id typeId, std::vector<spv::Id> constituents);
John Kessenich140f3df2015-06-26 16:58:36 -0600234
John Kessenich121853f2017-05-31 17:11:16 -0600235 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600236 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600237 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700238 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600239 int sequenceDepth;
240
Lei Zhang17535f72016-05-04 15:55:59 -0400241 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400242
John Kessenich140f3df2015-06-26 16:58:36 -0600243 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
244 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700245 bool inEntryPoint;
246 bool entryPointTerminated;
John Kessenich8985fc92020-03-03 10:25:07 -0700247 bool linkageOnly; // true when visiting the set of objects in the AST present only for
248 // establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700249 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600250 const glslang::TIntermediate* glslangIntermediate;
John Kessenich605afc72019-06-17 23:33:09 -0600251 bool nanMinMaxClamp; // true if use NMin/NMax/NClamp instead of FMin/FMax/FClamp
John Kessenich140f3df2015-06-26 16:58:36 -0600252 spv::Id stdBuiltins;
Jeff Bolz04d73732019-05-31 13:06:01 -0500253 spv::Id nonSemanticDebugPrintf;
Rex Xu9d93a232016-05-05 12:30:44 +0800254 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600255
John Kessenich2f273362015-07-18 22:34:27 -0600256 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich8985fc92020-03-03 10:25:07 -0700257 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues,
258 // rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600259 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700260 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700261 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
Roy05a5b532020-01-03 16:21:34 +0800262 std::unordered_map<int, std::vector<int>> memberRemapper;
263 // for mapping glslang symbol struct to symbol Id
264 std::unordered_map<const glslang::TTypeList*, int> glslangTypeToIdMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600265 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700266 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600267 // Map pointee types for EbtReference to their forward pointers
268 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich9c14f772019-06-17 08:38:35 -0600269 // Type forcing, for when SPIR-V wants a different type than the AST,
270 // requiring local translation to and from SPIR-V type on every access.
271 // Maps <builtin-variable-id -> AST-required-type-id>
272 std::unordered_map<spv::Id, spv::Id> forceType;
John Kessenich140f3df2015-06-26 16:58:36 -0600273};
274
275//
276// Helper functions for translating glslang representations to SPIR-V enumerants.
277//
278
279// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700280spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600281{
John Kessenich155d3512019-08-08 23:29:20 -0600282#ifdef GLSLANG_WEB
283 return spv::SourceLanguageESSL;
284#endif
285
John Kessenich66e2faf2016-03-12 18:34:36 -0700286 switch (source) {
287 case glslang::EShSourceGlsl:
288 switch (profile) {
289 case ENoProfile:
290 case ECoreProfile:
291 case ECompatibilityProfile:
292 return spv::SourceLanguageGLSL;
293 case EEsProfile:
294 return spv::SourceLanguageESSL;
295 default:
296 return spv::SourceLanguageUnknown;
297 }
298 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600299 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600300 default:
301 return spv::SourceLanguageUnknown;
302 }
303}
304
305// Translate glslang language (stage) to SPIR-V execution model.
306spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
307{
308 switch (stage) {
309 case EShLangVertex: return spv::ExecutionModelVertex;
John Kessenicha28f7a72019-08-06 07:00:58 -0600310 case EShLangFragment: return spv::ExecutionModelFragment;
John Kessenicha28f7a72019-08-06 07:00:58 -0600311 case EShLangCompute: return spv::ExecutionModelGLCompute;
John Kessenich51ed01c2019-10-10 11:40:11 -0600312#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -0600313 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
314 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
315 case EShLangGeometry: return spv::ExecutionModelGeometry;
Daniel Kochdb32b242020-03-17 20:42:47 -0400316 case EShLangRayGen: return spv::ExecutionModelRayGenerationKHR;
317 case EShLangIntersect: return spv::ExecutionModelIntersectionKHR;
318 case EShLangAnyHit: return spv::ExecutionModelAnyHitKHR;
319 case EShLangClosestHit: return spv::ExecutionModelClosestHitKHR;
320 case EShLangMiss: return spv::ExecutionModelMissKHR;
321 case EShLangCallable: return spv::ExecutionModelCallableKHR;
Chao Chen3c366992018-09-19 11:41:59 -0700322 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
323 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
324#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600325 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700326 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600327 return spv::ExecutionModelFragment;
328 }
329}
330
John Kessenich140f3df2015-06-26 16:58:36 -0600331// Translate glslang sampler type to SPIR-V dimensionality.
332spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
333{
334 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700335 case glslang::Esd1D: return spv::Dim1D;
336 case glslang::Esd2D: return spv::Dim2D;
337 case glslang::Esd3D: return spv::Dim3D;
338 case glslang::EsdCube: return spv::DimCube;
339 case glslang::EsdRect: return spv::DimRect;
340 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700341 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600342 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700343 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600344 return spv::Dim2D;
345 }
346}
347
John Kessenichf6640762016-08-01 19:44:00 -0600348// Translate glslang precision to SPIR-V precision decorations.
349spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600350{
John Kessenichf6640762016-08-01 19:44:00 -0600351 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700352 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600353 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600354 default:
355 return spv::NoPrecision;
356 }
357}
358
John Kessenichf6640762016-08-01 19:44:00 -0600359// Translate glslang type to SPIR-V precision decorations.
360spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
361{
362 return TranslatePrecisionDecoration(type.getQualifier().precision);
363}
364
John Kessenich140f3df2015-06-26 16:58:36 -0600365// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600366spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600367{
368 if (type.getBasicType() == glslang::EbtBlock) {
369 switch (type.getQualifier().storage) {
370 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600371 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600372 case glslang::EvqVaryingIn: return spv::DecorationBlock;
373 case glslang::EvqVaryingOut: return spv::DecorationBlock;
John Kessenicha28f7a72019-08-06 07:00:58 -0600374#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -0400375 case glslang::EvqPayload: return spv::DecorationBlock;
376 case glslang::EvqPayloadIn: return spv::DecorationBlock;
377 case glslang::EvqHitAttr: return spv::DecorationBlock;
378 case glslang::EvqCallableData: return spv::DecorationBlock;
379 case glslang::EvqCallableDataIn: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700380#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600381 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700382 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600383 break;
384 }
385 }
386
John Kessenich4016e382016-07-15 11:53:56 -0600387 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600388}
389
Rex Xu1da878f2016-02-21 20:59:01 +0800390// Translate glslang type to SPIR-V memory decorations.
John Kessenich8985fc92020-03-03 10:25:07 -0700391void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory,
392 bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800393{
Jeff Bolz36831c92018-09-05 10:11:41 -0500394 if (!useVulkanMemoryModel) {
John Kessenichf8d1d742019-10-21 06:55:11 -0600395 if (qualifier.isCoherent())
Jeff Bolz36831c92018-09-05 10:11:41 -0500396 memory.push_back(spv::DecorationCoherent);
John Kessenichf8d1d742019-10-21 06:55:11 -0600397 if (qualifier.isVolatile()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500398 memory.push_back(spv::DecorationVolatile);
399 memory.push_back(spv::DecorationCoherent);
400 }
John Kessenich14b85d32018-06-04 15:36:03 -0600401 }
John Kessenichf8d1d742019-10-21 06:55:11 -0600402 if (qualifier.isRestrict())
Rex Xu1da878f2016-02-21 20:59:01 +0800403 memory.push_back(spv::DecorationRestrict);
John Kessenichdeec1932019-08-13 08:00:30 -0600404 if (qualifier.isReadOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800405 memory.push_back(spv::DecorationNonWritable);
John Kessenichdeec1932019-08-13 08:00:30 -0600406 if (qualifier.isWriteOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800407 memory.push_back(spv::DecorationNonReadable);
408}
409
John Kessenich140f3df2015-06-26 16:58:36 -0600410// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700411spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600412{
413 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700414 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600415 case glslang::ElmRowMajor:
416 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700417 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600418 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700419 default:
420 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600421 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600422 }
423 } else {
424 switch (type.getBasicType()) {
425 default:
John Kessenich4016e382016-07-15 11:53:56 -0600426 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600427 break;
428 case glslang::EbtBlock:
429 switch (type.getQualifier().storage) {
430 case glslang::EvqUniform:
431 case glslang::EvqBuffer:
432 switch (type.getQualifier().layoutPacking) {
433 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600434 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
435 default:
John Kessenich4016e382016-07-15 11:53:56 -0600436 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600437 }
438 case glslang::EvqVaryingIn:
439 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700440 if (type.getQualifier().isTaskMemory()) {
441 switch (type.getQualifier().layoutPacking) {
442 case glslang::ElpShared: return spv::DecorationGLSLShared;
443 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
444 default: break;
445 }
446 } else {
447 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
448 }
John Kessenich4016e382016-07-15 11:53:56 -0600449 return spv::DecorationMax;
John Kessenicha28f7a72019-08-06 07:00:58 -0600450#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -0400451 case glslang::EvqPayload:
452 case glslang::EvqPayloadIn:
453 case glslang::EvqHitAttr:
454 case glslang::EvqCallableData:
455 case glslang::EvqCallableDataIn:
Chao Chenb50c02e2018-09-19 11:42:24 -0700456 return spv::DecorationMax;
457#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600458 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700459 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600460 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600461 }
462 }
463 }
464}
465
466// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600467// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700468// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800469spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600470{
Rex Xubbceed72016-05-21 09:40:44 +0800471 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700472 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600473 return spv::DecorationMax;
John Kessenich7015bd62019-08-01 03:28:08 -0600474 else if (qualifier.isNonPerspective())
John Kessenich55e7d112015-11-15 21:33:39 -0700475 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700476 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600477 return spv::DecorationFlat;
John Kessenicha28f7a72019-08-06 07:00:58 -0600478 else if (qualifier.isExplicitInterpolation()) {
Rex Xu17ff3432016-10-14 17:41:45 +0800479 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800480 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800481 }
Rex Xubbceed72016-05-21 09:40:44 +0800482 else
John Kessenich4016e382016-07-15 11:53:56 -0600483 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800484}
485
486// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600487// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800488// should be applied.
489spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
490{
John Kessenichb9197c82019-08-11 07:41:45 -0600491 if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600492 return spv::DecorationCentroid;
John Kessenichb9197c82019-08-11 07:41:45 -0600493#ifndef GLSLANG_WEB
494 else if (qualifier.patch)
495 return spv::DecorationPatch;
John Kessenich5e801132016-02-15 11:09:46 -0700496 else if (qualifier.sample) {
497 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600498 return spv::DecorationSample;
John Kessenichb9197c82019-08-11 07:41:45 -0600499 }
500#endif
501
502 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600503}
504
John Kessenich92187592016-02-01 13:45:25 -0700505// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700506spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600507{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700508 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600509 return spv::DecorationInvariant;
510 else
John Kessenich4016e382016-07-15 11:53:56 -0600511 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600512}
513
qining9220dbb2016-05-04 17:34:38 -0400514// If glslang type is noContraction, return SPIR-V NoContraction decoration.
515spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
516{
John Kessenichb9197c82019-08-11 07:41:45 -0600517#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -0600518 if (qualifier.isNoContraction())
qining9220dbb2016-05-04 17:34:38 -0400519 return spv::DecorationNoContraction;
520 else
John Kessenichb9197c82019-08-11 07:41:45 -0600521#endif
John Kessenich4016e382016-07-15 11:53:56 -0600522 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400523}
524
John Kessenich5611c6d2018-04-05 11:25:02 -0600525// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
526spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
527{
John Kessenichb9197c82019-08-11 07:41:45 -0600528#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -0600529 if (qualifier.isNonUniform()) {
John Kessenich8317e6c2019-08-18 23:58:08 -0600530 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -0600531 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
532 return spv::DecorationNonUniformEXT;
533 } else
John Kessenichb9197c82019-08-11 07:41:45 -0600534#endif
John Kessenich5611c6d2018-04-05 11:25:02 -0600535 return spv::DecorationMax;
536}
537
John Kessenichb9197c82019-08-11 07:41:45 -0600538spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(
539 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500540{
Jeff Bolz36831c92018-09-05 10:11:41 -0500541 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600542
543#ifndef GLSLANG_WEB
544 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage)
545 return mask;
546
Daniel Kochdb32b242020-03-17 20:42:47 -0400547 if (coherentFlags.isVolatile() || coherentFlags.anyCoherent()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500548 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
549 spv::MemoryAccessMakePointerVisibleKHRMask;
550 }
Daniel Kochdb32b242020-03-17 20:42:47 -0400551
Jeff Bolz36831c92018-09-05 10:11:41 -0500552 if (coherentFlags.nonprivate) {
553 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
554 }
555 if (coherentFlags.volatil) {
556 mask = mask | spv::MemoryAccessVolatileMask;
557 }
558 if (mask != spv::MemoryAccessMaskNone) {
559 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
560 }
John Kessenichb9197c82019-08-11 07:41:45 -0600561#endif
562
Jeff Bolz36831c92018-09-05 10:11:41 -0500563 return mask;
564}
565
John Kessenichb9197c82019-08-11 07:41:45 -0600566spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(
567 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500568{
Jeff Bolz36831c92018-09-05 10:11:41 -0500569 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600570
571#ifndef GLSLANG_WEB
572 if (!glslangIntermediate->usingVulkanMemoryModel())
573 return mask;
574
Jeff Bolz36831c92018-09-05 10:11:41 -0500575 if (coherentFlags.volatil ||
Daniel Kochdb32b242020-03-17 20:42:47 -0400576 coherentFlags.anyCoherent()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500577 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
578 spv::ImageOperandsMakeTexelVisibleKHRMask;
579 }
580 if (coherentFlags.nonprivate) {
581 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
582 }
583 if (coherentFlags.volatil) {
584 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
585 }
586 if (mask != spv::ImageOperandsMaskNone) {
587 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
588 }
John Kessenichb9197c82019-08-11 07:41:45 -0600589#endif
590
Jeff Bolz36831c92018-09-05 10:11:41 -0500591 return mask;
592}
593
594spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
595{
John Kessenichb9197c82019-08-11 07:41:45 -0600596 spv::Builder::AccessChain::CoherentFlags flags = {};
597#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -0500598 flags.coherent = type.getQualifier().coherent;
599 flags.devicecoherent = type.getQualifier().devicecoherent;
600 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
601 // shared variables are implicitly workgroupcoherent in GLSL.
602 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
603 type.getQualifier().storage == glslang::EvqShared;
604 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Daniel Kochdb32b242020-03-17 20:42:47 -0400605 flags.shadercallcoherent = type.getQualifier().shadercallcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600606 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500607 // *coherent variables are implicitly nonprivate in GLSL
608 flags.nonprivate = type.getQualifier().nonprivate ||
Daniel Kochdb32b242020-03-17 20:42:47 -0400609 flags.anyCoherent() ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600610 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500611 flags.isImage = type.getBasicType() == glslang::EbtSampler;
John Kessenichb9197c82019-08-11 07:41:45 -0600612#endif
Jeff Bolz36831c92018-09-05 10:11:41 -0500613 return flags;
614}
615
John Kessenichb9197c82019-08-11 07:41:45 -0600616spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(
617 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500618{
John Kessenichb9197c82019-08-11 07:41:45 -0600619 spv::Scope scope = spv::ScopeMax;
620
621#ifndef GLSLANG_WEB
Jeff Bolz38cbad12019-03-05 14:40:07 -0600622 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500623 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
624 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
625 } else if (coherentFlags.devicecoherent) {
626 scope = spv::ScopeDevice;
627 } else if (coherentFlags.queuefamilycoherent) {
628 scope = spv::ScopeQueueFamilyKHR;
629 } else if (coherentFlags.workgroupcoherent) {
630 scope = spv::ScopeWorkgroup;
631 } else if (coherentFlags.subgroupcoherent) {
632 scope = spv::ScopeSubgroup;
Daniel Kochdb32b242020-03-17 20:42:47 -0400633 } else if (coherentFlags.shadercallcoherent) {
634 scope = spv::ScopeShaderCallKHR;
Jeff Bolz36831c92018-09-05 10:11:41 -0500635 }
636 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
637 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
638 }
John Kessenichb9197c82019-08-11 07:41:45 -0600639#endif
640
Jeff Bolz36831c92018-09-05 10:11:41 -0500641 return scope;
642}
643
David Netoa901ffe2016-06-08 14:11:40 +0100644// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
645// associated capabilities when required. For some built-in variables, a capability
646// is generated only when using the variable in an executable instruction, but not when
647// just declaring a struct member variable with it. This is true for PointSize,
648// ClipDistance, and CullDistance.
John Kessenich8985fc92020-03-03 10:25:07 -0700649spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn,
650 bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600651{
652 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700653 case glslang::EbvPointSize:
John Kessenich155d3512019-08-08 23:29:20 -0600654#ifndef GLSLANG_WEB
John Kessenich78a45572016-07-08 14:05:15 -0600655 // Defer adding the capability until the built-in is actually used.
656 if (! memberDeclaration) {
657 switch (glslangIntermediate->getStage()) {
658 case EShLangGeometry:
659 builder.addCapability(spv::CapabilityGeometryPointSize);
660 break;
661 case EShLangTessControl:
662 case EShLangTessEvaluation:
663 builder.addCapability(spv::CapabilityTessellationPointSize);
664 break;
665 default:
666 break;
667 }
John Kessenich92187592016-02-01 13:45:25 -0700668 }
John Kessenich155d3512019-08-08 23:29:20 -0600669#endif
John Kessenich92187592016-02-01 13:45:25 -0700670 return spv::BuiltInPointSize;
671
John Kessenicha28f7a72019-08-06 07:00:58 -0600672 case glslang::EbvPosition: return spv::BuiltInPosition;
673 case glslang::EbvVertexId: return spv::BuiltInVertexId;
674 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
675 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
676 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
677
678 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
679 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
680 case glslang::EbvFace: return spv::BuiltInFrontFacing;
681 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
682
John Kessenich3dd1ce52019-10-17 07:08:40 -0600683 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
684 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
685 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
686 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
687 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
688 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
689
John Kessenicha28f7a72019-08-06 07:00:58 -0600690#ifndef GLSLANG_WEB
John Kessenichebb50532016-05-16 19:22:05 -0600691 // These *Distance capabilities logically belong here, but if the member is declared and
692 // then never used, consumers of SPIR-V prefer the capability not be declared.
693 // They are now generated when used, rather than here when declared.
694 // Potentially, the specification should be more clear what the minimum
695 // use needed is to trigger the capability.
696 //
John Kessenich92187592016-02-01 13:45:25 -0700697 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100698 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800699 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700700 return spv::BuiltInClipDistance;
701
702 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100703 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800704 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700705 return spv::BuiltInCullDistance;
706
707 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600708 builder.addCapability(spv::CapabilityMultiViewport);
709 if (glslangIntermediate->getStage() == EShLangVertex ||
710 glslangIntermediate->getStage() == EShLangTessControl ||
711 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800712
John Kessenich8317e6c2019-08-18 23:58:08 -0600713 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600714 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800715 }
John Kessenich92187592016-02-01 13:45:25 -0700716 return spv::BuiltInViewportIndex;
717
John Kessenich5e801132016-02-15 11:09:46 -0700718 case glslang::EbvSampleId:
719 builder.addCapability(spv::CapabilitySampleRateShading);
720 return spv::BuiltInSampleId;
721
722 case glslang::EbvSamplePosition:
723 builder.addCapability(spv::CapabilitySampleRateShading);
724 return spv::BuiltInSamplePosition;
725
726 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700727 return spv::BuiltInSampleMask;
728
John Kessenich78a45572016-07-08 14:05:15 -0600729 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700730 if (glslangIntermediate->getStage() == EShLangMeshNV) {
731 return spv::BuiltInLayer;
732 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600733 builder.addCapability(spv::CapabilityGeometry);
734 if (glslangIntermediate->getStage() == EShLangVertex ||
735 glslangIntermediate->getStage() == EShLangTessControl ||
736 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800737
John Kessenich8317e6c2019-08-18 23:58:08 -0600738 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600739 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800740 }
John Kessenich78a45572016-07-08 14:05:15 -0600741 return spv::BuiltInLayer;
742
John Kessenichda581a22015-10-14 14:10:30 -0600743 case glslang::EbvBaseVertex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600744 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800745 builder.addCapability(spv::CapabilityDrawParameters);
746 return spv::BuiltInBaseVertex;
747
John Kessenichda581a22015-10-14 14:10:30 -0600748 case glslang::EbvBaseInstance:
John Kessenich8317e6c2019-08-18 23:58:08 -0600749 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800750 builder.addCapability(spv::CapabilityDrawParameters);
751 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200752
John Kessenichda581a22015-10-14 14:10:30 -0600753 case glslang::EbvDrawId:
John Kessenich8317e6c2019-08-18 23:58:08 -0600754 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800755 builder.addCapability(spv::CapabilityDrawParameters);
756 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200757
758 case glslang::EbvPrimitiveId:
759 if (glslangIntermediate->getStage() == EShLangFragment)
760 builder.addCapability(spv::CapabilityGeometry);
761 return spv::BuiltInPrimitiveId;
762
Rex Xu37cdcee2017-06-29 17:46:34 +0800763 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800764 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
765 builder.addCapability(spv::CapabilityStencilExportEXT);
766 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800767
John Kessenich140f3df2015-06-26 16:58:36 -0600768 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600769 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
770 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
771 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
772 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
John Kessenich140f3df2015-06-26 16:58:36 -0600773 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
Rex Xu51596642016-09-21 18:56:12 +0800774
Rex Xu574ab042016-04-14 16:53:07 +0800775 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800776 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800777 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
778 return spv::BuiltInSubgroupSize;
779
Rex Xu574ab042016-04-14 16:53:07 +0800780 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800781 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800782 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
783 return spv::BuiltInSubgroupLocalInvocationId;
784
Rex Xu574ab042016-04-14 16:53:07 +0800785 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800786 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
787 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600788 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800789
Rex Xu574ab042016-04-14 16:53:07 +0800790 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800791 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
792 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600793 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800794
Rex Xu574ab042016-04-14 16:53:07 +0800795 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800796 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
797 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600798 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800799
Rex Xu574ab042016-04-14 16:53:07 +0800800 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800801 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
802 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600803 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800804
Rex Xu574ab042016-04-14 16:53:07 +0800805 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800806 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
807 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600808 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800809
John Kessenich66011cb2018-03-06 16:12:04 -0700810 case glslang::EbvNumSubgroups:
811 builder.addCapability(spv::CapabilityGroupNonUniform);
812 return spv::BuiltInNumSubgroups;
813
814 case glslang::EbvSubgroupID:
815 builder.addCapability(spv::CapabilityGroupNonUniform);
816 return spv::BuiltInSubgroupId;
817
818 case glslang::EbvSubgroupSize2:
819 builder.addCapability(spv::CapabilityGroupNonUniform);
820 return spv::BuiltInSubgroupSize;
821
822 case glslang::EbvSubgroupInvocation2:
823 builder.addCapability(spv::CapabilityGroupNonUniform);
824 return spv::BuiltInSubgroupLocalInvocationId;
825
826 case glslang::EbvSubgroupEqMask2:
827 builder.addCapability(spv::CapabilityGroupNonUniform);
828 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
829 return spv::BuiltInSubgroupEqMask;
830
831 case glslang::EbvSubgroupGeMask2:
832 builder.addCapability(spv::CapabilityGroupNonUniform);
833 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
834 return spv::BuiltInSubgroupGeMask;
835
836 case glslang::EbvSubgroupGtMask2:
837 builder.addCapability(spv::CapabilityGroupNonUniform);
838 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
839 return spv::BuiltInSubgroupGtMask;
840
841 case glslang::EbvSubgroupLeMask2:
842 builder.addCapability(spv::CapabilityGroupNonUniform);
843 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
844 return spv::BuiltInSubgroupLeMask;
845
846 case glslang::EbvSubgroupLtMask2:
847 builder.addCapability(spv::CapabilityGroupNonUniform);
848 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
849 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600850
Rex Xu17ff3432016-10-14 17:41:45 +0800851 case glslang::EbvBaryCoordNoPersp:
852 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
853 return spv::BuiltInBaryCoordNoPerspAMD;
854
855 case glslang::EbvBaryCoordNoPerspCentroid:
856 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
857 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
858
859 case glslang::EbvBaryCoordNoPerspSample:
860 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
861 return spv::BuiltInBaryCoordNoPerspSampleAMD;
862
863 case glslang::EbvBaryCoordSmooth:
864 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
865 return spv::BuiltInBaryCoordSmoothAMD;
866
867 case glslang::EbvBaryCoordSmoothCentroid:
868 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
869 return spv::BuiltInBaryCoordSmoothCentroidAMD;
870
871 case glslang::EbvBaryCoordSmoothSample:
872 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
873 return spv::BuiltInBaryCoordSmoothSampleAMD;
874
875 case glslang::EbvBaryCoordPullModel:
876 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
877 return spv::BuiltInBaryCoordPullModelAMD;
chaoc771d89f2017-01-13 01:10:53 -0800878
John Kessenich6c8aaac2017-02-27 01:20:51 -0700879 case glslang::EbvDeviceIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600880 builder.addIncorporatedExtension(spv::E_SPV_KHR_device_group, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700881 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700882 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700883
884 case glslang::EbvViewIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600885 builder.addIncorporatedExtension(spv::E_SPV_KHR_multiview, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700886 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700887 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700888
Daniel Koch5154db52018-11-26 10:01:58 -0500889 case glslang::EbvFragSizeEXT:
890 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
891 builder.addCapability(spv::CapabilityFragmentDensityEXT);
892 return spv::BuiltInFragSizeEXT;
893
894 case glslang::EbvFragInvocationCountEXT:
895 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
896 builder.addCapability(spv::CapabilityFragmentDensityEXT);
897 return spv::BuiltInFragInvocationCountEXT;
898
chaoc771d89f2017-01-13 01:10:53 -0800899 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800900 if (!memberDeclaration) {
901 builder.addExtension(spv::E_SPV_NV_viewport_array2);
902 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
903 }
chaoc771d89f2017-01-13 01:10:53 -0800904 return spv::BuiltInViewportMaskNV;
905 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800906 if (!memberDeclaration) {
907 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
908 builder.addCapability(spv::CapabilityShaderStereoViewNV);
909 }
chaoc771d89f2017-01-13 01:10:53 -0800910 return spv::BuiltInSecondaryPositionNV;
911 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800912 if (!memberDeclaration) {
913 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
914 builder.addCapability(spv::CapabilityShaderStereoViewNV);
915 }
chaoc771d89f2017-01-13 01:10:53 -0800916 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800917 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800918 if (!memberDeclaration) {
919 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
920 builder.addCapability(spv::CapabilityPerViewAttributesNV);
921 }
chaocdf3956c2017-02-14 14:52:34 -0800922 return spv::BuiltInPositionPerViewNV;
923 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800924 if (!memberDeclaration) {
925 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
926 builder.addCapability(spv::CapabilityPerViewAttributesNV);
927 }
chaocdf3956c2017-02-14 14:52:34 -0800928 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700929 case glslang::EbvFragFullyCoveredNV:
930 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
931 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
932 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700933 case glslang::EbvFragmentSizeNV:
934 builder.addExtension(spv::E_SPV_NV_shading_rate);
935 builder.addCapability(spv::CapabilityShadingRateNV);
936 return spv::BuiltInFragmentSizeNV;
937 case glslang::EbvInvocationsPerPixelNV:
938 builder.addExtension(spv::E_SPV_NV_shading_rate);
939 builder.addCapability(spv::CapabilityShadingRateNV);
940 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700941
Daniel Koch593a4e02019-05-27 16:46:31 -0400942 // ray tracing
Daniel Kochdb32b242020-03-17 20:42:47 -0400943 case glslang::EbvLaunchId:
944 return spv::BuiltInLaunchIdKHR;
945 case glslang::EbvLaunchSize:
946 return spv::BuiltInLaunchSizeKHR;
947 case glslang::EbvWorldRayOrigin:
948 return spv::BuiltInWorldRayOriginKHR;
949 case glslang::EbvWorldRayDirection:
950 return spv::BuiltInWorldRayDirectionKHR;
951 case glslang::EbvObjectRayOrigin:
952 return spv::BuiltInObjectRayOriginKHR;
953 case glslang::EbvObjectRayDirection:
954 return spv::BuiltInObjectRayDirectionKHR;
955 case glslang::EbvRayTmin:
956 return spv::BuiltInRayTminKHR;
957 case glslang::EbvRayTmax:
958 return spv::BuiltInRayTmaxKHR;
959 case glslang::EbvInstanceCustomIndex:
960 return spv::BuiltInInstanceCustomIndexKHR;
961 case glslang::EbvHitT:
962 return spv::BuiltInHitTKHR;
963 case glslang::EbvHitKind:
964 return spv::BuiltInHitKindKHR;
965 case glslang::EbvObjectToWorld:
966 case glslang::EbvObjectToWorld3x4:
967 return spv::BuiltInObjectToWorldKHR;
968 case glslang::EbvWorldToObject:
969 case glslang::EbvWorldToObject3x4:
970 return spv::BuiltInWorldToObjectKHR;
971 case glslang::EbvIncomingRayFlags:
972 return spv::BuiltInIncomingRayFlagsKHR;
973 case glslang::EbvGeometryIndex:
974 return spv::BuiltInRayGeometryIndexKHR;
Daniel Koch593a4e02019-05-27 16:46:31 -0400975
976 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700977 case glslang::EbvBaryCoordNV:
978 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
979 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
980 return spv::BuiltInBaryCoordNV;
981 case glslang::EbvBaryCoordNoPerspNV:
982 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
983 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
984 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400985
986 // mesh shaders
987 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700988 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400989 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700990 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400991 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700992 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400993 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700994 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400995 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700996 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400997 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700998 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400999 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001000 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001001 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -07001002 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch2cb2f192019-06-04 08:43:32 -04001003
1004 // sm builtins
1005 case glslang::EbvWarpsPerSM:
1006 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1007 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1008 return spv::BuiltInWarpsPerSMNV;
1009 case glslang::EbvSMCount:
1010 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1011 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1012 return spv::BuiltInSMCountNV;
1013 case glslang::EbvWarpID:
1014 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1015 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1016 return spv::BuiltInWarpIDNV;
1017 case glslang::EbvSMID:
1018 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1019 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1020 return spv::BuiltInSMIDNV;
John Kessenicha28f7a72019-08-06 07:00:58 -06001021#endif
1022
Rex Xu3e783f92017-02-22 16:44:48 +08001023 default:
1024 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -06001025 }
1026}
1027
Rex Xufc618912015-09-09 16:42:49 +08001028// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -07001029spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +08001030{
1031 assert(type.getBasicType() == glslang::EbtSampler);
1032
John Kessenichb9197c82019-08-11 07:41:45 -06001033#ifdef GLSLANG_WEB
1034 return spv::ImageFormatUnknown;
1035#endif
1036
John Kessenich5d0fa972016-02-15 11:57:00 -07001037 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -06001038 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -07001039 case glslang::ElfRg32f:
1040 case glslang::ElfRg16f:
1041 case glslang::ElfR11fG11fB10f:
1042 case glslang::ElfR16f:
1043 case glslang::ElfRgba16:
1044 case glslang::ElfRgb10A2:
1045 case glslang::ElfRg16:
1046 case glslang::ElfRg8:
1047 case glslang::ElfR16:
1048 case glslang::ElfR8:
1049 case glslang::ElfRgba16Snorm:
1050 case glslang::ElfRg16Snorm:
1051 case glslang::ElfRg8Snorm:
1052 case glslang::ElfR16Snorm:
1053 case glslang::ElfR8Snorm:
1054
1055 case glslang::ElfRg32i:
1056 case glslang::ElfRg16i:
1057 case glslang::ElfRg8i:
1058 case glslang::ElfR16i:
1059 case glslang::ElfR8i:
1060
1061 case glslang::ElfRgb10a2ui:
1062 case glslang::ElfRg32ui:
1063 case glslang::ElfRg16ui:
1064 case glslang::ElfRg8ui:
1065 case glslang::ElfR16ui:
1066 case glslang::ElfR8ui:
1067 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1068 break;
1069
1070 default:
1071 break;
1072 }
1073
1074 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001075 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001076 case glslang::ElfNone: return spv::ImageFormatUnknown;
1077 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1078 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1079 case glslang::ElfR32f: return spv::ImageFormatR32f;
1080 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1081 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1082 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1083 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1084 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1085 case glslang::ElfR16f: return spv::ImageFormatR16f;
1086 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1087 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1088 case glslang::ElfRg16: return spv::ImageFormatRg16;
1089 case glslang::ElfRg8: return spv::ImageFormatRg8;
1090 case glslang::ElfR16: return spv::ImageFormatR16;
1091 case glslang::ElfR8: return spv::ImageFormatR8;
1092 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1093 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1094 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1095 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1096 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1097 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1098 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1099 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1100 case glslang::ElfR32i: return spv::ImageFormatR32i;
1101 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1102 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1103 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1104 case glslang::ElfR16i: return spv::ImageFormatR16i;
1105 case glslang::ElfR8i: return spv::ImageFormatR8i;
1106 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1107 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1108 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1109 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1110 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1111 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1112 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1113 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1114 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1115 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001116 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001117 }
1118}
1119
John Kessenich8985fc92020-03-03 10:25:07 -07001120spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(
1121 const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001122{
John Kesseniche18fd202018-01-30 11:01:39 -07001123 if (selectionNode.getFlatten())
1124 return spv::SelectionControlFlattenMask;
1125 if (selectionNode.getDontFlatten())
1126 return spv::SelectionControlDontFlattenMask;
1127 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001128}
1129
John Kessenich8985fc92020-03-03 10:25:07 -07001130spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode)
1131 const
steve-lunargf1709e72017-05-02 20:14:50 -06001132{
John Kesseniche18fd202018-01-30 11:01:39 -07001133 if (switchNode.getFlatten())
1134 return spv::SelectionControlFlattenMask;
1135 if (switchNode.getDontFlatten())
1136 return spv::SelectionControlDontFlattenMask;
1137 return spv::SelectionControlMaskNone;
1138}
1139
John Kessenicha2858d92018-01-31 08:11:18 -07001140// return a non-0 dependency if the dependency argument must be set
1141spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001142 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001143{
1144 spv::LoopControlMask control = spv::LoopControlMaskNone;
1145
1146 if (loopNode.getDontUnroll())
1147 control = control | spv::LoopControlDontUnrollMask;
1148 if (loopNode.getUnroll())
1149 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001150 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001151 control = control | spv::LoopControlDependencyInfiniteMask;
1152 else if (loopNode.getLoopDependency() > 0) {
1153 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001154 operands.push_back((unsigned int)loopNode.getLoopDependency());
1155 }
1156 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1157 if (loopNode.getMinIterations() > 0) {
1158 control = control | spv::LoopControlMinIterationsMask;
1159 operands.push_back(loopNode.getMinIterations());
1160 }
1161 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1162 control = control | spv::LoopControlMaxIterationsMask;
1163 operands.push_back(loopNode.getMaxIterations());
1164 }
1165 if (loopNode.getIterationMultiple() > 1) {
1166 control = control | spv::LoopControlIterationMultipleMask;
1167 operands.push_back(loopNode.getIterationMultiple());
1168 }
1169 if (loopNode.getPeelCount() > 0) {
1170 control = control | spv::LoopControlPeelCountMask;
1171 operands.push_back(loopNode.getPeelCount());
1172 }
1173 if (loopNode.getPartialCount() > 0) {
1174 control = control | spv::LoopControlPartialCountMask;
1175 operands.push_back(loopNode.getPartialCount());
1176 }
John Kessenicha2858d92018-01-31 08:11:18 -07001177 }
John Kesseniche18fd202018-01-30 11:01:39 -07001178
1179 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001180}
1181
John Kessenicha5c5fb62017-05-05 05:09:58 -06001182// Translate glslang type to SPIR-V storage class.
1183spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1184{
Torosdagli06c2eee2020-03-19 11:09:57 -04001185 if (type.getBasicType() == glslang::EbtRayQuery)
Neslisah Torosdagli054b5e32020-03-26 12:24:31 -04001186 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001187 if (type.getQualifier().isPipeInput())
1188 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001189 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001190 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001191
1192 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001193 type.getQualifier().storage == glslang::EvqUniform) {
John Kessenichdeec1932019-08-13 08:00:30 -06001194 if (type.isAtomic())
John Kessenichbed4e4f2017-09-08 02:38:07 -06001195 return spv::StorageClassAtomicCounter;
1196 if (type.containsOpaque())
1197 return spv::StorageClassUniformConstant;
1198 }
1199
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001200 if (type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001201 type.getQualifier().isShaderRecord()) {
1202 return spv::StorageClassShaderRecordBufferKHR;
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001203 }
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001204
John Kessenichbed4e4f2017-09-08 02:38:07 -06001205 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001206 builder.addIncorporatedExtension(spv::E_SPV_KHR_storage_buffer_storage_class, spv::Spv_1_3);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001207 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001208 }
1209
1210 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich7015bd62019-08-01 03:28:08 -06001211 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001212 return spv::StorageClassPushConstant;
1213 if (type.getBasicType() == glslang::EbtBlock)
1214 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001215 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001216 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001217
1218 switch (type.getQualifier().storage) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001219 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1220 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1221 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenichdeec1932019-08-13 08:00:30 -06001222 case glslang::EvqShared: return spv::StorageClassWorkgroup;
John Kessenich3dd1ce52019-10-17 07:08:40 -06001223#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -04001224 case glslang::EvqPayload: return spv::StorageClassRayPayloadKHR;
1225 case glslang::EvqPayloadIn: return spv::StorageClassIncomingRayPayloadKHR;
1226 case glslang::EvqHitAttr: return spv::StorageClassHitAttributeKHR;
1227 case glslang::EvqCallableData: return spv::StorageClassCallableDataKHR;
1228 case glslang::EvqCallableDataIn: return spv::StorageClassIncomingCallableDataKHR;
Chao Chenb50c02e2018-09-19 11:42:24 -07001229#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001230 default:
1231 assert(0);
1232 break;
1233 }
1234
1235 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001236}
1237
John Kessenich5611c6d2018-04-05 11:25:02 -06001238// Add capabilities pertaining to how an array is indexed.
1239void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1240 const glslang::TType& indexType)
1241{
John Kessenichb9197c82019-08-11 07:41:45 -06001242#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06001243 if (indexType.getQualifier().isNonUniform()) {
1244 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001245 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001246 if (baseType.getBasicType() == glslang::EbtSampler) {
1247 if (baseType.getQualifier().hasAttachment())
1248 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001249 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001250 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001251 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001252 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1253 else if (baseType.isImage())
1254 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1255 else if (baseType.isTexture())
1256 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1257 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1258 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1259 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1260 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1261 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1262 }
1263 } else {
1264 // assume a dynamically uniform index
1265 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001266 if (baseType.getQualifier().hasAttachment()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001267 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001268 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001269 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001270 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001271 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001272 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001273 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001274 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001275 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001276 }
1277 }
John Kessenichb9197c82019-08-11 07:41:45 -06001278#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06001279}
1280
qining25262b32016-05-06 17:25:16 -04001281// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001282// descriptor set.
1283bool IsDescriptorResource(const glslang::TType& type)
1284{
John Kessenichf7497e22016-03-08 21:36:22 -07001285 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001286 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001287 return type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001288 ! type.getQualifier().isShaderRecord() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001289 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001290
1291 // non block...
1292 // basically samplerXXX/subpass/sampler/texture are all included
1293 // if they are the global-scope-class, not the function parameter
1294 // (or local, if they ever exist) class.
alelenv999d4fd2020-06-01 23:24:41 -07001295 if (type.getBasicType() == glslang::EbtSampler ||
1296 type.getBasicType() == glslang::EbtAccStruct)
John Kessenich6c292d32016-02-15 20:58:50 -07001297 return type.getQualifier().isUniformOrBuffer();
1298
1299 // None of the above.
1300 return false;
1301}
1302
John Kesseniche0b6cad2015-12-24 10:30:13 -07001303void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1304{
1305 if (child.layoutMatrix == glslang::ElmNone)
1306 child.layoutMatrix = parent.layoutMatrix;
1307
1308 if (parent.invariant)
1309 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001310 if (parent.flat)
1311 child.flat = true;
1312 if (parent.centroid)
1313 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001314#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001315 if (parent.nopersp)
1316 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001317 if (parent.explicitInterp)
1318 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001319 if (parent.perPrimitiveNV)
1320 child.perPrimitiveNV = true;
1321 if (parent.perViewNV)
1322 child.perViewNV = true;
1323 if (parent.perTaskNV)
1324 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001325 if (parent.patch)
1326 child.patch = true;
1327 if (parent.sample)
1328 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001329 if (parent.coherent)
1330 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001331 if (parent.devicecoherent)
1332 child.devicecoherent = true;
1333 if (parent.queuefamilycoherent)
1334 child.queuefamilycoherent = true;
1335 if (parent.workgroupcoherent)
1336 child.workgroupcoherent = true;
1337 if (parent.subgroupcoherent)
1338 child.subgroupcoherent = true;
Daniel Kochdb32b242020-03-17 20:42:47 -04001339 if (parent.shadercallcoherent)
1340 child.shadercallcoherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001341 if (parent.nonprivate)
1342 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001343 if (parent.volatil)
1344 child.volatil = true;
1345 if (parent.restrict)
1346 child.restrict = true;
1347 if (parent.readonly)
1348 child.readonly = true;
1349 if (parent.writeonly)
1350 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001351#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001352}
1353
John Kessenichf2b7f332016-09-01 17:05:23 -06001354bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001355{
John Kessenich7b9fa252016-01-21 18:56:57 -07001356 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001357 // - struct members might inherit from a struct declaration
1358 // (note that non-block structs don't explicitly inherit,
1359 // only implicitly, meaning no decoration involved)
1360 // - affect decorations on the struct members
1361 // (note smooth does not, and expecting something like volatile
1362 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001363 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001364 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001365}
1366
John Kessenich140f3df2015-06-26 16:58:36 -06001367//
1368// Implement the TGlslangToSpvTraverser class.
1369//
1370
John Kessenich8985fc92020-03-03 10:25:07 -07001371TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion,
1372 const glslang::TIntermediate* glslangIntermediate,
1373 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options) :
1374 TIntermTraverser(true, false, true),
1375 options(options),
1376 shaderEntry(nullptr), currentFunction(nullptr),
1377 sequenceDepth(0), logger(buildLogger),
1378 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
1379 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
1380 glslangIntermediate(glslangIntermediate),
Jeff Bolz04d73732019-05-31 13:06:01 -05001381 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp()),
1382 nonSemanticDebugPrintf(0)
John Kessenich140f3df2015-06-26 16:58:36 -06001383{
1384 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1385
1386 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001387 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1388 glslangIntermediate->getVersion());
1389
John Kessenich121853f2017-05-31 17:11:16 -06001390 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001391 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001392 builder.setSourceFile(glslangIntermediate->getSourceFile());
1393
1394 // Set the source shader's text. If for SPV version 1.0, include
1395 // a preamble in comments stating the OpModuleProcessed instructions.
1396 // Otherwise, emit those as actual instructions.
1397 std::string text;
1398 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1399 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001400 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001401 text.append("// OpModuleProcessed ");
1402 text.append(processes[p]);
1403 text.append("\n");
1404 } else
1405 builder.addModuleProcessed(processes[p]);
1406 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001407 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001408 text.append("#line 1\n");
1409 text.append(glslangIntermediate->getSourceText());
1410 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001411 // Pass name and text for all included files
1412 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1413 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1414 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001415 }
John Kessenich140f3df2015-06-26 16:58:36 -06001416 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001417
1418 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1419 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1420
1421 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1422 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
John Kessenich1ff0c182019-10-10 12:01:13 -06001423 builder.addIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001424 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
John Kessenich8985fc92020-03-03 10:25:07 -07001425 }
Jeff Bolz36831c92018-09-05 10:11:41 -05001426 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001427 memoryModel = spv::MemoryModelVulkanKHR;
1428 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001429 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001430 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001431 builder.setMemoryModel(addressingModel, memoryModel);
1432
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001433 if (glslangIntermediate->usingVariablePointers()) {
1434 builder.addCapability(spv::CapabilityVariablePointers);
1435 }
1436
John Kessenicheee9d532016-09-19 18:09:30 -06001437 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1438 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001439
1440 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001441 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1442 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
Pankaj Mistry2a8ead22020-04-26 17:52:31 -07001443 builder.addSourceExtension(it->first.c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001444
1445 // Add the top-level modes for this shader.
1446
John Kessenich92187592016-02-01 13:45:25 -07001447 if (glslangIntermediate->getXfbMode()) {
1448 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001449 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001450 }
John Kessenich140f3df2015-06-26 16:58:36 -06001451
alelenv59216d52020-05-21 04:38:41 -07001452 if (glslangIntermediate->getLayoutPrimitiveCulling()) {
alelenv75de1962020-04-08 21:09:20 -07001453 builder.addCapability(spv::CapabilityRayTraversalPrimitiveCullingProvisionalKHR);
1454 }
1455
John Kessenich140f3df2015-06-26 16:58:36 -06001456 unsigned int mode;
1457 switch (glslangIntermediate->getStage()) {
1458 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001459 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001460 break;
1461
John Kessenicha28f7a72019-08-06 07:00:58 -06001462 case EShLangFragment:
1463 builder.addCapability(spv::CapabilityShader);
1464 if (glslangIntermediate->getPixelCenterInteger())
1465 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1466
1467 if (glslangIntermediate->getOriginUpperLeft())
1468 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1469 else
1470 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1471
1472 if (glslangIntermediate->getEarlyFragmentTests())
1473 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1474
1475 if (glslangIntermediate->getPostDepthCoverage()) {
1476 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1477 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1478 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1479 }
1480
John Kessenichb9197c82019-08-11 07:41:45 -06001481 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1482 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1483
1484#ifndef GLSLANG_WEB
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001485
John Kessenicha28f7a72019-08-06 07:00:58 -06001486 switch(glslangIntermediate->getDepth()) {
1487 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1488 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1489 default: mode = spv::ExecutionModeMax; break;
1490 }
1491 if (mode != spv::ExecutionModeMax)
1492 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001493 switch (glslangIntermediate->getInterlockOrdering()) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001494 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT;
1495 break;
1496 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT;
1497 break;
1498 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT;
1499 break;
1500 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT;
1501 break;
1502 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT;
1503 break;
1504 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT;
1505 break;
1506 default: mode = spv::ExecutionModeMax;
1507 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001508 }
1509 if (mode != spv::ExecutionModeMax) {
1510 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1511 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1512 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1513 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1514 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1515 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1516 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1517 } else {
1518 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1519 }
1520 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1521 }
John Kessenichb9197c82019-08-11 07:41:45 -06001522#endif
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001523 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001524
John Kessenicha28f7a72019-08-06 07:00:58 -06001525 case EShLangCompute:
1526 builder.addCapability(spv::CapabilityShader);
1527 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1528 glslangIntermediate->getLocalSize(1),
1529 glslangIntermediate->getLocalSize(2));
1530 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1531 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1532 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1533 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1534 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1535 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1536 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1537 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1538 }
1539 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001540#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001541 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001542 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001543 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001544
steve-lunarge7412492017-03-23 11:56:07 -06001545 glslang::TLayoutGeometry primitive;
1546
1547 if (glslangIntermediate->getStage() == EShLangTessControl) {
John Kessenich8985fc92020-03-03 10:25:07 -07001548 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1549 glslangIntermediate->getVertices());
steve-lunarge7412492017-03-23 11:56:07 -06001550 primitive = glslangIntermediate->getOutputPrimitive();
1551 } else {
1552 primitive = glslangIntermediate->getInputPrimitive();
1553 }
1554
1555 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001556 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1557 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1558 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001559 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001560 }
John Kessenich4016e382016-07-15 11:53:56 -06001561 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001562 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1563
John Kesseniche6903322015-10-13 16:29:02 -06001564 switch (glslangIntermediate->getVertexSpacing()) {
1565 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1566 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1567 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001568 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001569 }
John Kessenich4016e382016-07-15 11:53:56 -06001570 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001571 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1572
1573 switch (glslangIntermediate->getVertexOrder()) {
1574 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1575 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001576 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001577 }
John Kessenich4016e382016-07-15 11:53:56 -06001578 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001579 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1580
1581 if (glslangIntermediate->getPointMode())
1582 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001583 break;
1584
1585 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001586 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001587 switch (glslangIntermediate->getInputPrimitive()) {
1588 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1589 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1590 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001591 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001592 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001593 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001594 }
John Kessenich4016e382016-07-15 11:53:56 -06001595 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001596 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001597
John Kessenich140f3df2015-06-26 16:58:36 -06001598 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1599
1600 switch (glslangIntermediate->getOutputPrimitive()) {
1601 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1602 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1603 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001604 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001605 }
John Kessenich4016e382016-07-15 11:53:56 -06001606 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001607 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1608 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1609 break;
1610
Daniel Kochdb32b242020-03-17 20:42:47 -04001611 case EShLangRayGen:
1612 case EShLangIntersect:
1613 case EShLangAnyHit:
1614 case EShLangClosestHit:
1615 case EShLangMiss:
1616 case EShLangCallable:
1617 {
1618 auto& extensions = glslangIntermediate->getRequestedExtensions();
1619 if (extensions.find("GL_NV_ray_tracing") == extensions.end()) {
1620 builder.addCapability(spv::CapabilityRayTracingProvisionalKHR);
1621 builder.addExtension("SPV_KHR_ray_tracing");
1622 }
1623 else {
1624 builder.addCapability(spv::CapabilityRayTracingNV);
1625 builder.addExtension("SPV_NV_ray_tracing");
1626 }
Chao Chenb50c02e2018-09-19 11:42:24 -07001627 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04001628 }
Chao Chen3c366992018-09-19 11:41:59 -07001629 case EShLangTaskNV:
1630 case EShLangMeshNV:
1631 builder.addCapability(spv::CapabilityMeshShadingNV);
1632 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1633 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1634 glslangIntermediate->getLocalSize(1),
1635 glslangIntermediate->getLocalSize(2));
1636 if (glslangIntermediate->getStage() == EShLangMeshNV) {
John Kessenich8985fc92020-03-03 10:25:07 -07001637 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1638 glslangIntermediate->getVertices());
1639 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV,
1640 glslangIntermediate->getPrimitives());
Chao Chen3c366992018-09-19 11:41:59 -07001641
1642 switch (glslangIntermediate->getOutputPrimitive()) {
1643 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1644 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1645 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1646 default: mode = spv::ExecutionModeMax; break;
1647 }
1648 if (mode != spv::ExecutionModeMax)
1649 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1650 }
1651 break;
1652#endif
1653
John Kessenich140f3df2015-06-26 16:58:36 -06001654 default:
1655 break;
1656 }
John Kessenich140f3df2015-06-26 16:58:36 -06001657}
1658
John Kessenichfca82622016-11-26 13:23:20 -07001659// Finish creating SPV, after the traversal is complete.
1660void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001661{
John Kessenichf04c51b2018-08-03 15:56:12 -06001662 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001663 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001664 builder.setBuildPoint(shaderEntry->getLastBlock());
1665 builder.leaveFunction();
1666 }
1667
John Kessenich7ba63412015-12-20 17:37:07 -07001668 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001669 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1670 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001671
David Neto8c3d5b42019-10-21 14:50:31 -04001672 // Add capabilities, extensions, remove unneeded decorations, etc.,
John Kessenichf04c51b2018-08-03 15:56:12 -06001673 // based on the resulting SPIR-V.
David Neto8c3d5b42019-10-21 14:50:31 -04001674 // Note: WebGPU code generation must have the opportunity to aggressively
1675 // prune unreachable merge blocks and continue targets.
John Kessenichf04c51b2018-08-03 15:56:12 -06001676 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001677}
1678
John Kessenichfca82622016-11-26 13:23:20 -07001679// Write the SPV into 'out'.
1680void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001681{
John Kessenichfca82622016-11-26 13:23:20 -07001682 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001683}
1684
1685//
1686// Implement the traversal functions.
1687//
1688// Return true from interior nodes to have the external traversal
1689// continue on to children. Return false if children were
1690// already processed.
1691//
1692
1693//
qining25262b32016-05-06 17:25:16 -04001694// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001695// - uniform/input reads
1696// - output writes
1697// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1698// - something simple that degenerates into the last bullet
1699//
1700void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1701{
qining75d1d802016-04-06 14:42:01 -04001702 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
Roy05a5b532020-01-03 16:21:34 +08001703 if (symbol->getType().isStruct())
1704 glslangTypeToIdMap[symbol->getType().getStruct()] = symbol->getId();
1705
qining75d1d802016-04-06 14:42:01 -04001706 if (symbol->getType().getQualifier().isSpecConstant())
1707 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1708
John Kessenich140f3df2015-06-26 16:58:36 -06001709 // getSymbolId() will set up all the IO decorations on the first call.
1710 // Formal function parameters were mapped during makeFunctions().
1711 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001712
John Kessenich7ba63412015-12-20 17:37:07 -07001713 if (builder.isPointer(id)) {
John Kessenichc30d3352020-06-10 07:15:24 -06001714 if (!symbol->getType().getQualifier().isParamInput() &&
1715 !symbol->getType().getQualifier().isParamOutput()) {
1716 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1717 // Consider adding to the OpEntryPoint interface list.
1718 // Only looking at structures if they have at least one member.
1719 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1720 spv::StorageClass sc = builder.getStorageClass(id);
1721 // Before SPIR-V 1.4, we only want to include Input and Output.
1722 // Starting with SPIR-V 1.4, we want all globals.
1723 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1724 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
1725 iOSet.insert(id);
1726 }
John Kessenich7c7731e2019-01-04 16:47:06 +07001727 }
John Kessenich5f77d862017-09-19 11:09:59 -06001728 }
John Kessenich9c14f772019-06-17 08:38:35 -06001729
Daniel Kochdb32b242020-03-17 20:42:47 -04001730 // If the SPIR-V type is required to be different than the AST type
1731 // (for ex SubgroupMasks or 3x4 ObjectToWorld/WorldToObject matrices),
John Kessenich9c14f772019-06-17 08:38:35 -06001732 // translate now from the SPIR-V type to the AST type, for the consuming
1733 // operation.
1734 // Note this turns it from an l-value to an r-value.
1735 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1736 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1737 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001738 }
1739
1740 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001741 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001742 // Prepare to generate code for the access
1743
1744 // L-value chains will be computed left to right. We're on the symbol now,
1745 // which is the left-most part of the access chain, so now is "clear" time,
1746 // followed by setting the base.
1747 builder.clearAccessChain();
1748
1749 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001750 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001751 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001752 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001753 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001754 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001755 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001756 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001757 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1758 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001759 builder.setAccessChainRValue(id);
1760 else
1761 builder.setAccessChainLValue(id);
1762 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001763
John Kessenichb9197c82019-08-11 07:41:45 -06001764#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001765 // Process linkage-only nodes for any special additional interface work.
1766 if (linkageOnly) {
1767 if (glslangIntermediate->getHlslFunctionality1()) {
1768 // Map implicit counter buffers to their originating buffers, which should have been
1769 // seen by now, given earlier pruning of unused counters, and preservation of order
1770 // of declaration.
1771 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1772 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1773 // Save possible originating buffers for counter buffers, keyed by
1774 // making the potential counter-buffer name.
1775 std::string keyName = symbol->getName().c_str();
1776 keyName = glslangIntermediate->addCounterBufferName(keyName);
1777 counterOriginator[keyName] = symbol;
1778 } else {
1779 // Handle a counter buffer, by finding the saved originating buffer.
1780 std::string keyName = symbol->getName().c_str();
1781 auto it = counterOriginator.find(keyName);
1782 if (it != counterOriginator.end()) {
1783 id = getSymbolId(it->second);
1784 if (id != spv::NoResult) {
1785 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001786 if (counterId != spv::NoResult) {
1787 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001788 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001789 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001790 }
1791 }
1792 }
1793 }
1794 }
1795 }
John Kessenich155d3512019-08-08 23:29:20 -06001796#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001797}
1798
1799bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1800{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001801 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Roy05a5b532020-01-03 16:21:34 +08001802 if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
1803 glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
1804 }
1805 if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
1806 glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
1807 }
John Kesseniche485c7a2017-05-31 18:50:53 -06001808
qining40887662016-04-03 22:20:42 -04001809 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1810 if (node->getType().getQualifier().isSpecConstant())
1811 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1812
John Kessenich140f3df2015-06-26 16:58:36 -06001813 // First, handle special cases
1814 switch (node->getOp()) {
1815 case glslang::EOpAssign:
1816 case glslang::EOpAddAssign:
1817 case glslang::EOpSubAssign:
1818 case glslang::EOpMulAssign:
1819 case glslang::EOpVectorTimesMatrixAssign:
1820 case glslang::EOpVectorTimesScalarAssign:
1821 case glslang::EOpMatrixTimesScalarAssign:
1822 case glslang::EOpMatrixTimesMatrixAssign:
1823 case glslang::EOpDivAssign:
1824 case glslang::EOpModAssign:
1825 case glslang::EOpAndAssign:
1826 case glslang::EOpInclusiveOrAssign:
1827 case glslang::EOpExclusiveOrAssign:
1828 case glslang::EOpLeftShiftAssign:
1829 case glslang::EOpRightShiftAssign:
1830 // A bin-op assign "a += b" means the same thing as "a = a + b"
1831 // where a is evaluated before b. For a simple assignment, GLSL
1832 // says to evaluate the left before the right. So, always, left
1833 // node then right node.
1834 {
1835 // get the left l-value, save it away
1836 builder.clearAccessChain();
1837 node->getLeft()->traverse(this);
1838 spv::Builder::AccessChain lValue = builder.getAccessChain();
1839
1840 // evaluate the right
1841 builder.clearAccessChain();
1842 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001843 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001844
1845 if (node->getOp() != glslang::EOpAssign) {
1846 // the left is also an r-value
1847 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001848 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001849
1850 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001851 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001852 TranslateNoContractionDecoration(node->getType().getQualifier()),
1853 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001854 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001855 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1856 node->getType().getBasicType());
1857
1858 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001859 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001860 }
1861
1862 // store the result
1863 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001864 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001865
1866 // assignments are expressions having an rValue after they are evaluated...
1867 builder.clearAccessChain();
1868 builder.setAccessChainRValue(rValue);
1869 }
1870 return false;
1871 case glslang::EOpIndexDirect:
1872 case glslang::EOpIndexDirectStruct:
1873 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001874 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001875 // Get the left part of the access chain.
1876 node->getLeft()->traverse(this);
1877
1878 // Add the next element in the chain
1879
David Netoa901ffe2016-06-08 14:11:40 +01001880 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001881 if (! node->getLeft()->getType().isArray() &&
1882 node->getLeft()->getType().isVector() &&
1883 node->getOp() == glslang::EOpIndexDirect) {
1884 // This is essentially a hard-coded vector swizzle of size 1,
1885 // so short circuit the access-chain stuff with a swizzle.
1886 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001887 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001888 int dummySize;
1889 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1890 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001891 glslangIntermediate->getBaseAlignmentScalar(
1892 node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001893 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001894
1895 // Load through a block reference is performed with a dot operator that
1896 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1897 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001898 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001899 !node->getLeft()->getType().isArray() &&
1900 node->getOp() == glslang::EOpIndexDirectStruct)
1901 {
1902 spv::Id left = accessChainLoad(node->getLeft()->getType());
1903 builder.clearAccessChain();
1904 builder.setAccessChainLValue(left);
1905 }
1906
David Netoa901ffe2016-06-08 14:11:40 +01001907 int spvIndex = glslangIndex;
1908 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1909 node->getOp() == glslang::EOpIndexDirectStruct)
1910 {
1911 // This may be, e.g., an anonymous block-member selection, which generally need
1912 // index remapping due to hidden members in anonymous blocks.
Roy05a5b532020-01-03 16:21:34 +08001913 int glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
1914 if (memberRemapper.find(glslangId) != memberRemapper.end()) {
1915 std::vector<int>& remapper = memberRemapper[glslangId];
1916 assert(remapper.size() > 0);
1917 spvIndex = remapper[glslangIndex];
1918 }
David Netoa901ffe2016-06-08 14:11:40 +01001919 }
John Kessenichebb50532016-05-16 19:22:05 -06001920
David Netoa901ffe2016-06-08 14:11:40 +01001921 // normal case for indexing array or structure or block
John Kessenich8985fc92020-03-03 10:25:07 -07001922 builder.accessChainPush(builder.makeIntConstant(spvIndex),
1923 TranslateCoherent(node->getLeft()->getType()),
1924 node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001925
1926 // Add capabilities here for accessing PointSize and clip/cull distance.
1927 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001928 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001929 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001930 }
1931 }
1932 return false;
1933 case glslang::EOpIndexIndirect:
1934 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001935 // Array, matrix, or vector indirection with variable index.
1936 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001937 // matrices are arrays of vectors, so will also work for a matrix.
1938 // Will use the access chain's 'component' for variable index into a vector.
1939
1940 // This adapter is building access chains left to right.
1941 // Set up the access chain to the left.
1942 node->getLeft()->traverse(this);
1943
1944 // save it so that computing the right side doesn't trash it
1945 spv::Builder::AccessChain partial = builder.getAccessChain();
1946
1947 // compute the next index in the chain
1948 builder.clearAccessChain();
1949 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001950 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001951
John Kessenich5611c6d2018-04-05 11:25:02 -06001952 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1953
John Kessenich140f3df2015-06-26 16:58:36 -06001954 // restore the saved access chain
1955 builder.setAccessChain(partial);
1956
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001957 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1958 int dummySize;
1959 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1960 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001961 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1962 dummySize));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001963 } else
John Kessenich8985fc92020-03-03 10:25:07 -07001964 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()),
1965 node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001966 }
1967 return false;
1968 case glslang::EOpVectorSwizzle:
1969 {
1970 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001971 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001972 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001973 int dummySize;
1974 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1975 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001976 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1977 dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001978 }
1979 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001980 case glslang::EOpMatrixSwizzle:
1981 logger->missingFunctionality("matrix swizzle");
1982 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001983 case glslang::EOpLogicalOr:
1984 case glslang::EOpLogicalAnd:
1985 {
1986
1987 // These may require short circuiting, but can sometimes be done as straight
1988 // binary operations. The right operand must be short circuited if it has
1989 // side effects, and should probably be if it is complex.
1990 if (isTrivial(node->getRight()->getAsTyped()))
1991 break; // handle below as a normal binary operation
1992 // otherwise, we need to do dynamic short circuiting on the right operand
John Kessenich8985fc92020-03-03 10:25:07 -07001993 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(),
1994 *node->getRight()->getAsTyped());
John Kessenich7c1aa102015-10-15 13:29:11 -06001995 builder.clearAccessChain();
1996 builder.setAccessChainRValue(result);
1997 }
1998 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001999 default:
2000 break;
2001 }
2002
2003 // Assume generic binary op...
2004
John Kessenich32cfd492016-02-02 12:37:46 -07002005 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06002006 builder.clearAccessChain();
2007 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002008 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002009
John Kessenich32cfd492016-02-02 12:37:46 -07002010 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06002011 builder.clearAccessChain();
2012 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002013 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002014
John Kessenich32cfd492016-02-02 12:37:46 -07002015 // get result
John Kessenichead86222018-03-28 18:01:20 -06002016 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002017 TranslateNoContractionDecoration(node->getType().getQualifier()),
2018 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002019 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07002020 convertGlslangToSpvType(node->getType()), left, right,
2021 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002022
John Kessenich50e57562015-12-21 21:21:11 -07002023 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06002024 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002025 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07002026 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06002027 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06002028 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06002029 return false;
2030 }
John Kessenich140f3df2015-06-26 16:58:36 -06002031}
2032
John Kessenich9c14f772019-06-17 08:38:35 -06002033// Figure out what, if any, type changes are needed when accessing a specific built-in.
2034// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
2035// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
Daniel Kochdb32b242020-03-17 20:42:47 -04002036std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(glslang::TBuiltInVariable glslangBuiltIn,
John Kessenich9c14f772019-06-17 08:38:35 -06002037 const glslang::TType& glslangType)
2038{
Daniel Kochdb32b242020-03-17 20:42:47 -04002039 switch(glslangBuiltIn)
John Kessenich9c14f772019-06-17 08:38:35 -06002040 {
Daniel Kochdb32b242020-03-17 20:42:47 -04002041 case glslang::EbvSubGroupEqMask:
2042 case glslang::EbvSubGroupGeMask:
2043 case glslang::EbvSubGroupGtMask:
2044 case glslang::EbvSubGroupLeMask:
2045 case glslang::EbvSubGroupLtMask: {
John Kessenich9c14f772019-06-17 08:38:35 -06002046 // these require changing a 64-bit scaler -> a vector of 32-bit components
2047 if (glslangType.isVector())
2048 break;
2049 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
2050 builder.makeUintType(64));
2051 return ret;
2052 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002053 // There are no SPIR-V builtins defined for these and map onto original non-transposed
2054 // builtins. During visitBinary we insert a transpose
2055 case glslang::EbvWorldToObject3x4:
2056 case glslang::EbvObjectToWorld3x4: {
2057 std::pair<spv::Id, spv::Id> ret(builder.makeMatrixType(builder.makeFloatType(32), 4, 3),
2058 builder.makeMatrixType(builder.makeFloatType(32), 3, 4)
2059 );
2060 return ret;
2061 }
John Kessenich9c14f772019-06-17 08:38:35 -06002062 default:
2063 break;
2064 }
2065
2066 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2067 return ret;
2068}
2069
2070// For an object previously identified (see getForcedType() and forceType)
2071// as needing type translations, do the translation needed for a load, turning
2072// an L-value into in R-value.
2073spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2074{
2075 const auto forceIt = forceType.find(object);
2076 if (forceIt == forceType.end())
2077 return object;
2078
2079 spv::Id desiredTypeId = forceIt->second;
2080 spv::Id objectTypeId = builder.getTypeId(object);
2081 assert(builder.isPointerType(objectTypeId));
2082 objectTypeId = builder.getContainedTypeId(objectTypeId);
2083 if (builder.isVectorType(objectTypeId) &&
2084 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2085 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2086 // handle 32-bit v.xy* -> 64-bit
2087 builder.clearAccessChain();
2088 builder.setAccessChainLValue(object);
2089 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2090 std::vector<spv::Id> components;
2091 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2092 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2093
2094 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2095 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2096 builder.createCompositeConstruct(vecType, components));
2097 } else {
2098 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2099 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002100 } else if (builder.isMatrixType(objectTypeId)) {
2101 // There are no SPIR-V builtins defined for 3x4 variants of ObjectToWorld/WorldToObject
2102 // and we insert a transpose after loading the original non-transposed builtins
2103 builder.clearAccessChain();
2104 builder.setAccessChainLValue(object);
2105 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2106 return builder.createUnaryOp(spv::OpTranspose, desiredTypeId, object);
2107
2108 } else {
John Kessenich9c14f772019-06-17 08:38:35 -06002109 logger->missingFunctionality("forcing non 32-bit vector type");
2110 }
2111
2112 return object;
2113}
2114
John Kessenich140f3df2015-06-26 16:58:36 -06002115bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2116{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002117 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002118
qining40887662016-04-03 22:20:42 -04002119 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2120 if (node->getType().getQualifier().isSpecConstant())
2121 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2122
John Kessenichfc51d282015-08-19 13:34:18 -06002123 spv::Id result = spv::NoResult;
2124
2125 // try texturing first
2126 result = createImageTextureFunctionCall(node);
2127 if (result != spv::NoResult) {
2128 builder.clearAccessChain();
2129 builder.setAccessChainRValue(result);
2130
2131 return false; // done with this node
2132 }
2133
2134 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002135
2136 if (node->getOp() == glslang::EOpArrayLength) {
2137 // Quite special; won't want to evaluate the operand.
2138
John Kessenich5611c6d2018-04-05 11:25:02 -06002139 // Currently, the front-end does not allow .length() on an array until it is sized,
2140 // except for the last block membeor of an SSBO.
2141 // TODO: If this changes, link-time sized arrays might show up here, and need their
2142 // size extracted.
2143
John Kessenichc9a80832015-09-12 12:17:44 -06002144 // Normal .length() would have been constant folded by the front-end.
2145 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002146 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002147
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002148 spv::Id length;
2149 if (node->getOperand()->getType().isCoopMat()) {
2150 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2151
2152 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2153 assert(builder.isCooperativeMatrixType(typeId));
2154
2155 length = builder.createCooperativeMatrixLength(typeId);
2156 } else {
2157 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2158 block->traverse(this);
John Kessenich8985fc92020-03-03 10:25:07 -07002159 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()
2160 ->getConstArray()[0].getUConst();
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002161 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2162 }
John Kessenichc9a80832015-09-12 12:17:44 -06002163
John Kessenich8c869672018-11-28 07:01:37 -07002164 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2165 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2166 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002167 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2168 if (builder.isInSpecConstCodeGenMode()) {
2169 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2170 } else {
2171 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2172 }
2173 }
John Kessenich8c869672018-11-28 07:01:37 -07002174
John Kessenichc9a80832015-09-12 12:17:44 -06002175 builder.clearAccessChain();
2176 builder.setAccessChainRValue(length);
2177
2178 return false;
2179 }
2180
John Kessenichfc51d282015-08-19 13:34:18 -06002181 // Start by evaluating the operand
2182
John Kessenich8c8505c2016-07-26 12:50:38 -06002183 // Does it need a swizzle inversion? If so, evaluation is inverted;
2184 // operate first on the swizzle base, then apply the swizzle.
2185 spv::Id invertedType = spv::NoType;
John Kessenich8985fc92020-03-03 10:25:07 -07002186 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2187 invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenich8c8505c2016-07-26 12:50:38 -06002188 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2189 invertedType = getInvertedSwizzleType(*node->getOperand());
2190
John Kessenich140f3df2015-06-26 16:58:36 -06002191 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002192 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002193 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002194 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002195 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002196 operandNode = node->getOperand();
2197
2198 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002199
Rex Xufc618912015-09-09 16:42:49 +08002200 spv::Id operand = spv::NoResult;
2201
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002202 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2203
John Kessenichfb4f2332019-08-09 03:49:15 -06002204#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002205 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2206 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002207 node->getOp() == glslang::EOpAtomicCounter ||
Neslisah Torosdagli7d37a682020-03-26 10:52:33 -04002208 node->getOp() == glslang::EOpInterpolateAtCentroid ||
2209 node->getOp() == glslang::EOpRayQueryProceed ||
2210 node->getOp() == glslang::EOpRayQueryGetRayTMin ||
2211 node->getOp() == glslang::EOpRayQueryGetRayFlags ||
2212 node->getOp() == glslang::EOpRayQueryGetWorldRayOrigin ||
2213 node->getOp() == glslang::EOpRayQueryGetWorldRayDirection ||
2214 node->getOp() == glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque ||
2215 node->getOp() == glslang::EOpRayQueryTerminate ||
2216 node->getOp() == glslang::EOpRayQueryConfirmIntersection) {
Rex Xufc618912015-09-09 16:42:49 +08002217 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002218 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2219 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2220 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002221#endif
2222 {
John Kessenich32cfd492016-02-02 12:37:46 -07002223 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002224 }
John Kessenich140f3df2015-06-26 16:58:36 -06002225
John Kessenichead86222018-03-28 18:01:20 -06002226 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002227 TranslateNoContractionDecoration(node->getType().getQualifier()),
2228 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002229
2230 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002231 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002232 result = createConversion(node->getOp(), decorations, resultType(), operand,
2233 node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002234
2235 // if not, then possibly an operation
2236 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002237 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand,
2238 node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002239
2240 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002241 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002242 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002243 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002244 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002245
John Kessenich140f3df2015-06-26 16:58:36 -06002246 builder.clearAccessChain();
2247 builder.setAccessChainRValue(result);
2248
2249 return false; // done with this node
2250 }
2251
2252 // it must be a special case, check...
2253 switch (node->getOp()) {
2254 case glslang::EOpPostIncrement:
2255 case glslang::EOpPostDecrement:
2256 case glslang::EOpPreIncrement:
2257 case glslang::EOpPreDecrement:
2258 {
2259 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002260 spv::Id one = 0;
2261 if (node->getBasicType() == glslang::EbtFloat)
2262 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002263#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002264 else if (node->getBasicType() == glslang::EbtDouble)
2265 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002266 else if (node->getBasicType() == glslang::EbtFloat16)
2267 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002268 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2269 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002270 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2271 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002272 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2273 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002274#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002275 else
2276 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002277 glslang::TOperator op;
2278 if (node->getOp() == glslang::EOpPreIncrement ||
2279 node->getOp() == glslang::EOpPostIncrement)
2280 op = glslang::EOpAdd;
2281 else
2282 op = glslang::EOpSub;
2283
John Kessenichead86222018-03-28 18:01:20 -06002284 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002285 convertGlslangToSpvType(node->getType()), operand, one,
2286 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002287 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002288
2289 // The result of operation is always stored, but conditionally the
2290 // consumed result. The consumed result is always an r-value.
2291 builder.accessChainStore(result);
2292 builder.clearAccessChain();
2293 if (node->getOp() == glslang::EOpPreIncrement ||
2294 node->getOp() == glslang::EOpPreDecrement)
2295 builder.setAccessChainRValue(result);
2296 else
2297 builder.setAccessChainRValue(operand);
2298 }
2299
2300 return false;
2301
John Kessenich155d3512019-08-08 23:29:20 -06002302#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002303 case glslang::EOpEmitStreamVertex:
2304 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2305 return false;
2306 case glslang::EOpEndStreamPrimitive:
2307 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2308 return false;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002309 case glslang::EOpRayQueryTerminate:
2310 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operand);
2311 return false;
2312 case glslang::EOpRayQueryConfirmIntersection:
2313 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operand);
2314 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002315#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002316
2317 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002318 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002319 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002320 }
John Kessenich140f3df2015-06-26 16:58:36 -06002321}
2322
Jeff Bolz53134492019-06-25 13:31:10 -05002323// Construct a composite object, recursively copying members if their types don't match
2324spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2325{
2326 for (int c = 0; c < (int)constituents.size(); ++c) {
2327 spv::Id& constituent = constituents[c];
2328 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2329 spv::Id rType = builder.getTypeId(constituent);
2330 if (lType != rType) {
2331 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2332 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2333 } else if (builder.isStructType(rType)) {
2334 std::vector<spv::Id> rTypeConstituents;
2335 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2336 for (int i = 0; i < numrTypeConstituents; ++i) {
John Kessenich8985fc92020-03-03 10:25:07 -07002337 rTypeConstituents.push_back(builder.createCompositeExtract(constituent,
2338 builder.getContainedTypeId(rType, i), i));
Jeff Bolz53134492019-06-25 13:31:10 -05002339 }
2340 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2341 } else {
2342 assert(builder.isArrayType(rType));
2343 std::vector<spv::Id> rTypeConstituents;
2344 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2345
2346 spv::Id elementRType = builder.getContainedTypeId(rType);
2347 for (int i = 0; i < numrTypeConstituents; ++i) {
2348 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2349 }
2350 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2351 }
2352 }
2353 }
2354 return builder.createCompositeConstruct(resultTypeId, constituents);
2355}
2356
John Kessenich140f3df2015-06-26 16:58:36 -06002357bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2358{
qining27e04a02016-04-14 16:40:20 -04002359 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2360 if (node->getType().getQualifier().isSpecConstant())
2361 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2362
John Kessenichfc51d282015-08-19 13:34:18 -06002363 spv::Id result = spv::NoResult;
Cody Northrop4d2298b2020-04-13 21:59:49 -06002364 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2365 std::vector<spv::Builder::AccessChain> complexLvalues; // for holding swizzling l-values too complex for
2366 // SPIR-V, for an out parameter
2367 std::vector<spv::Id> temporaryLvalues; // temporaries to pass, as proxies for complexLValues
John Kessenichbbbd9a22020-03-03 07:21:37 -07002368
John Kessenich8985fc92020-03-03 10:25:07 -07002369 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2370 invertedType :
2371 convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002372
2373 // try texturing
2374 result = createImageTextureFunctionCall(node);
2375 if (result != spv::NoResult) {
2376 builder.clearAccessChain();
2377 builder.setAccessChainRValue(result);
2378
2379 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002380 }
2381#ifndef GLSLANG_WEB
2382 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002383 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002384 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002385 // "imageStore" is a special case, which has no result
2386 return false;
2387 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002388#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002389
John Kessenich140f3df2015-06-26 16:58:36 -06002390 glslang::TOperator binOp = glslang::EOpNull;
2391 bool reduceComparison = true;
2392 bool isMatrix = false;
2393 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002394 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002395
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002396 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2397
John Kessenich140f3df2015-06-26 16:58:36 -06002398 assert(node->getOp());
2399
John Kessenichf6640762016-08-01 19:44:00 -06002400 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002401
2402 switch (node->getOp()) {
2403 case glslang::EOpSequence:
2404 {
2405 if (preVisit)
2406 ++sequenceDepth;
2407 else
2408 --sequenceDepth;
2409
2410 if (sequenceDepth == 1) {
2411 // If this is the parent node of all the functions, we want to see them
2412 // early, so all call points have actual SPIR-V functions to reference.
2413 // In all cases, still let the traverser visit the children for us.
2414 makeFunctions(node->getAsAggregate()->getSequence());
2415
John Kessenich6fccb3c2016-09-19 16:01:41 -06002416 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002417 // anything else gets there, so visit out of order, doing them all now.
2418 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2419
John Kessenich6a60c2f2016-12-08 21:01:59 -07002420 // 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 -06002421 // so do them manually.
2422 visitFunctions(node->getAsAggregate()->getSequence());
2423
2424 return false;
2425 }
2426
2427 return true;
2428 }
2429 case glslang::EOpLinkerObjects:
2430 {
2431 if (visit == glslang::EvPreVisit)
2432 linkageOnly = true;
2433 else
2434 linkageOnly = false;
2435
2436 return true;
2437 }
2438 case glslang::EOpComma:
2439 {
2440 // processing from left to right naturally leaves the right-most
2441 // lying around in the access chain
2442 glslang::TIntermSequence& glslangOperands = node->getSequence();
2443 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2444 glslangOperands[i]->traverse(this);
2445
2446 return false;
2447 }
2448 case glslang::EOpFunction:
2449 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002450 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002451 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002452 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002453 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002454 } else {
2455 handleFunctionEntry(node);
2456 }
2457 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002458 if (inEntryPoint)
2459 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002460 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002461 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002462 }
2463
2464 return true;
2465 case glslang::EOpParameters:
2466 // Parameters will have been consumed by EOpFunction processing, but not
2467 // the body, so we still visited the function node's children, making this
2468 // child redundant.
2469 return false;
2470 case glslang::EOpFunctionCall:
2471 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002472 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002473 if (node->isUserDefined())
2474 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07002475 if (result) {
2476 builder.clearAccessChain();
2477 builder.setAccessChainRValue(result);
2478 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002479 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002480
2481 return false;
2482 }
2483 case glslang::EOpConstructMat2x2:
2484 case glslang::EOpConstructMat2x3:
2485 case glslang::EOpConstructMat2x4:
2486 case glslang::EOpConstructMat3x2:
2487 case glslang::EOpConstructMat3x3:
2488 case glslang::EOpConstructMat3x4:
2489 case glslang::EOpConstructMat4x2:
2490 case glslang::EOpConstructMat4x3:
2491 case glslang::EOpConstructMat4x4:
2492 case glslang::EOpConstructDMat2x2:
2493 case glslang::EOpConstructDMat2x3:
2494 case glslang::EOpConstructDMat2x4:
2495 case glslang::EOpConstructDMat3x2:
2496 case glslang::EOpConstructDMat3x3:
2497 case glslang::EOpConstructDMat3x4:
2498 case glslang::EOpConstructDMat4x2:
2499 case glslang::EOpConstructDMat4x3:
2500 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002501 case glslang::EOpConstructIMat2x2:
2502 case glslang::EOpConstructIMat2x3:
2503 case glslang::EOpConstructIMat2x4:
2504 case glslang::EOpConstructIMat3x2:
2505 case glslang::EOpConstructIMat3x3:
2506 case glslang::EOpConstructIMat3x4:
2507 case glslang::EOpConstructIMat4x2:
2508 case glslang::EOpConstructIMat4x3:
2509 case glslang::EOpConstructIMat4x4:
2510 case glslang::EOpConstructUMat2x2:
2511 case glslang::EOpConstructUMat2x3:
2512 case glslang::EOpConstructUMat2x4:
2513 case glslang::EOpConstructUMat3x2:
2514 case glslang::EOpConstructUMat3x3:
2515 case glslang::EOpConstructUMat3x4:
2516 case glslang::EOpConstructUMat4x2:
2517 case glslang::EOpConstructUMat4x3:
2518 case glslang::EOpConstructUMat4x4:
2519 case glslang::EOpConstructBMat2x2:
2520 case glslang::EOpConstructBMat2x3:
2521 case glslang::EOpConstructBMat2x4:
2522 case glslang::EOpConstructBMat3x2:
2523 case glslang::EOpConstructBMat3x3:
2524 case glslang::EOpConstructBMat3x4:
2525 case glslang::EOpConstructBMat4x2:
2526 case glslang::EOpConstructBMat4x3:
2527 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002528 case glslang::EOpConstructF16Mat2x2:
2529 case glslang::EOpConstructF16Mat2x3:
2530 case glslang::EOpConstructF16Mat2x4:
2531 case glslang::EOpConstructF16Mat3x2:
2532 case glslang::EOpConstructF16Mat3x3:
2533 case glslang::EOpConstructF16Mat3x4:
2534 case glslang::EOpConstructF16Mat4x2:
2535 case glslang::EOpConstructF16Mat4x3:
2536 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002537 isMatrix = true;
2538 // fall through
2539 case glslang::EOpConstructFloat:
2540 case glslang::EOpConstructVec2:
2541 case glslang::EOpConstructVec3:
2542 case glslang::EOpConstructVec4:
2543 case glslang::EOpConstructDouble:
2544 case glslang::EOpConstructDVec2:
2545 case glslang::EOpConstructDVec3:
2546 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002547 case glslang::EOpConstructFloat16:
2548 case glslang::EOpConstructF16Vec2:
2549 case glslang::EOpConstructF16Vec3:
2550 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002551 case glslang::EOpConstructBool:
2552 case glslang::EOpConstructBVec2:
2553 case glslang::EOpConstructBVec3:
2554 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002555 case glslang::EOpConstructInt8:
2556 case glslang::EOpConstructI8Vec2:
2557 case glslang::EOpConstructI8Vec3:
2558 case glslang::EOpConstructI8Vec4:
2559 case glslang::EOpConstructUint8:
2560 case glslang::EOpConstructU8Vec2:
2561 case glslang::EOpConstructU8Vec3:
2562 case glslang::EOpConstructU8Vec4:
2563 case glslang::EOpConstructInt16:
2564 case glslang::EOpConstructI16Vec2:
2565 case glslang::EOpConstructI16Vec3:
2566 case glslang::EOpConstructI16Vec4:
2567 case glslang::EOpConstructUint16:
2568 case glslang::EOpConstructU16Vec2:
2569 case glslang::EOpConstructU16Vec3:
2570 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002571 case glslang::EOpConstructInt:
2572 case glslang::EOpConstructIVec2:
2573 case glslang::EOpConstructIVec3:
2574 case glslang::EOpConstructIVec4:
2575 case glslang::EOpConstructUint:
2576 case glslang::EOpConstructUVec2:
2577 case glslang::EOpConstructUVec3:
2578 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002579 case glslang::EOpConstructInt64:
2580 case glslang::EOpConstructI64Vec2:
2581 case glslang::EOpConstructI64Vec3:
2582 case glslang::EOpConstructI64Vec4:
2583 case glslang::EOpConstructUint64:
2584 case glslang::EOpConstructU64Vec2:
2585 case glslang::EOpConstructU64Vec3:
2586 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002587 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002588 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002589 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002590 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002591 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002592 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002593 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002594 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002595 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002596 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002597 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002598 else if (node->getOp() == glslang::EOpConstructStruct ||
2599 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2600 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002601 std::vector<spv::Id> constituents;
2602 for (int c = 0; c < (int)arguments.size(); ++c)
2603 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002604 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002605 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002606 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002607 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002608 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002609
2610 builder.clearAccessChain();
2611 builder.setAccessChainRValue(constructed);
2612
2613 return false;
2614 }
2615
2616 // These six are component-wise compares with component-wise results.
2617 // Forward on to createBinaryOperation(), requesting a vector result.
2618 case glslang::EOpLessThan:
2619 case glslang::EOpGreaterThan:
2620 case glslang::EOpLessThanEqual:
2621 case glslang::EOpGreaterThanEqual:
2622 case glslang::EOpVectorEqual:
2623 case glslang::EOpVectorNotEqual:
2624 {
2625 // Map the operation to a binary
2626 binOp = node->getOp();
2627 reduceComparison = false;
2628 switch (node->getOp()) {
2629 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2630 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2631 default: binOp = node->getOp(); break;
2632 }
2633
2634 break;
2635 }
2636 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002637 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002638 binOp = glslang::EOpMul;
2639 break;
2640 case glslang::EOpOuterProduct:
2641 // two vectors multiplied to make a matrix
2642 binOp = glslang::EOpOuterProduct;
2643 break;
2644 case glslang::EOpDot:
2645 {
qining25262b32016-05-06 17:25:16 -04002646 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002647 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002648 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002649 binOp = glslang::EOpMul;
2650 break;
2651 }
2652 case glslang::EOpMod:
2653 // when an aggregate, this is the floating-point mod built-in function,
2654 // which can be emitted by the one in createBinaryOperation()
2655 binOp = glslang::EOpMod;
2656 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002657
John Kessenich140f3df2015-06-26 16:58:36 -06002658 case glslang::EOpEmitVertex:
2659 case glslang::EOpEndPrimitive:
2660 case glslang::EOpBarrier:
2661 case glslang::EOpMemoryBarrier:
2662 case glslang::EOpMemoryBarrierAtomicCounter:
2663 case glslang::EOpMemoryBarrierBuffer:
2664 case glslang::EOpMemoryBarrierImage:
2665 case glslang::EOpMemoryBarrierShared:
2666 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002667 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002668 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002669 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002670 case glslang::EOpWorkgroupMemoryBarrier:
2671 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002672 case glslang::EOpSubgroupBarrier:
2673 case glslang::EOpSubgroupMemoryBarrier:
2674 case glslang::EOpSubgroupMemoryBarrierBuffer:
2675 case glslang::EOpSubgroupMemoryBarrierImage:
2676 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002677 noReturnValue = true;
2678 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2679 break;
2680
John Kessenich426394d2015-07-23 10:22:48 -06002681 case glslang::EOpAtomicAdd:
2682 case glslang::EOpAtomicMin:
2683 case glslang::EOpAtomicMax:
2684 case glslang::EOpAtomicAnd:
2685 case glslang::EOpAtomicOr:
2686 case glslang::EOpAtomicXor:
2687 case glslang::EOpAtomicExchange:
2688 case glslang::EOpAtomicCompSwap:
2689 atomic = true;
2690 break;
2691
John Kesseniche5eee8f2019-10-18 01:03:11 -06002692#ifndef GLSLANG_WEB
2693 case glslang::EOpAtomicStore:
2694 noReturnValue = true;
2695 // fallthrough
2696 case glslang::EOpAtomicLoad:
2697 atomic = true;
2698 break;
2699
John Kessenich0d0c6d32017-07-23 16:08:26 -06002700 case glslang::EOpAtomicCounterAdd:
2701 case glslang::EOpAtomicCounterSubtract:
2702 case glslang::EOpAtomicCounterMin:
2703 case glslang::EOpAtomicCounterMax:
2704 case glslang::EOpAtomicCounterAnd:
2705 case glslang::EOpAtomicCounterOr:
2706 case glslang::EOpAtomicCounterXor:
2707 case glslang::EOpAtomicCounterExchange:
2708 case glslang::EOpAtomicCounterCompSwap:
2709 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2710 builder.addCapability(spv::CapabilityAtomicStorageOps);
2711 atomic = true;
2712 break;
2713
Ian Romanickb3bd4022019-01-21 08:57:25 -08002714 case glslang::EOpAbsDifference:
2715 case glslang::EOpAddSaturate:
2716 case glslang::EOpSubSaturate:
2717 case glslang::EOpAverage:
2718 case glslang::EOpAverageRounded:
2719 case glslang::EOpMul32x16:
2720 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2721 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2722 binOp = node->getOp();
2723 break;
2724
Daniel Kochdb32b242020-03-17 20:42:47 -04002725 case glslang::EOpIgnoreIntersection:
2726 case glslang::EOpTerminateRay:
2727 case glslang::EOpTrace:
2728 case glslang::EOpExecuteCallable:
Chao Chen3c366992018-09-19 11:41:59 -07002729 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2730 noReturnValue = true;
2731 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04002732 case glslang::EOpRayQueryInitialize:
2733 case glslang::EOpRayQueryTerminate:
2734 case glslang::EOpRayQueryGenerateIntersection:
2735 case glslang::EOpRayQueryConfirmIntersection:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002736 builder.addExtension("SPV_KHR_ray_query");
2737 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
Torosdagli06c2eee2020-03-19 11:09:57 -04002738 noReturnValue = true;
2739 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002740 case glslang::EOpRayQueryProceed:
2741 case glslang::EOpRayQueryGetIntersectionType:
2742 case glslang::EOpRayQueryGetRayTMin:
2743 case glslang::EOpRayQueryGetRayFlags:
2744 case glslang::EOpRayQueryGetIntersectionT:
2745 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2746 case glslang::EOpRayQueryGetIntersectionInstanceId:
2747 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2748 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2749 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2750 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2751 case glslang::EOpRayQueryGetIntersectionFrontFace:
2752 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
2753 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2754 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2755 case glslang::EOpRayQueryGetWorldRayDirection:
2756 case glslang::EOpRayQueryGetWorldRayOrigin:
2757 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2758 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2759 builder.addExtension("SPV_KHR_ray_query");
2760 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
2761 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002762 case glslang::EOpCooperativeMatrixLoad:
2763 case glslang::EOpCooperativeMatrixStore:
2764 noReturnValue = true;
2765 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002766 case glslang::EOpBeginInvocationInterlock:
2767 case glslang::EOpEndInvocationInterlock:
2768 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2769 noReturnValue = true;
2770 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002771#endif
Chao Chen3c366992018-09-19 11:41:59 -07002772
Jeff Bolz04d73732019-05-31 13:06:01 -05002773 case glslang::EOpDebugPrintf:
2774 noReturnValue = true;
2775 break;
2776
John Kessenich140f3df2015-06-26 16:58:36 -06002777 default:
2778 break;
2779 }
2780
2781 //
2782 // See if it maps to a regular operation.
2783 //
John Kessenich140f3df2015-06-26 16:58:36 -06002784 if (binOp != glslang::EOpNull) {
2785 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2786 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2787 assert(left && right);
2788
2789 builder.clearAccessChain();
2790 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002791 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002792
2793 builder.clearAccessChain();
2794 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002795 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002796
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002797 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002798 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002799 TranslateNoContractionDecoration(node->getType().getQualifier()),
2800 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002801 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002802 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002803 left->getType().getBasicType(), reduceComparison);
2804
2805 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002806 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002807 builder.clearAccessChain();
2808 builder.setAccessChainRValue(result);
2809
2810 return false;
2811 }
2812
John Kessenich426394d2015-07-23 10:22:48 -06002813 //
2814 // Create the list of operands.
2815 //
John Kessenich140f3df2015-06-26 16:58:36 -06002816 glslang::TIntermSequence& glslangOperands = node->getSequence();
2817 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002818 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002819 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002820 // special case l-value operands; there are just a few
2821 bool lvalue = false;
2822 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002823 case glslang::EOpModf:
2824 if (arg == 1)
2825 lvalue = true;
2826 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002827
Torosdagli06c2eee2020-03-19 11:09:57 -04002828 case glslang::EOpRayQueryInitialize:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002829 case glslang::EOpRayQueryTerminate:
2830 case glslang::EOpRayQueryConfirmIntersection:
2831 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04002832 case glslang::EOpRayQueryGenerateIntersection:
2833 case glslang::EOpRayQueryGetIntersectionType:
2834 case glslang::EOpRayQueryGetIntersectionT:
2835 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2836 case glslang::EOpRayQueryGetIntersectionInstanceId:
2837 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2838 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2839 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2840 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2841 case glslang::EOpRayQueryGetIntersectionFrontFace:
2842 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2843 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2844 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2845 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2846 if (arg == 0)
2847 lvalue = true;
2848 break;
2849
John Kesseniche5eee8f2019-10-18 01:03:11 -06002850 case glslang::EOpAtomicAdd:
2851 case glslang::EOpAtomicMin:
2852 case glslang::EOpAtomicMax:
2853 case glslang::EOpAtomicAnd:
2854 case glslang::EOpAtomicOr:
2855 case glslang::EOpAtomicXor:
2856 case glslang::EOpAtomicExchange:
2857 case glslang::EOpAtomicCompSwap:
2858 if (arg == 0)
2859 lvalue = true;
2860 break;
2861
John Kessenicha28f7a72019-08-06 07:00:58 -06002862#ifndef GLSLANG_WEB
2863 case glslang::EOpFrexp:
2864 if (arg == 1)
2865 lvalue = true;
2866 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002867 case glslang::EOpInterpolateAtSample:
2868 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002869 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002870 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002871 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002872
2873 // Does it need a swizzle inversion? If so, evaluation is inverted;
2874 // operate first on the swizzle base, then apply the swizzle.
John Kessenichbbbd9a22020-03-03 07:21:37 -07002875 // That is, we transform
2876 //
2877 // interpolate(v.zy) -> interpolate(v).zy
2878 //
John Kessenichecba76f2017-01-06 00:34:48 -07002879 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002880 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
John Kessenich8985fc92020-03-03 10:25:07 -07002881 invertedType = convertGlslangToSpvType(
2882 glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
John Kessenich8c8505c2016-07-26 12:50:38 -06002883 }
Rex Xu7a26c172015-12-08 17:12:09 +08002884 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002885 case glslang::EOpAtomicLoad:
2886 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002887 case glslang::EOpAtomicCounterAdd:
2888 case glslang::EOpAtomicCounterSubtract:
2889 case glslang::EOpAtomicCounterMin:
2890 case glslang::EOpAtomicCounterMax:
2891 case glslang::EOpAtomicCounterAnd:
2892 case glslang::EOpAtomicCounterOr:
2893 case glslang::EOpAtomicCounterXor:
2894 case glslang::EOpAtomicCounterExchange:
2895 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002896 if (arg == 0)
2897 lvalue = true;
2898 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002899 case glslang::EOpAddCarry:
2900 case glslang::EOpSubBorrow:
2901 if (arg == 2)
2902 lvalue = true;
2903 break;
2904 case glslang::EOpUMulExtended:
2905 case glslang::EOpIMulExtended:
2906 if (arg >= 2)
2907 lvalue = true;
2908 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002909 case glslang::EOpCooperativeMatrixLoad:
2910 if (arg == 0 || arg == 1)
2911 lvalue = true;
2912 break;
2913 case glslang::EOpCooperativeMatrixStore:
2914 if (arg == 1)
2915 lvalue = true;
2916 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002917#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002918 default:
2919 break;
2920 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002921 builder.clearAccessChain();
2922 if (invertedType != spv::NoType && arg == 0)
2923 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2924 else
2925 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002926
John Kessenichb9197c82019-08-11 07:41:45 -06002927#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002928 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2929 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2930
2931 if (arg == 1) {
2932 // fold "element" parameter into the access chain
2933 spv::Builder::AccessChain save = builder.getAccessChain();
2934 builder.clearAccessChain();
2935 glslangOperands[2]->traverse(this);
2936
2937 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2938
2939 builder.setAccessChain(save);
2940
2941 // Point to the first element of the array.
John Kessenich8985fc92020-03-03 10:25:07 -07002942 builder.accessChainPush(elementId,
2943 TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
2944 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002945
2946 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2947 unsigned int alignment = builder.getAccessChain().alignment;
2948
2949 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2950 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2951 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2952 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2953 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
John Kessenich8985fc92020-03-03 10:25:07 -07002954 if (builder.getStorageClass(builder.getAccessChain().base) ==
2955 spv::StorageClassPhysicalStorageBufferEXT) {
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002956 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2957 }
2958
2959 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2960
2961 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2962 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2963 }
2964
John Kessenich8985fc92020-03-03 10:25:07 -07002965 if (memoryAccess &
2966 (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2967 memoryAccessOperands.push_back(spv::IdImmediate(true,
2968 builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002969 }
2970 } else if (arg == 2) {
2971 continue;
2972 }
2973 }
John Kessenichb9197c82019-08-11 07:41:45 -06002974#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002975
John Kessenichbbbd9a22020-03-03 07:21:37 -07002976 // for l-values, pass the address, for r-values, pass the value
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002977 if (lvalue) {
John Kessenichbbbd9a22020-03-03 07:21:37 -07002978 if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
2979 // SPIR-V cannot represent an l-value containing a swizzle that doesn't
2980 // reduce to a simple access chain. So, we need a temporary vector to
2981 // receive the result, and must later swizzle that into the original
2982 // l-value.
Cody Northrop4d2298b2020-04-13 21:59:49 -06002983 complexLvalues.push_back(builder.getAccessChain());
John Kessenich435dd802020-06-30 01:27:08 -06002984 temporaryLvalues.push_back(builder.createVariable(
2985 spv::NoPrecision, spv::StorageClassFunction,
Cody Northrop4d2298b2020-04-13 21:59:49 -06002986 builder.accessChainGetInferredType(), "swizzleTemp"));
2987 operands.push_back(temporaryLvalues.back());
John Kessenichbbbd9a22020-03-03 07:21:37 -07002988 } else {
2989 operands.push_back(builder.accessChainGetLValue());
2990 }
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002991 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2992 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2993 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002994 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Torosdagli06c2eee2020-03-19 11:09:57 -04002995 glslang::TOperator glslangOp = node->getOp();
2996 if (arg == 1 &&
2997 (glslangOp == glslang::EOpRayQueryGetIntersectionType ||
2998 glslangOp == glslang::EOpRayQueryGetIntersectionT ||
2999 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceCustomIndex ||
3000 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceId ||
3001 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset ||
3002 glslangOp == glslang::EOpRayQueryGetIntersectionGeometryIndex ||
3003 glslangOp == glslang::EOpRayQueryGetIntersectionPrimitiveIndex ||
3004 glslangOp == glslang::EOpRayQueryGetIntersectionBarycentrics ||
3005 glslangOp == glslang::EOpRayQueryGetIntersectionFrontFace ||
3006 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayDirection ||
3007 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayOrigin ||
3008 glslangOp == glslang::EOpRayQueryGetIntersectionObjectToWorld ||
3009 glslangOp == glslang::EOpRayQueryGetIntersectionWorldToObject
3010 )) {
3011 bool cond = glslangOperands[arg]->getAsConstantUnion()->getConstArray()[0].getBConst();
3012 operands.push_back(builder.makeIntConstant(cond ? 1 : 0));
3013 }
3014 else {
3015 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
3016 }
3017
John Kesseniche485c7a2017-05-31 18:50:53 -06003018 }
John Kessenich140f3df2015-06-26 16:58:36 -06003019 }
John Kessenich426394d2015-07-23 10:22:48 -06003020
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003021 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06003022#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003023 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
3024 std::vector<spv::IdImmediate> idImmOps;
3025
3026 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3027 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3028 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3029 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3030 // get the pointee type
3031 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
3032 assert(builder.isCooperativeMatrixType(typeId));
3033 // do the op
3034 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
3035 // store the result to the pointer (out param 'm')
3036 builder.createStore(result, operands[0]);
3037 result = 0;
3038 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
3039 std::vector<spv::IdImmediate> idImmOps;
3040
3041 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3042 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
3043 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3044 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3045 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3046
3047 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
3048 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06003049 } else
3050#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06003051 if (atomic) {
3052 // Handle all atomics
John Kessenich8985fc92020-03-03 10:25:07 -07003053 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
3054 lvalueCoherentFlags);
Jeff Bolz04d73732019-05-31 13:06:01 -05003055 } else if (node->getOp() == glslang::EOpDebugPrintf) {
3056 if (!nonSemanticDebugPrintf) {
3057 nonSemanticDebugPrintf = builder.import("NonSemantic.DebugPrintf");
3058 }
3059 result = builder.createBuiltinCall(builder.makeVoidType(), nonSemanticDebugPrintf, spv::NonSemanticDebugPrintfDebugPrintf, operands);
3060 builder.addExtension(spv::E_SPV_KHR_non_semantic_info);
John Kesseniche5eee8f2019-10-18 01:03:11 -06003061 } else {
John Kessenich426394d2015-07-23 10:22:48 -06003062 // Pass through to generic operations.
3063 switch (glslangOperands.size()) {
3064 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06003065 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06003066 break;
3067 case 1:
John Kessenichead86222018-03-28 18:01:20 -06003068 {
3069 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06003070 TranslateNoContractionDecoration(node->getType().getQualifier()),
3071 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06003072 result = createUnaryOperation(
3073 node->getOp(), decorations,
3074 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003075 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06003076 }
John Kessenich426394d2015-07-23 10:22:48 -06003077 break;
3078 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06003079 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06003080 break;
3081 }
Cody Northrop4d2298b2020-04-13 21:59:49 -06003082
John Kessenichbbbd9a22020-03-03 07:21:37 -07003083 if (invertedType != spv::NoResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003084 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
Cody Northrop4d2298b2020-04-13 21:59:49 -06003085
3086 for (unsigned int i = 0; i < temporaryLvalues.size(); ++i) {
3087 builder.setAccessChain(complexLvalues[i]);
John Kessenich435dd802020-06-30 01:27:08 -06003088 builder.accessChainStore(builder.createLoad(temporaryLvalues[i], spv::NoPrecision));
John Kessenichbbbd9a22020-03-03 07:21:37 -07003089 }
John Kessenich140f3df2015-06-26 16:58:36 -06003090 }
3091
3092 if (noReturnValue)
3093 return false;
3094
3095 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04003096 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07003097 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06003098 } else {
3099 builder.clearAccessChain();
3100 builder.setAccessChainRValue(result);
3101 return false;
3102 }
3103}
3104
John Kessenich433e9ff2017-01-26 20:31:11 -07003105// This path handles both if-then-else and ?:
3106// The if-then-else has a node type of void, while
3107// ?: has either a void or a non-void node type
3108//
3109// Leaving the result, when not void:
3110// GLSL only has r-values as the result of a :?, but
3111// if we have an l-value, that can be more efficient if it will
3112// become the base of a complex r-value expression, because the
3113// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06003114bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
3115{
John Kessenich0c1e71a2019-01-10 18:23:06 +07003116 // see if OpSelect can handle it
3117 const auto isOpSelectable = [&]() {
3118 if (node->getBasicType() == glslang::EbtVoid)
3119 return false;
3120 // OpSelect can do all other types starting with SPV 1.4
3121 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
3122 // pre-1.4, only scalars and vectors can be handled
3123 if ((!node->getType().isScalar() && !node->getType().isVector()))
3124 return false;
3125 }
3126 return true;
3127 };
3128
John Kessenich4bee5312018-02-20 21:29:05 -07003129 // See if it simple and safe, or required, to execute both sides.
3130 // Crucially, side effects must be either semantically required or avoided,
3131 // and there are performance trade-offs.
3132 // Return true if required or a good idea (and safe) to execute both sides,
3133 // false otherwise.
3134 const auto bothSidesPolicy = [&]() -> bool {
3135 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07003136 if (node->getTrueBlock() == nullptr ||
3137 node->getFalseBlock() == nullptr)
3138 return false;
3139
John Kessenich4bee5312018-02-20 21:29:05 -07003140 // required? (unless we write additional code to look for side effects
3141 // and make performance trade-offs if none are present)
3142 if (!node->getShortCircuit())
3143 return true;
3144
3145 // if not required to execute both, decide based on performance/practicality...
3146
John Kessenich0c1e71a2019-01-10 18:23:06 +07003147 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07003148 return false;
3149
John Kessenich433e9ff2017-01-26 20:31:11 -07003150 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
3151 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
3152
3153 // return true if a single operand to ? : is okay for OpSelect
3154 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003155 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07003156 };
3157
3158 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
3159 operandOkay(node->getFalseBlock()->getAsTyped());
3160 };
3161
John Kessenich4bee5312018-02-20 21:29:05 -07003162 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
3163 // emit the condition before doing anything with selection
3164 node->getCondition()->traverse(this);
3165 spv::Id condition = accessChainLoad(node->getCondition()->getType());
3166
3167 // Find a way of executing both sides and selecting the right result.
3168 const auto executeBothSides = [&]() -> void {
3169 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07003170 node->getTrueBlock()->traverse(this);
3171 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3172 node->getFalseBlock()->traverse(this);
3173 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3174
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003175 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003176
John Kessenich4bee5312018-02-20 21:29:05 -07003177 // done if void
3178 if (node->getBasicType() == glslang::EbtVoid)
3179 return;
John Kesseniche434ad92017-03-30 10:09:28 -06003180
John Kessenich4bee5312018-02-20 21:29:05 -07003181 // emit code to select between trueValue and falseValue
3182
3183 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07003184 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07003185 // Emit OpSelect for this selection.
3186
3187 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07003188 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
3189 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07003190 condition = builder.smearScalar(spv::NoPrecision, condition,
3191 builder.makeVectorType(builder.makeBoolType(),
3192 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07003193 }
John Kessenich4bee5312018-02-20 21:29:05 -07003194
3195 // OpSelect
3196 result = builder.createTriOp(spv::OpSelect,
3197 convertGlslangToSpvType(node->getType()), condition,
3198 trueValue, falseValue);
3199
3200 builder.clearAccessChain();
3201 builder.setAccessChainRValue(result);
3202 } else {
3203 // We need control flow to select the result.
3204 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
John Kessenich435dd802020-06-30 01:27:08 -06003205 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()),
3206 spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich4bee5312018-02-20 21:29:05 -07003207
3208 // Selection control:
3209 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3210
3211 // make an "if" based on the value created by the condition
3212 spv::Builder::If ifBuilder(condition, control, builder);
3213
3214 // emit the "then" statement
3215 builder.createStore(trueValue, result);
3216 ifBuilder.makeBeginElse();
3217 // emit the "else" statement
3218 builder.createStore(falseValue, result);
3219
3220 // finish off the control flow
3221 ifBuilder.makeEndIf();
3222
3223 builder.clearAccessChain();
3224 builder.setAccessChainLValue(result);
3225 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003226 };
3227
John Kessenich4bee5312018-02-20 21:29:05 -07003228 // Execute the one side needed, as per the condition
3229 const auto executeOneSide = [&]() {
3230 // Always emit control flow.
John Kessenich435dd802020-06-30 01:27:08 -06003231 if (node->getBasicType() != glslang::EbtVoid) {
3232 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()), spv::StorageClassFunction,
3233 convertGlslangToSpvType(node->getType()));
3234 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003235
John Kessenich4bee5312018-02-20 21:29:05 -07003236 // Selection control:
3237 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3238
3239 // make an "if" based on the value created by the condition
3240 spv::Builder::If ifBuilder(condition, control, builder);
3241
3242 // emit the "then" statement
3243 if (node->getTrueBlock() != nullptr) {
3244 node->getTrueBlock()->traverse(this);
3245 if (result != spv::NoResult)
3246 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3247 }
3248
3249 if (node->getFalseBlock() != nullptr) {
3250 ifBuilder.makeBeginElse();
3251 // emit the "else" statement
3252 node->getFalseBlock()->traverse(this);
3253 if (result != spv::NoResult)
3254 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3255 }
3256
3257 // finish off the control flow
3258 ifBuilder.makeEndIf();
3259
3260 if (result != spv::NoResult) {
3261 builder.clearAccessChain();
3262 builder.setAccessChainLValue(result);
3263 }
3264 };
3265
3266 // Try for OpSelect (or a requirement to execute both sides)
3267 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003268 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3269 if (node->getType().getQualifier().isSpecConstant())
3270 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003271 executeBothSides();
3272 } else
3273 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003274
3275 return false;
3276}
3277
3278bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3279{
3280 // emit and get the condition before doing anything with switch
3281 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003282 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003283
Rex Xu57e65922017-07-04 23:23:40 +08003284 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003285 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003286
John Kessenich140f3df2015-06-26 16:58:36 -06003287 // browse the children to sort out code segments
3288 int defaultSegment = -1;
3289 std::vector<TIntermNode*> codeSegments;
3290 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3291 std::vector<int> caseValues;
3292 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3293 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3294 TIntermNode* child = *c;
3295 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003296 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003297 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003298 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich8985fc92020-03-03 10:25:07 -07003299 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()
3300 ->getConstArray()[0].getIConst());
John Kessenich140f3df2015-06-26 16:58:36 -06003301 } else
3302 codeSegments.push_back(child);
3303 }
3304
qining25262b32016-05-06 17:25:16 -04003305 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003306 // statements between the last case and the end of the switch statement
3307 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3308 (int)codeSegments.size() == defaultSegment)
3309 codeSegments.push_back(nullptr);
3310
3311 // make the switch statement
3312 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
John Kessenich8985fc92020-03-03 10:25:07 -07003313 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment,
3314 segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003315
3316 // emit all the code in the segments
3317 breakForLoop.push(false);
3318 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3319 builder.nextSwitchSegment(segmentBlocks, s);
3320 if (codeSegments[s])
3321 codeSegments[s]->traverse(this);
3322 else
3323 builder.addSwitchBreak();
3324 }
3325 breakForLoop.pop();
3326
3327 builder.endSwitch(segmentBlocks);
3328
3329 return false;
3330}
3331
3332void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3333{
3334 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003335 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003336
3337 builder.clearAccessChain();
3338 builder.setAccessChainRValue(constant);
3339}
3340
3341bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3342{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003343 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003344 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003345
3346 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003347 std::vector<unsigned int> operands;
3348 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003349
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003350 // Spec requires back edges to target header blocks, and every header block
3351 // must dominate its merge block. Make a header block first to ensure these
3352 // conditions are met. By definition, it will contain OpLoopMerge, followed
3353 // by a block-ending branch. But we don't want to put any other body/test
3354 // instructions in it, since the body/test may have arbitrary instructions,
3355 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003356 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003357 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003358 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003359 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003360 spv::Block& test = builder.makeNewBlock();
3361 builder.createBranch(&test);
3362
3363 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003364 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003365 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003366 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3367
3368 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003369 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003370 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003371 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003372 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003373 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003374
3375 builder.setBuildPoint(&blocks.continue_target);
3376 if (node->getTerminal())
3377 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003378 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003379 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003380 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003381 builder.createBranch(&blocks.body);
3382
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003383 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003384 builder.setBuildPoint(&blocks.body);
3385 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003386 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003387 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003388 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003389
3390 builder.setBuildPoint(&blocks.continue_target);
3391 if (node->getTerminal())
3392 node->getTerminal()->traverse(this);
3393 if (node->getTest()) {
3394 node->getTest()->traverse(this);
3395 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003396 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003397 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003398 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003399 // TODO: unless there was a break/return/discard instruction
3400 // somewhere in the body, this is an infinite loop, so we should
3401 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003402 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003403 }
John Kessenich140f3df2015-06-26 16:58:36 -06003404 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003405 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003406 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003407 return false;
3408}
3409
3410bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3411{
3412 if (node->getExpression())
3413 node->getExpression()->traverse(this);
3414
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003415 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003416
John Kessenich140f3df2015-06-26 16:58:36 -06003417 switch (node->getFlowOp()) {
3418 case glslang::EOpKill:
3419 builder.makeDiscard();
3420 break;
3421 case glslang::EOpBreak:
3422 if (breakForLoop.top())
3423 builder.createLoopExit();
3424 else
3425 builder.addSwitchBreak();
3426 break;
3427 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003428 builder.createLoopContinue();
3429 break;
3430 case glslang::EOpReturn:
John Kessenich435dd802020-06-30 01:27:08 -06003431 if (node->getExpression() != nullptr) {
John Kesseniched33e052016-10-06 12:59:51 -06003432 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3433 spv::Id returnId = accessChainLoad(glslangReturnType);
John Kessenich435dd802020-06-30 01:27:08 -06003434 if (builder.getTypeId(returnId) != currentFunction->getReturnType() ||
3435 TranslatePrecisionDecoration(glslangReturnType) != currentFunction->getReturnPrecision()) {
John Kesseniched33e052016-10-06 12:59:51 -06003436 builder.clearAccessChain();
John Kessenich435dd802020-06-30 01:27:08 -06003437 spv::Id copyId = builder.createVariable(currentFunction->getReturnPrecision(),
3438 spv::StorageClassFunction, currentFunction->getReturnType());
John Kesseniched33e052016-10-06 12:59:51 -06003439 builder.setAccessChainLValue(copyId);
3440 multiTypeStore(glslangReturnType, returnId);
John Kessenich435dd802020-06-30 01:27:08 -06003441 returnId = builder.createLoad(copyId, currentFunction->getReturnPrecision());
John Kesseniched33e052016-10-06 12:59:51 -06003442 }
3443 builder.makeReturn(false, returnId);
3444 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003445 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003446
3447 builder.clearAccessChain();
3448 break;
3449
John Kessenichb9197c82019-08-11 07:41:45 -06003450#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003451 case glslang::EOpDemote:
3452 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3453 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3454 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3455 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003456#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003457
John Kessenich140f3df2015-06-26 16:58:36 -06003458 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003459 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003460 break;
3461 }
3462
3463 return false;
3464}
3465
John Kessenich9c14f772019-06-17 08:38:35 -06003466spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003467{
qining25262b32016-05-06 17:25:16 -04003468 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003469 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003470 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003471 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003472 spv::Id result = createSpvConstant(*node);
3473 if (result != spv::NoResult)
3474 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003475 }
3476
3477 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003478 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003479 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3480 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003481
John Kessenichb9197c82019-08-11 07:41:45 -06003482 const bool contains16BitType = node->getType().contains16BitFloat() ||
3483 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003484 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003485 switch (storageClass) {
3486 case spv::StorageClassInput:
3487 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003488 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003489 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003490 break;
John Kessenich18310872018-05-14 22:08:53 -06003491 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003492 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003493 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3494 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003495 else
3496 builder.addCapability(spv::CapabilityStorageUniform16);
3497 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003498#ifndef GLSLANG_WEB
3499 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003500 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003501 builder.addCapability(spv::CapabilityStoragePushConstant16);
3502 break;
John Kessenich18310872018-05-14 22:08:53 -06003503 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003504 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003505 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003506 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3507 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003508#endif
John Kessenich18310872018-05-14 22:08:53 -06003509 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003510 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003511 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003512 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003513 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003514 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003515 }
3516 }
Rex Xuf89ad982017-04-07 23:22:33 +08003517
John Kessenichb9197c82019-08-11 07:41:45 -06003518 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003519 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003520 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003521 builder.addCapability(spv::CapabilityStoragePushConstant8);
3522 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003523 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003524 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003525 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003526 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003527 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003528 } else {
3529 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003530 }
3531 }
3532
John Kessenich140f3df2015-06-26 16:58:36 -06003533 const char* name = node->getName().c_str();
3534 if (glslang::IsAnonymous(name))
3535 name = "";
3536
Alejandro Piñeiroff6dcca2020-06-04 09:39:31 +02003537 spv::Id initializer = spv::NoResult;
3538
3539 if (node->getType().getQualifier().storage == glslang::EvqUniform &&
3540 !node->getConstArray().empty()) {
3541 int nextConst = 0;
3542 initializer = createSpvConstantFromConstUnionArray(node->getType(),
3543 node->getConstArray(),
3544 nextConst,
3545 false /* specConst */);
3546 }
3547
John Kessenich435dd802020-06-30 01:27:08 -06003548 return builder.createVariable(spv::NoPrecision, storageClass, spvType, name, initializer);
John Kessenich140f3df2015-06-26 16:58:36 -06003549}
3550
3551// Return type Id of the sampled type.
3552spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3553{
3554 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003555 case glslang::EbtInt: return builder.makeIntType(32);
3556 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003557 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003558#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003559 case glslang::EbtFloat16:
3560 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3561 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3562 return builder.makeFloatType(16);
3563#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003564 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003565 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003566 return builder.makeFloatType(32);
3567 }
3568}
3569
John Kessenich8c8505c2016-07-26 12:50:38 -06003570// If node is a swizzle operation, return the type that should be used if
3571// the swizzle base is first consumed by another operation, before the swizzle
3572// is applied.
3573spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3574{
John Kessenichecba76f2017-01-06 00:34:48 -07003575 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003576 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3577 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3578 else
3579 return spv::NoType;
3580}
3581
3582// When inverting a swizzle with a parent op, this function
3583// will apply the swizzle operation to a completed parent operation.
John Kessenich8985fc92020-03-03 10:25:07 -07003584spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
3585 spv::Id parentResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003586{
3587 std::vector<unsigned> swizzle;
3588 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3589 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3590}
3591
John Kessenich8c8505c2016-07-26 12:50:38 -06003592// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3593void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3594{
3595 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3596 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3597 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3598}
3599
John Kessenich3ac051e2015-12-20 11:29:16 -07003600// Convert from a glslang type to an SPV type, by calling into a
3601// recursive version of this function. This establishes the inherited
3602// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003603spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003604{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003605 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003606}
3607
3608// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003609// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003610// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003611spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003612 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3613 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003614{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003615 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003616
3617 switch (type.getBasicType()) {
3618 case glslang::EbtVoid:
3619 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003620 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003621 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003622 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003623 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3624 // a 32-bit int where non-0 means true.
3625 if (explicitLayout != glslang::ElpNone)
3626 spvType = builder.makeUintType(32);
3627 else
3628 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003629 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003630 case glslang::EbtInt:
3631 spvType = builder.makeIntType(32);
3632 break;
3633 case glslang::EbtUint:
3634 spvType = builder.makeUintType(32);
3635 break;
3636 case glslang::EbtFloat:
3637 spvType = builder.makeFloatType(32);
3638 break;
3639#ifndef GLSLANG_WEB
3640 case glslang::EbtDouble:
3641 spvType = builder.makeFloatType(64);
3642 break;
3643 case glslang::EbtFloat16:
3644 spvType = builder.makeFloatType(16);
3645 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003646 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003647 spvType = builder.makeIntType(8);
3648 break;
3649 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003650 spvType = builder.makeUintType(8);
3651 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003652 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003653 spvType = builder.makeIntType(16);
3654 break;
3655 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003656 spvType = builder.makeUintType(16);
3657 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003658 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003659 spvType = builder.makeIntType(64);
3660 break;
3661 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003662 spvType = builder.makeUintType(64);
3663 break;
John Kessenich426394d2015-07-23 10:22:48 -06003664 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003665 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003666 spvType = builder.makeUintType(32);
3667 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04003668 case glslang::EbtAccStruct:
3669 spvType = builder.makeAccelerationStructureType();
Chao Chenb50c02e2018-09-19 11:42:24 -07003670 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04003671 case glslang::EbtRayQuery:
3672 spvType = builder.makeRayQueryType();
3673 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003674 case glslang::EbtReference:
3675 {
3676 // Make the forward pointer, then recurse to convert the structure type, then
3677 // patch up the forward pointer with a real pointer type.
3678 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3679 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3680 forwardPointers[type.getReferentType()] = forwardId;
3681 }
3682 spvType = forwardPointers[type.getReferentType()];
3683 if (!forwardReferenceOnly) {
3684 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3685 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3686 forwardPointers[type.getReferentType()],
3687 referentType);
3688 }
3689 }
3690 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003691#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003692 case glslang::EbtSampler:
3693 {
3694 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003695 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003696 spvType = builder.makeSamplerType();
3697 } else {
3698 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003699 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3700 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3701 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3702 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003703 // already has both image and sampler, make the combined type
3704 spvType = builder.makeSampledImageType(spvType);
3705 }
John Kessenich55e7d112015-11-15 21:33:39 -07003706 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003707 }
John Kessenich140f3df2015-06-26 16:58:36 -06003708 break;
3709 case glslang::EbtStruct:
3710 case glslang::EbtBlock:
3711 {
3712 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003713 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003714
3715 // Try to share structs for different layouts, but not yet for other
3716 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003717 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003718 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003719 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003720 break;
3721
3722 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003723 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003724 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003725 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003726 }
3727 break;
Jeff Bolz04d73732019-05-31 13:06:01 -05003728 case glslang::EbtString:
3729 // no type used for OpString
3730 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003731 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003732 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003733 break;
3734 }
3735
3736 if (type.isMatrix())
3737 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3738 else {
3739 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3740 if (type.getVectorSize() > 1)
3741 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3742 }
3743
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003744 if (type.isCoopMat()) {
3745 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3746 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3747 if (type.getBasicType() == glslang::EbtFloat16)
3748 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003749 if (type.getBasicType() == glslang::EbtUint8 ||
3750 type.getBasicType() == glslang::EbtInt8) {
3751 builder.addCapability(spv::CapabilityInt8);
3752 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003753
3754 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3755 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3756 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3757
3758 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3759 }
3760
John Kessenich140f3df2015-06-26 16:58:36 -06003761 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003762 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3763
John Kessenichc9a80832015-09-12 12:17:44 -06003764 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003765 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003766 // We need to decorate array strides for types needing explicit layout, except blocks.
3767 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003768 // Use a dummy glslang type for querying internal strides of
3769 // arrays of arrays, but using just a one-dimensional array.
3770 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003771 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3772 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003773
3774 // Will compute the higher-order strides here, rather than making a whole
3775 // pile of types and doing repetitive recursion on their contents.
3776 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3777 }
John Kessenichf8842e52016-01-04 19:22:56 -07003778
3779 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003780 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003781 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003782 if (stride > 0)
3783 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003784 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003785 }
3786 } else {
3787 // single-dimensional array, and don't yet have stride
3788
John Kessenichf8842e52016-01-04 19:22:56 -07003789 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003790 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3791 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003792 }
John Kessenich31ed4832015-09-09 17:51:38 -06003793
John Kessenichead86222018-03-28 18:01:20 -06003794 // Do the outer dimension, which might not be known for a runtime-sized array.
3795 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3796 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003797 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003798 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003799#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003800 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003801 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003802 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3803 }
John Kessenichb9197c82019-08-11 07:41:45 -06003804#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003805 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003806 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003807 if (stride > 0)
3808 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003809 }
3810
3811 return spvType;
3812}
3813
John Kessenich0e737842017-03-24 18:38:16 -06003814// TODO: this functionality should exist at a higher level, in creating the AST
3815//
3816// Identify interface members that don't have their required extension turned on.
3817//
3818bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3819{
John Kessenicha28f7a72019-08-06 07:00:58 -06003820#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003821 auto& extensions = glslangIntermediate->getRequestedExtensions();
3822
Rex Xubcf291a2017-03-29 23:01:36 +08003823 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3824 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3825 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003826 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3827 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3828 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003829
3830 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3831 if (member.getFieldName() == "gl_ViewportMask" &&
3832 extensions.find("GL_NV_viewport_array2") == extensions.end())
3833 return true;
3834 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3835 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3836 return true;
3837 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3838 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3839 return true;
3840 }
3841#endif
John Kessenich0e737842017-03-24 18:38:16 -06003842
3843 return false;
3844};
3845
John Kessenich6090df02016-06-30 21:18:02 -06003846// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3847// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3848// Mutually recursive with convertGlslangToSpvType().
3849spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3850 const glslang::TTypeList* glslangMembers,
3851 glslang::TLayoutPacking explicitLayout,
3852 const glslang::TQualifier& qualifier)
3853{
3854 // Create a vector of struct types for SPIR-V to consume
3855 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07003856 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
3857 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003858 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003859 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3860 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3861 if (glslangMember.hiddenMember()) {
3862 ++memberDelta;
3863 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003864 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06003865 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003866 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003867 if (filterMember(glslangMember)) {
3868 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08003869 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003870 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003871 }
Roy05a5b532020-01-03 16:21:34 +08003872 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003873 }
John Kessenich6090df02016-06-30 21:18:02 -06003874 // modify just this child's view of the qualifier
3875 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3876 InheritQualifiers(memberQualifier, qualifier);
3877
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003878 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003879 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003880 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003881
3882 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003883 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3884 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003885
3886 // Make forward pointers for any pointer members, and create a list of members to
3887 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003888 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003889 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3890 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3891 }
3892 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003893 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3894 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003895 } else {
3896 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003897 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3898 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003899 }
John Kessenich6090df02016-06-30 21:18:02 -06003900 }
3901 }
3902
3903 // Make the SPIR-V type
3904 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003905 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003906 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3907
3908 // Decorate it
3909 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3910
John Kessenichd72f4882019-01-16 14:55:37 +07003911 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003912 auto it = deferredForwardPointers[i];
3913 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3914 }
3915
John Kessenich6090df02016-06-30 21:18:02 -06003916 return spvType;
3917}
3918
3919void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3920 const glslang::TTypeList* glslangMembers,
3921 glslang::TLayoutPacking explicitLayout,
3922 const glslang::TQualifier& qualifier,
3923 spv::Id spvType)
3924{
3925 // Name and decorate the non-hidden members
3926 int offset = -1;
3927 int locationOffset = 0; // for use within the members of this struct
3928 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3929 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3930 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003931 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08003932 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06003933 if (filterMember(glslangMember))
3934 continue;
3935 }
John Kessenich6090df02016-06-30 21:18:02 -06003936
3937 // modify just this child's view of the qualifier
3938 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3939 InheritQualifiers(memberQualifier, qualifier);
3940
3941 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003942 if (member < 0)
3943 continue;
3944
3945 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3946 builder.addMemberDecoration(spvType, member,
3947 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3948 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3949 // Add interpolation and auxiliary storage decorations only to
3950 // top-level members of Input and Output storage classes
3951 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3952 type.getQualifier().storage == glslang::EvqVaryingOut) {
3953 if (type.getBasicType() == glslang::EbtBlock ||
3954 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3955 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3956 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003957#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003958 addMeshNVDecoration(spvType, member, memberQualifier);
3959#endif
John Kessenich6090df02016-06-30 21:18:02 -06003960 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003961 }
3962 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003963
John Kessenichb9197c82019-08-11 07:41:45 -06003964#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003965 if (type.getBasicType() == glslang::EbtBlock &&
3966 qualifier.storage == glslang::EvqBuffer) {
3967 // Add memory decorations only to top-level members of shader storage block
3968 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003969 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003970 for (unsigned int i = 0; i < memory.size(); ++i)
3971 builder.addMemberDecoration(spvType, member, memory[i]);
3972 }
John Kessenichf8d1d742019-10-21 06:55:11 -06003973
John Kessenichb9197c82019-08-11 07:41:45 -06003974#endif
John Kessenich6090df02016-06-30 21:18:02 -06003975
John Kessenich5d610ee2018-03-07 18:05:55 -07003976 // Location assignment was already completed correctly by the front end,
3977 // just track whether a member needs to be decorated.
3978 // Ignore member locations if the container is an array, as that's
3979 // ill-specified and decisions have been made to not allow this.
3980 if (! type.isArray() && memberQualifier.hasLocation())
3981 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003982
John Kessenich5d610ee2018-03-07 18:05:55 -07003983 if (qualifier.hasLocation()) // track for upcoming inheritance
3984 locationOffset += glslangIntermediate->computeTypeLocationSize(
3985 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003986
John Kessenich5d610ee2018-03-07 18:05:55 -07003987 // component, XFB, others
3988 if (glslangMember.getQualifier().hasComponent())
3989 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3990 glslangMember.getQualifier().layoutComponent);
3991 if (glslangMember.getQualifier().hasXfbOffset())
3992 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3993 glslangMember.getQualifier().layoutXfbOffset);
3994 else if (explicitLayout != glslang::ElpNone) {
3995 // figure out what to do with offset, which is accumulating
3996 int nextOffset;
3997 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3998 if (offset >= 0)
3999 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
4000 offset = nextOffset;
4001 }
John Kessenich6090df02016-06-30 21:18:02 -06004002
John Kessenich5d610ee2018-03-07 18:05:55 -07004003 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
4004 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
4005 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06004006
John Kessenich5d610ee2018-03-07 18:05:55 -07004007 // built-in variable decorations
4008 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
4009 if (builtIn != spv::BuiltInMax)
4010 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08004011
John Kessenichb9197c82019-08-11 07:41:45 -06004012#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06004013 // nonuniform
4014 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
4015
John Kessenichead86222018-03-28 18:01:20 -06004016 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
4017 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
4018 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
4019 memberQualifier.semanticName);
4020 }
4021
John Kessenich5d610ee2018-03-07 18:05:55 -07004022 if (builtIn == spv::BuiltInLayer) {
4023 // SPV_NV_viewport_array2 extension
4024 if (glslangMember.getQualifier().layoutViewportRelative){
4025 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
4026 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4027 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08004028 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004029 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
4030 builder.addMemberDecoration(spvType, member,
4031 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
4032 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
4033 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4034 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08004035 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004036 }
4037 if (glslangMember.getQualifier().layoutPassthrough) {
4038 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
4039 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
4040 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4041 }
chaoc771d89f2017-01-13 01:10:53 -08004042#endif
John Kessenich6090df02016-06-30 21:18:02 -06004043 }
4044
4045 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07004046 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
4047 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06004048}
4049
John Kessenich6c292d32016-02-15 20:58:50 -07004050// Turn the expression forming the array size into an id.
4051// This is not quite trivial, because of specialization constants.
4052// Sometimes, a raw constant is turned into an Id, and sometimes
4053// a specialization constant expression is.
4054spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
4055{
4056 // First, see if this is sized with a node, meaning a specialization constant:
4057 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
4058 if (specNode != nullptr) {
4059 builder.clearAccessChain();
4060 specNode->traverse(this);
4061 return accessChainLoad(specNode->getAsTyped()->getType());
4062 }
qining25262b32016-05-06 17:25:16 -04004063
John Kessenich6c292d32016-02-15 20:58:50 -07004064 // Otherwise, need a compile-time (front end) size, get it:
4065 int size = arraySizes.getDimSize(dim);
4066 assert(size > 0);
4067 return builder.makeUintConstant(size);
4068}
4069
John Kessenich103bef92016-02-08 21:38:15 -07004070// Wrap the builder's accessChainLoad to:
4071// - localize handling of RelaxedPrecision
4072// - use the SPIR-V inferred type instead of another conversion of the glslang type
4073// (avoids unnecessary work and possible type punning for structures)
4074// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07004075spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
4076{
John Kessenich103bef92016-02-08 21:38:15 -07004077 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004078
4079 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4080 coherentFlags |= TranslateCoherent(type);
4081
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004082 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004083 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004084
John Kessenich5611c6d2018-04-05 11:25:02 -06004085 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
John Kessenich8985fc92020-03-03 10:25:07 -07004086 TranslateNonUniformDecoration(type.getQualifier()),
4087 nominalTypeId,
4088 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
4089 TranslateMemoryScope(coherentFlags),
4090 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07004091
4092 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08004093 if (type.getBasicType() == glslang::EbtBool) {
4094 if (builder.isScalarType(nominalTypeId)) {
4095 // Conversion for bool
4096 spv::Id boolType = builder.makeBoolType();
4097 if (nominalTypeId != boolType)
4098 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
4099 } else if (builder.isVectorType(nominalTypeId)) {
4100 // Conversion for bvec
4101 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4102 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
4103 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07004104 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
4105 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004106 }
4107 }
John Kessenich103bef92016-02-08 21:38:15 -07004108
4109 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07004110}
4111
Rex Xu27253232016-02-23 17:51:09 +08004112// Wrap the builder's accessChainStore to:
4113// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06004114//
4115// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08004116void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
4117{
4118 // Need to convert to abstract types when necessary
4119 if (type.getBasicType() == glslang::EbtBool) {
4120 spv::Id nominalTypeId = builder.accessChainGetInferredType();
4121
4122 if (builder.isScalarType(nominalTypeId)) {
4123 // Conversion for bool
4124 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06004125 if (nominalTypeId != boolType) {
4126 // keep these outside arguments, for determinant order-of-evaluation
4127 spv::Id one = builder.makeUintConstant(1);
4128 spv::Id zero = builder.makeUintConstant(0);
4129 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
4130 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06004131 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08004132 } else if (builder.isVectorType(nominalTypeId)) {
4133 // Conversion for bvec
4134 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4135 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06004136 if (nominalTypeId != bvecType) {
4137 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06004138 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
4139 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
4140 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06004141 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06004142 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
4143 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004144 }
4145 }
4146
Jeff Bolz36831c92018-09-05 10:11:41 -05004147 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4148 coherentFlags |= TranslateCoherent(type);
4149
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004150 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004151 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004152
Jeff Bolz36831c92018-09-05 10:11:41 -05004153 builder.accessChainStore(rvalue,
John Kessenich8985fc92020-03-03 10:25:07 -07004154 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
4155 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004156 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08004157}
4158
John Kessenich4bf71552016-09-02 11:20:21 -06004159// For storing when types match at the glslang level, but not might match at the
4160// SPIR-V level.
4161//
4162// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004163// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004164// as in a member-decorated way.
4165//
4166// NOTE: This function can handle any store request; if it's not special it
4167// simplifies to a simple OpStore.
4168//
4169// Implicitly uses the existing builder.accessChain as the storage target.
4170void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4171{
John Kessenichb3e24e42016-09-11 12:33:43 -06004172 // we only do the complex path here if it's an aggregate
4173 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004174 accessChainStore(type, rValue);
4175 return;
4176 }
4177
John Kessenichb3e24e42016-09-11 12:33:43 -06004178 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004179 spv::Id rType = builder.getTypeId(rValue);
4180 spv::Id lValue = builder.accessChainGetLValue();
4181 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4182 if (lType == rType) {
4183 accessChainStore(type, rValue);
4184 return;
4185 }
4186
John Kessenichb3e24e42016-09-11 12:33:43 -06004187 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004188 // where the two types were the same type in GLSL. This requires member
4189 // by member copy, recursively.
4190
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004191 // SPIR-V 1.4 added an instruction to do help do this.
4192 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4193 // However, bool in uniform space is changed to int, so
4194 // OpCopyLogical does not work for that.
4195 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4196 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4197 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4198 if (lBool == rBool) {
4199 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4200 accessChainStore(type, logicalCopy);
4201 return;
4202 }
4203 }
4204
John Kessenichb3e24e42016-09-11 12:33:43 -06004205 // If an array, copy element by element.
4206 if (type.isArray()) {
4207 glslang::TType glslangElementType(type, 0);
4208 spv::Id elementRType = builder.getContainedTypeId(rType);
4209 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4210 // get the source member
4211 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004212
John Kessenichb3e24e42016-09-11 12:33:43 -06004213 // set up the target storage
4214 builder.clearAccessChain();
4215 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004216 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4217 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004218
John Kessenichb3e24e42016-09-11 12:33:43 -06004219 // store the member
4220 multiTypeStore(glslangElementType, elementRValue);
4221 }
4222 } else {
4223 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004224
John Kessenichb3e24e42016-09-11 12:33:43 -06004225 // loop over structure members
4226 const glslang::TTypeList& members = *type.getStruct();
4227 for (int m = 0; m < (int)members.size(); ++m) {
4228 const glslang::TType& glslangMemberType = *members[m].type;
4229
4230 // get the source member
4231 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4232 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4233
4234 // set up the target storage
4235 builder.clearAccessChain();
4236 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004237 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4238 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004239
4240 // store the member
4241 multiTypeStore(glslangMemberType, memberRValue);
4242 }
John Kessenich4bf71552016-09-02 11:20:21 -06004243 }
4244}
4245
John Kessenichf85e8062015-12-19 13:57:10 -07004246// Decide whether or not this type should be
4247// decorated with offsets and strides, and if so
4248// whether std140 or std430 rules should be applied.
4249glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004250{
John Kessenichf85e8062015-12-19 13:57:10 -07004251 // has to be a block
4252 if (type.getBasicType() != glslang::EbtBlock)
4253 return glslang::ElpNone;
4254
Chao Chen3c366992018-09-19 11:41:59 -07004255 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004256 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004257 type.getQualifier().storage != glslang::EvqBuffer &&
4258 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004259 return glslang::ElpNone;
4260
4261 // return the layout to use
4262 switch (type.getQualifier().layoutPacking) {
4263 case glslang::ElpStd140:
4264 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004265 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004266 return type.getQualifier().layoutPacking;
4267 default:
4268 return glslang::ElpNone;
4269 }
John Kessenich31ed4832015-09-09 17:51:38 -06004270}
4271
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004272// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004273int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4274 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004275{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004276 int size;
John Kessenich49987892015-12-29 17:11:44 -07004277 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004278 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4279 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004280
4281 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004282}
4283
John Kessenich49987892015-12-29 17:11:44 -07004284// 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 -07004285// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004286int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4287 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004288{
John Kessenich49987892015-12-29 17:11:44 -07004289 glslang::TType elementType;
4290 elementType.shallowCopy(matrixType);
4291 elementType.clearArraySizes();
4292
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004293 int size;
John Kessenich49987892015-12-29 17:11:44 -07004294 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004295 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4296 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004297
4298 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004299}
4300
John Kessenich5e4b1242015-08-06 22:53:06 -06004301// Given a member type of a struct, realign the current offset for it, and compute
4302// the next (not yet aligned) offset for the next member, which will get aligned
4303// on the next call.
4304// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4305// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4306// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004307void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4308 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004309{
4310 // this will get a positive value when deemed necessary
4311 nextOffset = -1;
4312
John Kessenich5e4b1242015-08-06 22:53:06 -06004313 // override anything in currentOffset with user-set offset
4314 if (memberType.getQualifier().hasOffset())
4315 currentOffset = memberType.getQualifier().layoutOffset;
4316
4317 // It could be that current linker usage in glslang updated all the layoutOffset,
4318 // in which case the following code does not matter. But, that's not quite right
4319 // once cross-compilation unit GLSL validation is done, as the original user
4320 // settings are needed in layoutOffset, and then the following will come into play.
4321
John Kessenichf85e8062015-12-19 13:57:10 -07004322 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004323 if (! memberType.getQualifier().hasOffset())
4324 currentOffset = -1;
4325
4326 return;
4327 }
4328
John Kessenichf85e8062015-12-19 13:57:10 -07004329 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004330 if (currentOffset < 0)
4331 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004332
John Kessenich5e4b1242015-08-06 22:53:06 -06004333 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4334 // but possibly not yet correctly aligned.
4335
4336 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004337 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004338 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4339 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004340
4341 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004342 // TODO: make this consistent in early phases of code:
4343 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4344 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4345 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004346 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004347 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004348 int dummySize;
4349 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4350 if (componentAlignment <= 4)
4351 memberAlignment = componentAlignment;
4352 }
4353
4354 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004355 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004356
4357 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004358 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4359 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004360 glslang::RoundToPow2(currentOffset, 16);
4361
John Kessenich5e4b1242015-08-06 22:53:06 -06004362 nextOffset = currentOffset + memberSize;
4363}
4364
David Netoa901ffe2016-06-08 14:11:40 +01004365void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004366{
David Netoa901ffe2016-06-08 14:11:40 +01004367 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4368 switch (glslangBuiltIn)
4369 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004370 case glslang::EbvPointSize:
4371#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004372 case glslang::EbvClipDistance:
4373 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004374 case glslang::EbvViewportMaskNV:
4375 case glslang::EbvSecondaryPositionNV:
4376 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004377 case glslang::EbvPositionPerViewNV:
4378 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004379 case glslang::EbvTaskCountNV:
4380 case glslang::EbvPrimitiveCountNV:
4381 case glslang::EbvPrimitiveIndicesNV:
4382 case glslang::EbvClipDistancePerViewNV:
4383 case glslang::EbvCullDistancePerViewNV:
4384 case glslang::EbvLayerPerViewNV:
4385 case glslang::EbvMeshViewCountNV:
4386 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004387#endif
David Netoa901ffe2016-06-08 14:11:40 +01004388 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4389 // Alternately, we could just call this for any glslang built-in, since the
4390 // capability already guards against duplicates.
4391 TranslateBuiltInDecoration(glslangBuiltIn, false);
4392 break;
4393 default:
4394 // Capabilities were already generated when the struct was declared.
4395 break;
4396 }
John Kessenichebb50532016-05-16 19:22:05 -06004397}
4398
John Kessenich6fccb3c2016-09-19 16:01:41 -06004399bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004400{
John Kessenicheee9d532016-09-19 18:09:30 -06004401 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004402}
4403
John Kessenichd41993d2017-09-10 15:21:05 -06004404// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004405// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4406// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004407bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004408{
John Kessenich6a14f782017-12-04 02:48:10 -07004409 assert(qualifier == glslang::EvqIn ||
4410 qualifier == glslang::EvqOut ||
4411 qualifier == glslang::EvqInOut ||
rdbd8edfd82020-06-02 08:30:07 +02004412 qualifier == glslang::EvqUniform ||
John Kessenich6a14f782017-12-04 02:48:10 -07004413 qualifier == glslang::EvqConstReadOnly);
rdbd8edfd82020-06-02 08:30:07 +02004414 return qualifier != glslang::EvqConstReadOnly &&
4415 qualifier != glslang::EvqUniform;
John Kessenichd41993d2017-09-10 15:21:05 -06004416}
4417
4418// Is parameter pass-by-original?
4419bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4420 bool implicitThisParam)
4421{
4422 if (implicitThisParam) // implicit this
4423 return true;
4424 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004425 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004426 return paramType.containsOpaque() || // sampler, etc.
4427 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4428}
4429
John Kessenich140f3df2015-06-26 16:58:36 -06004430// Make all the functions, skeletally, without actually visiting their bodies.
4431void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4432{
John Kessenich8985fc92020-03-03 10:25:07 -07004433 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4434 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004435 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4436 if (paramPrecision != spv::NoPrecision)
4437 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004438 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004439 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004440 // Original and non-writable params pass the pointer directly and
4441 // use restrict/aliased, others are stored to a pointer in Function
4442 // memory and use RestrictPointer/AliasedPointer.
4443 if (originalParam(type.getQualifier().storage, type, false) ||
4444 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004445 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4446 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004447 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004448 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4449 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004450 }
4451 }
John Kessenichfad62972017-07-18 02:35:46 -06004452 };
4453
John Kessenich140f3df2015-06-26 16:58:36 -06004454 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4455 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004456 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004457 continue;
4458
4459 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004460 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004461 //
qining25262b32016-05-06 17:25:16 -04004462 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004463 // function. What it is an address of varies:
4464 //
John Kessenich4bf71552016-09-02 11:20:21 -06004465 // - "in" parameters not marked as "const" can be written to without modifying the calling
4466 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004467 //
4468 // - "const in" parameters can just be the r-value, as no writes need occur.
4469 //
John Kessenich4bf71552016-09-02 11:20:21 -06004470 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4471 // 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 -06004472
4473 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004474 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004475 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4476
John Kessenich155d3512019-08-08 23:29:20 -06004477#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004478 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4479 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004480#else
4481 bool implicitThis = false;
4482#endif
John Kessenich37789792017-03-21 23:56:40 -06004483
John Kessenichfad62972017-07-18 02:35:46 -06004484 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004485 for (int p = 0; p < (int)parameters.size(); ++p) {
4486 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4487 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004488 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004489 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004490 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004491 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4492 else
John Kessenich4bf71552016-09-02 11:20:21 -06004493 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004494 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004495 paramTypes.push_back(typeId);
4496 }
4497
4498 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004499 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4500 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004501 glslFunction->getName().c_str(), paramTypes,
4502 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004503 if (implicitThis)
4504 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004505
4506 // Track function to emit/call later
4507 functionMap[glslFunction->getName().c_str()] = function;
4508
4509 // Set the parameter id's
4510 for (int p = 0; p < (int)parameters.size(); ++p) {
4511 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4512 // give a name too
4513 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004514
4515 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004516 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004517 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004518 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004519 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004520 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004521 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004522 }
4523 }
4524}
4525
4526// Process all the initializers, while skipping the functions and link objects
4527void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4528{
4529 builder.setBuildPoint(shaderEntry->getLastBlock());
4530 for (int i = 0; i < (int)initializers.size(); ++i) {
4531 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004532 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4533 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004534
4535 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004536 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004537 initializer->traverse(this);
4538 }
4539 }
4540}
4541
4542// Process all the functions, while skipping initializers.
4543void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4544{
4545 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4546 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004547 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004548 node->traverse(this);
4549 }
4550}
4551
4552void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4553{
qining25262b32016-05-06 17:25:16 -04004554 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004555 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004556 currentFunction = functionMap[node->getName().c_str()];
4557 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004558 builder.setBuildPoint(functionBlock);
4559}
4560
John Kessenich8985fc92020-03-03 10:25:07 -07004561void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4562 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004563{
Rex Xufc618912015-09-09 16:42:49 +08004564 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004565
4566 glslang::TSampler sampler = {};
4567 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004568#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004569 bool f16ShadowCompare = false;
4570#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004571 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004572 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4573 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004574#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004575 f16ShadowCompare = sampler.shadow &&
4576 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004577#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004578 }
4579
John Kessenich140f3df2015-06-26 16:58:36 -06004580 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4581 builder.clearAccessChain();
4582 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004583
John Kessenicha28f7a72019-08-06 07:00:58 -06004584#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004585 // Special case l-value operands
4586 bool lvalue = false;
4587 switch (node.getOp()) {
4588 case glslang::EOpImageAtomicAdd:
4589 case glslang::EOpImageAtomicMin:
4590 case glslang::EOpImageAtomicMax:
4591 case glslang::EOpImageAtomicAnd:
4592 case glslang::EOpImageAtomicOr:
4593 case glslang::EOpImageAtomicXor:
4594 case glslang::EOpImageAtomicExchange:
4595 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004596 case glslang::EOpImageAtomicLoad:
4597 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004598 if (i == 0)
4599 lvalue = true;
4600 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004601 case glslang::EOpSparseImageLoad:
4602 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4603 lvalue = true;
4604 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004605 case glslang::EOpSparseTexture:
4606 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4607 lvalue = true;
4608 break;
4609 case glslang::EOpSparseTextureClamp:
4610 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4611 lvalue = true;
4612 break;
4613 case glslang::EOpSparseTextureLod:
4614 case glslang::EOpSparseTextureOffset:
4615 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4616 lvalue = true;
4617 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004618 case glslang::EOpSparseTextureFetch:
4619 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4620 lvalue = true;
4621 break;
4622 case glslang::EOpSparseTextureFetchOffset:
4623 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4624 lvalue = true;
4625 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004626 case glslang::EOpSparseTextureLodOffset:
4627 case glslang::EOpSparseTextureGrad:
4628 case glslang::EOpSparseTextureOffsetClamp:
4629 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4630 lvalue = true;
4631 break;
4632 case glslang::EOpSparseTextureGradOffset:
4633 case glslang::EOpSparseTextureGradClamp:
4634 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4635 lvalue = true;
4636 break;
4637 case glslang::EOpSparseTextureGradOffsetClamp:
4638 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4639 lvalue = true;
4640 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004641 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004642 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4643 lvalue = true;
4644 break;
4645 case glslang::EOpSparseTextureGatherOffset:
4646 case glslang::EOpSparseTextureGatherOffsets:
4647 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4648 lvalue = true;
4649 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004650 case glslang::EOpSparseTextureGatherLod:
4651 if (i == 3)
4652 lvalue = true;
4653 break;
4654 case glslang::EOpSparseTextureGatherLodOffset:
4655 case glslang::EOpSparseTextureGatherLodOffsets:
4656 if (i == 4)
4657 lvalue = true;
4658 break;
Rex Xu129799a2017-07-05 17:23:28 +08004659 case glslang::EOpSparseImageLoadLod:
4660 if (i == 3)
4661 lvalue = true;
4662 break;
Chao Chen3a137962018-09-19 11:41:27 -07004663 case glslang::EOpImageSampleFootprintNV:
4664 if (i == 4)
4665 lvalue = true;
4666 break;
4667 case glslang::EOpImageSampleFootprintClampNV:
4668 case glslang::EOpImageSampleFootprintLodNV:
4669 if (i == 5)
4670 lvalue = true;
4671 break;
4672 case glslang::EOpImageSampleFootprintGradNV:
4673 if (i == 6)
4674 lvalue = true;
4675 break;
4676 case glslang::EOpImageSampleFootprintGradClampNV:
4677 if (i == 7)
4678 lvalue = true;
4679 break;
Rex Xufc618912015-09-09 16:42:49 +08004680 default:
4681 break;
4682 }
4683
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004684 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004685 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004686 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4687 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4688 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004689#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004690 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004691 }
4692}
4693
John Kessenichfc51d282015-08-19 13:34:18 -06004694void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004695{
John Kessenichfc51d282015-08-19 13:34:18 -06004696 builder.clearAccessChain();
4697 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004698 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004699}
John Kessenich140f3df2015-06-26 16:58:36 -06004700
John Kessenichfc51d282015-08-19 13:34:18 -06004701spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4702{
John Kesseniche485c7a2017-05-31 18:50:53 -06004703 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004704 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004705
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004706 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004707
John Kessenichfc51d282015-08-19 13:34:18 -06004708 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004709
John Kessenichf43c7392019-03-31 10:51:57 -06004710 const glslang::TType &imageType = node->getAsAggregate()
4711 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4712 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004713 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004714#ifdef GLSLANG_WEB
4715 const bool f16ShadowCompare = false;
4716#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004717 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004718 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4719 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004720#endif
4721
John Kessenichf43c7392019-03-31 10:51:57 -06004722 const auto signExtensionMask = [&]() {
4723 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4724 if (sampler.type == glslang::EbtUint)
4725 return spv::ImageOperandsZeroExtendMask;
4726 else if (sampler.type == glslang::EbtInt)
4727 return spv::ImageOperandsSignExtendMask;
4728 }
4729 return spv::ImageOperandsMaskNone;
4730 };
4731
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004732 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4733
John Kessenichfc51d282015-08-19 13:34:18 -06004734 std::vector<spv::Id> arguments;
4735 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004736 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004737 else
4738 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004739 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004740
4741 spv::Builder::TextureParameters params = { };
4742 params.sampler = arguments[0];
4743
Rex Xu04db3f52015-09-16 11:44:02 +08004744 glslang::TCrackedTextureOp cracked;
4745 node->crackTexture(sampler, cracked);
4746
amhagan05506bb2017-06-13 16:53:02 -04004747 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004748
John Kessenichfc51d282015-08-19 13:34:18 -06004749 // Check for queries
4750 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004751 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4752 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004753 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004754
John Kessenichfc51d282015-08-19 13:34:18 -06004755 switch (node->getOp()) {
4756 case glslang::EOpImageQuerySize:
4757 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004758 if (arguments.size() > 1) {
4759 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004760 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004761 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004762 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004763#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004764 case glslang::EOpImageQuerySamples:
4765 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004766 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004767 case glslang::EOpTextureQueryLod:
4768 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004769 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004770 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004771 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004772 case glslang::EOpSparseTexelsResident:
4773 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004774#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004775 default:
4776 assert(0);
4777 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004778 }
John Kessenich140f3df2015-06-26 16:58:36 -06004779 }
4780
LoopDawg4425f242018-02-18 11:40:01 -07004781 int components = node->getType().getVectorSize();
4782
4783 if (node->getOp() == glslang::EOpTextureFetch) {
4784 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4785 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4786 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4787 // here around e.g. which ones return scalars or other types.
4788 components = 4;
4789 }
4790
4791 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4792
4793 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4794
Rex Xufc618912015-09-09 16:42:49 +08004795 // Check for image functions other than queries
4796 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004797 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004798 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004799 spv::IdImmediate image = { true, *(opIt++) };
4800 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004801
4802 // Handle subpass operations
4803 // TODO: GLSL should change to have the "MS" only on the type rather than the
4804 // built-in function.
4805 if (cracked.subpass) {
4806 // add on the (0,0) coordinate
4807 spv::Id zero = builder.makeIntConstant(0);
4808 std::vector<spv::Id> comps;
4809 comps.push_back(zero);
4810 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004811 spv::IdImmediate coord = { true,
4812 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4813 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004814 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4815 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004816 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004817 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4818 }
4819 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004820 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004821 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004822 spv::IdImmediate imageOperand = { true, *(opIt++) };
4823 operands.push_back(imageOperand);
4824 }
John Kessenich6c292d32016-02-15 20:58:50 -07004825 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004826 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4827 builder.setPrecision(result, precision);
4828 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004829 }
4830
John Kessenich149afc32018-08-14 13:31:43 -06004831 spv::IdImmediate coord = { true, *(opIt++) };
4832 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004833 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004834 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004835 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004836 mask = mask | spv::ImageOperandsSampleMask;
4837 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004838 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004839 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4840 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004841 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004842 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004843 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4844 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004845 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004846 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004847 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4848 operands.push_back(imageOperands);
4849 }
4850 if (mask & spv::ImageOperandsSampleMask) {
4851 spv::IdImmediate imageOperand = { true, *opIt++ };
4852 operands.push_back(imageOperand);
4853 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004854 if (mask & spv::ImageOperandsLodMask) {
4855 spv::IdImmediate imageOperand = { true, *opIt++ };
4856 operands.push_back(imageOperand);
4857 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004858 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004859 spv::IdImmediate imageOperand = { true,
4860 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004861 operands.push_back(imageOperand);
4862 }
4863
John Kessenich149afc32018-08-14 13:31:43 -06004864 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004865 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004866
John Kessenich149afc32018-08-14 13:31:43 -06004867 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004868 builder.setPrecision(result[0], precision);
4869
4870 // If needed, add a conversion constructor to the proper size.
4871 if (components != node->getType().getVectorSize())
4872 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4873
4874 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004875 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004876
Jeff Bolz36831c92018-09-05 10:11:41 -05004877 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004878 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004879 spv::IdImmediate texel = { true, *(opIt + 1) };
4880 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004881 } else {
4882 spv::IdImmediate texel = { true, *opIt };
4883 operands.push_back(texel);
4884 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004885
4886 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004887 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004888 mask = mask | spv::ImageOperandsSampleMask;
4889 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004890 if (cracked.lod) {
4891 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4892 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4893 mask = mask | spv::ImageOperandsLodMask;
4894 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004895 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4896 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004897 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004898 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004899 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4900 operands.push_back(imageOperands);
4901 }
4902 if (mask & spv::ImageOperandsSampleMask) {
4903 spv::IdImmediate imageOperand = { true, *opIt++ };
4904 operands.push_back(imageOperand);
4905 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004906 if (mask & spv::ImageOperandsLodMask) {
4907 spv::IdImmediate imageOperand = { true, *opIt++ };
4908 operands.push_back(imageOperand);
4909 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004910 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004911 spv::IdImmediate imageOperand = { true,
4912 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004913 operands.push_back(imageOperand);
4914 }
4915
John Kessenich56bab042015-09-16 10:54:31 -06004916 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004917 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004918 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004919 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004920 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4921 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004922 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004923 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004924 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4925
Jeff Bolz36831c92018-09-05 10:11:41 -05004926 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004927 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004928 mask = mask | spv::ImageOperandsSampleMask;
4929 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004930 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004931 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4932 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4933
Jeff Bolz36831c92018-09-05 10:11:41 -05004934 mask = mask | spv::ImageOperandsLodMask;
4935 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004936 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4937 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004938 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004939 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004940 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004941 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004942 }
4943 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004944 spv::IdImmediate imageOperand = { true, *opIt++ };
4945 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004946 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004947 if (mask & spv::ImageOperandsLodMask) {
4948 spv::IdImmediate imageOperand = { true, *opIt++ };
4949 operands.push_back(imageOperand);
4950 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004951 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07004952 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
4953 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004954 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004955 }
4956
4957 // Create the return type that was a special structure
4958 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004959 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004960 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4961 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4962
4963 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4964
4965 // Decode the return type
4966 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4967 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004968 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004969 // Process image atomic operations
4970
4971 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4972 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004973 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004974 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004975 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004976
Jeff Bolz36831c92018-09-05 10:11:41 -05004977 spv::Id resultTypeId;
4978 // imageAtomicStore has a void return type so base the pointer type on
4979 // the type of the value operand.
4980 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08004981 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05004982 } else {
4983 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4984 }
John Kessenich56bab042015-09-16 10:54:31 -06004985 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Jeff Bolz39ffdaf2020-03-09 10:48:12 -05004986 if (imageType.getQualifier().nonUniform) {
4987 builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
4988 }
Rex Xufc618912015-09-09 16:42:49 +08004989
4990 std::vector<spv::Id> operands;
4991 operands.push_back(pointer);
4992 for (; opIt != arguments.end(); ++opIt)
4993 operands.push_back(*opIt);
4994
John Kessenich8985fc92020-03-03 10:25:07 -07004995 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
4996 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004997 }
4998 }
4999
John Kessenicha28f7a72019-08-06 07:00:58 -06005000#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04005001 // Check for fragment mask functions other than queries
5002 if (cracked.fragMask) {
5003 assert(sampler.ms);
5004
5005 auto opIt = arguments.begin();
5006 std::vector<spv::Id> operands;
5007
5008 // Extract the image if necessary
5009 if (builder.isSampledImage(params.sampler))
5010 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
5011
5012 operands.push_back(params.sampler);
5013 ++opIt;
5014
5015 if (sampler.isSubpass()) {
5016 // add on the (0,0) coordinate
5017 spv::Id zero = builder.makeIntConstant(0);
5018 std::vector<spv::Id> comps;
5019 comps.push_back(zero);
5020 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07005021 operands.push_back(builder.makeCompositeConstant(
5022 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04005023 }
5024
5025 for (; opIt != arguments.end(); ++opIt)
5026 operands.push_back(*opIt);
5027
5028 spv::Op fragMaskOp = spv::OpNop;
5029 if (node->getOp() == glslang::EOpFragmentMaskFetch)
5030 fragMaskOp = spv::OpFragmentMaskFetchAMD;
5031 else if (node->getOp() == glslang::EOpFragmentFetch)
5032 fragMaskOp = spv::OpFragmentFetchAMD;
5033
5034 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
5035 builder.addCapability(spv::CapabilityFragmentMaskAMD);
5036 return builder.createOp(fragMaskOp, resultType(), operands);
5037 }
5038#endif
5039
Rex Xufc618912015-09-09 16:42:49 +08005040 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08005041 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07005042 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005043 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08005044
John Kessenichfc51d282015-08-19 13:34:18 -06005045 // check for bias argument
5046 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08005047 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005048 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08005049 if (cracked.gather)
5050 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08005051
5052 if (f16ShadowCompare)
5053 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005054 if (cracked.offset)
5055 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08005056 else if (cracked.offsets)
5057 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005058 if (cracked.grad)
5059 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08005060 if (cracked.lodClamp)
5061 ++nonBiasArgCount;
5062 if (sparse)
5063 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07005064 if (imageFootprint)
5065 //Following three extra arguments
5066 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5067 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06005068 if ((int)arguments.size() > nonBiasArgCount)
5069 bias = true;
5070 }
5071
John Kessenicha5c33d62016-06-02 23:45:21 -06005072 // See if the sampler param should really be just the SPV image part
5073 if (cracked.fetch) {
5074 // a fetch needs to have the image extracted first
5075 if (builder.isSampledImage(params.sampler))
5076 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
5077 }
5078
John Kessenicha28f7a72019-08-06 07:00:58 -06005079#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08005080 if (cracked.gather) {
5081 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
5082 if (bias || cracked.lod ||
5083 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
5084 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08005085 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08005086 }
5087 }
5088#endif
5089
John Kessenichfc51d282015-08-19 13:34:18 -06005090 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07005091
John Kessenichfc51d282015-08-19 13:34:18 -06005092 params.coords = arguments[1];
5093 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07005094 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07005095
5096 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08005097 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005098 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08005099 ++extraArgs;
5100 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07005101 params.Dref = arguments[2];
5102 ++extraArgs;
5103 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06005104 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06005105 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06005106 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06005107 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06005108 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005109 dRefComp = builder.getNumComponents(params.coords) - 1;
5110 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07005111 params.Dref = builder.createCompositeExtract(params.coords,
5112 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06005113 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005114
5115 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06005116 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005117 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06005118 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06005119 } else if (glslangIntermediate->getStage() != EShLangFragment &&
5120 !(glslangIntermediate->getStage() == EShLangCompute &&
5121 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07005122 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
5123 noImplicitLod = true;
5124 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005125
5126 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005127 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005128 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08005129 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005130 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005131
5132 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06005133 if (cracked.grad) {
5134 params.gradX = arguments[2 + extraArgs];
5135 params.gradY = arguments[3 + extraArgs];
5136 extraArgs += 2;
5137 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005138
5139 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07005140 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06005141 params.offset = arguments[2 + extraArgs];
5142 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005143 } else if (cracked.offsets) {
5144 params.offsets = arguments[2 + extraArgs];
5145 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005146 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005147
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005148#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005149 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005150 if (cracked.lodClamp) {
5151 params.lodClamp = arguments[2 + extraArgs];
5152 ++extraArgs;
5153 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005154 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005155 if (sparse) {
5156 params.texelOut = arguments[2 + extraArgs];
5157 ++extraArgs;
5158 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005159 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005160 if (cracked.gather && ! sampler.shadow) {
5161 // default component is 0, if missing, otherwise an argument
5162 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005163 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005164 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005165 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005166 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005167 }
Chao Chen3a137962018-09-19 11:41:27 -07005168 spv::Id resultStruct = spv::NoResult;
5169 if (imageFootprint) {
5170 //Following three extra arguments
5171 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5172 params.granularity = arguments[2 + extraArgs];
5173 params.coarse = arguments[3 + extraArgs];
5174 resultStruct = arguments[4 + extraArgs];
5175 extraArgs += 3;
5176 }
5177#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005178 // bias
5179 if (bias) {
5180 params.bias = arguments[2 + extraArgs];
5181 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005182 }
John Kessenichfc51d282015-08-19 13:34:18 -06005183
John Kessenicha28f7a72019-08-06 07:00:58 -06005184#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005185 if (imageFootprint) {
5186 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5187 builder.addCapability(spv::CapabilityImageFootprintNV);
5188
5189
5190 //resultStructType(OpenGL type) contains 5 elements:
5191 //struct gl_TextureFootprint2DNV {
5192 // uvec2 anchor;
5193 // uvec2 offset;
5194 // uvec2 mask;
5195 // uint lod;
5196 // uint granularity;
5197 //};
5198 //or
5199 //struct gl_TextureFootprint3DNV {
5200 // uvec3 anchor;
5201 // uvec3 offset;
5202 // uvec2 mask;
5203 // uint lod;
5204 // uint granularity;
5205 //};
5206 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5207 assert(builder.isStructType(resultStructType));
5208
5209 //resType (SPIR-V type) contains 6 elements:
5210 //Member 0 must be a Boolean type scalar(LOD),
5211 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5212 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5213 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5214 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5215 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5216 std::vector<spv::Id> members;
5217 members.push_back(resultType());
5218 for (int i = 0; i < 5; i++) {
5219 members.push_back(builder.getContainedTypeId(resultStructType, i));
5220 }
5221 spv::Id resType = builder.makeStructType(members, "ResType");
5222
5223 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005224 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5225 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005226
5227 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5228 for (int i = 0; i < 5; i++) {
5229 builder.clearAccessChain();
5230 builder.setAccessChainLValue(resultStruct);
5231
5232 //Accessing to a struct we created, no coherent flag is set
5233 spv::Builder::AccessChain::CoherentFlags flags;
5234 flags.clear();
5235
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005236 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005237 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
5238 i+1));
Chao Chen3a137962018-09-19 11:41:27 -07005239 }
5240 return builder.createCompositeExtract(res, resultType(), 0);
5241 }
5242#endif
5243
John Kessenich65336482016-06-16 14:06:26 -06005244 // projective component (might not to move)
5245 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5246 // are divided by the last component of P."
5247 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5248 // unused components will appear after all used components."
5249 if (cracked.proj) {
5250 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5251 int projTargetComp;
5252 switch (sampler.dim) {
5253 case glslang::Esd1D: projTargetComp = 1; break;
5254 case glslang::Esd2D: projTargetComp = 2; break;
5255 case glslang::EsdRect: projTargetComp = 2; break;
5256 default: projTargetComp = projSourceComp; break;
5257 }
5258 // copy the projective coordinate if we have to
5259 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005260 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005261 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005262 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005263 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005264 }
5265 }
5266
John Kessenichf8d1d742019-10-21 06:55:11 -06005267#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005268 // nonprivate
5269 if (imageType.getQualifier().nonprivate) {
5270 params.nonprivate = true;
5271 }
5272
5273 // volatile
5274 if (imageType.getQualifier().volatil) {
5275 params.volatil = true;
5276 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005277#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005278
St0fFa1184dd2018-04-09 21:08:14 +02005279 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005280 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5281 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005282 );
LoopDawg4425f242018-02-18 11:40:01 -07005283
5284 if (components != node->getType().getVectorSize())
5285 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5286
5287 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005288}
5289
5290spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5291{
5292 // Grab the function's pointer from the previously created function
5293 spv::Function* function = functionMap[node->getName().c_str()];
5294 if (! function)
5295 return 0;
5296
5297 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5298 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5299
5300 // See comments in makeFunctions() for details about the semantics for parameter passing.
5301 //
5302 // These imply we need a four step process:
5303 // 1. Evaluate the arguments
5304 // 2. Allocate and make copies of in, out, and inout arguments
5305 // 3. Make the call
5306 // 4. Copy back the results
5307
John Kessenichd3ed90b2018-05-04 11:43:03 -06005308 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005309 std::vector<spv::Builder::AccessChain> lValues;
5310 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005311 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005312 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005313 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005314 // build l-value
5315 builder.clearAccessChain();
5316 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005317 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005318 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005319 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005320 // save l-value
5321 lValues.push_back(builder.getAccessChain());
5322 } else {
5323 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005324 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005325 }
5326 }
5327
5328 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5329 // copy the original into that space.
5330 //
5331 // Also, build up the list of actual arguments to pass in for the call
5332 int lValueCount = 0;
5333 int rValueCount = 0;
5334 std::vector<spv::Id> spvArgs;
5335 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5336 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005337 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005338 builder.setAccessChain(lValues[lValueCount]);
5339 arg = builder.accessChainGetLValue();
5340 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005341 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005342 // need space to hold the copy
John Kessenich435dd802020-06-30 01:27:08 -06005343 arg = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction,
John Kessenich8985fc92020-03-03 10:25:07 -07005344 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005345 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5346 // need to copy the input into output space
5347 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005348 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005349 builder.clearAccessChain();
5350 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005351 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005352 }
5353 ++lValueCount;
5354 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005355 // process r-value, which involves a copy for a type mismatch
John Kessenich4df10332020-06-26 08:37:06 -06005356 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a]) ||
John Kessenich435dd802020-06-30 01:27:08 -06005357 TranslatePrecisionDecoration(*argTypes[a]) != function->getParamPrecision(a))
John Kessenich4df10332020-06-26 08:37:06 -06005358 {
John Kessenich435dd802020-06-30 01:27:08 -06005359 spv::Id argCopy = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction, function->getParamType(a), "arg");
John Kessenichd3ed90b2018-05-04 11:43:03 -06005360 builder.clearAccessChain();
5361 builder.setAccessChainLValue(argCopy);
5362 multiTypeStore(*argTypes[a], rValues[rValueCount]);
John Kessenich435dd802020-06-30 01:27:08 -06005363 arg = builder.createLoad(argCopy, function->getParamPrecision(a));
John Kessenichd3ed90b2018-05-04 11:43:03 -06005364 } else
5365 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005366 ++rValueCount;
5367 }
5368 spvArgs.push_back(arg);
5369 }
5370
5371 // 3. Make the call.
5372 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005373 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005374
5375 // 4. Copy back out an "out" arguments.
5376 lValueCount = 0;
5377 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005378 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005379 ++lValueCount;
5380 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005381 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
John Kessenich435dd802020-06-30 01:27:08 -06005382 spv::Id copy = builder.createLoad(spvArgs[a], spv::NoPrecision);
John Kessenich140f3df2015-06-26 16:58:36 -06005383 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005384 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005385 }
5386 ++lValueCount;
5387 }
5388 }
5389
5390 return result;
5391}
5392
5393// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005394spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005395 spv::Id typeId, spv::Id left, spv::Id right,
5396 glslang::TBasicType typeProxy, bool reduceComparison)
5397{
John Kessenich66011cb2018-03-06 16:12:04 -07005398 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5399 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005400 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005401
5402 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005403 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005404 bool comparison = false;
5405
5406 switch (op) {
5407 case glslang::EOpAdd:
5408 case glslang::EOpAddAssign:
5409 if (isFloat)
5410 binOp = spv::OpFAdd;
5411 else
5412 binOp = spv::OpIAdd;
5413 break;
5414 case glslang::EOpSub:
5415 case glslang::EOpSubAssign:
5416 if (isFloat)
5417 binOp = spv::OpFSub;
5418 else
5419 binOp = spv::OpISub;
5420 break;
5421 case glslang::EOpMul:
5422 case glslang::EOpMulAssign:
5423 if (isFloat)
5424 binOp = spv::OpFMul;
5425 else
5426 binOp = spv::OpIMul;
5427 break;
5428 case glslang::EOpVectorTimesScalar:
5429 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005430 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005431 if (builder.isVector(right))
5432 std::swap(left, right);
5433 assert(builder.isScalar(right));
5434 needMatchingVectors = false;
5435 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005436 } else if (isFloat)
5437 binOp = spv::OpFMul;
5438 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005439 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005440 break;
5441 case glslang::EOpVectorTimesMatrix:
5442 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005443 binOp = spv::OpVectorTimesMatrix;
5444 break;
5445 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005446 binOp = spv::OpMatrixTimesVector;
5447 break;
5448 case glslang::EOpMatrixTimesScalar:
5449 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005450 binOp = spv::OpMatrixTimesScalar;
5451 break;
5452 case glslang::EOpMatrixTimesMatrix:
5453 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005454 binOp = spv::OpMatrixTimesMatrix;
5455 break;
5456 case glslang::EOpOuterProduct:
5457 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005458 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005459 break;
5460
5461 case glslang::EOpDiv:
5462 case glslang::EOpDivAssign:
5463 if (isFloat)
5464 binOp = spv::OpFDiv;
5465 else if (isUnsigned)
5466 binOp = spv::OpUDiv;
5467 else
5468 binOp = spv::OpSDiv;
5469 break;
5470 case glslang::EOpMod:
5471 case glslang::EOpModAssign:
5472 if (isFloat)
5473 binOp = spv::OpFMod;
5474 else if (isUnsigned)
5475 binOp = spv::OpUMod;
5476 else
5477 binOp = spv::OpSMod;
5478 break;
5479 case glslang::EOpRightShift:
5480 case glslang::EOpRightShiftAssign:
5481 if (isUnsigned)
5482 binOp = spv::OpShiftRightLogical;
5483 else
5484 binOp = spv::OpShiftRightArithmetic;
5485 break;
5486 case glslang::EOpLeftShift:
5487 case glslang::EOpLeftShiftAssign:
5488 binOp = spv::OpShiftLeftLogical;
5489 break;
5490 case glslang::EOpAnd:
5491 case glslang::EOpAndAssign:
5492 binOp = spv::OpBitwiseAnd;
5493 break;
5494 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005495 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005496 binOp = spv::OpLogicalAnd;
5497 break;
5498 case glslang::EOpInclusiveOr:
5499 case glslang::EOpInclusiveOrAssign:
5500 binOp = spv::OpBitwiseOr;
5501 break;
5502 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005503 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005504 binOp = spv::OpLogicalOr;
5505 break;
5506 case glslang::EOpExclusiveOr:
5507 case glslang::EOpExclusiveOrAssign:
5508 binOp = spv::OpBitwiseXor;
5509 break;
5510 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005511 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005512 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005513 break;
5514
Ian Romanickb3bd4022019-01-21 08:57:25 -08005515 case glslang::EOpAbsDifference:
5516 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5517 break;
5518
5519 case glslang::EOpAddSaturate:
5520 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5521 break;
5522
5523 case glslang::EOpSubSaturate:
5524 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5525 break;
5526
5527 case glslang::EOpAverage:
5528 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5529 break;
5530
5531 case glslang::EOpAverageRounded:
5532 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5533 break;
5534
5535 case glslang::EOpMul32x16:
5536 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5537 break;
5538
John Kessenich140f3df2015-06-26 16:58:36 -06005539 case glslang::EOpLessThan:
5540 case glslang::EOpGreaterThan:
5541 case glslang::EOpLessThanEqual:
5542 case glslang::EOpGreaterThanEqual:
5543 case glslang::EOpEqual:
5544 case glslang::EOpNotEqual:
5545 case glslang::EOpVectorEqual:
5546 case glslang::EOpVectorNotEqual:
5547 comparison = true;
5548 break;
5549 default:
5550 break;
5551 }
5552
John Kessenich7c1aa102015-10-15 13:29:11 -06005553 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005554 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005555 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005556 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5557 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005558 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005559
5560 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005561 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005562 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005563
qining25262b32016-05-06 17:25:16 -04005564 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005565 decorations.addNoContraction(builder, result);
5566 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005567 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005568 }
5569
5570 if (! comparison)
5571 return 0;
5572
John Kessenich7c1aa102015-10-15 13:29:11 -06005573 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005574
John Kessenich4583b612016-08-07 19:14:22 -06005575 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005576 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5577 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005578 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005579 return result;
5580 }
John Kessenich140f3df2015-06-26 16:58:36 -06005581
5582 switch (op) {
5583 case glslang::EOpLessThan:
5584 if (isFloat)
5585 binOp = spv::OpFOrdLessThan;
5586 else if (isUnsigned)
5587 binOp = spv::OpULessThan;
5588 else
5589 binOp = spv::OpSLessThan;
5590 break;
5591 case glslang::EOpGreaterThan:
5592 if (isFloat)
5593 binOp = spv::OpFOrdGreaterThan;
5594 else if (isUnsigned)
5595 binOp = spv::OpUGreaterThan;
5596 else
5597 binOp = spv::OpSGreaterThan;
5598 break;
5599 case glslang::EOpLessThanEqual:
5600 if (isFloat)
5601 binOp = spv::OpFOrdLessThanEqual;
5602 else if (isUnsigned)
5603 binOp = spv::OpULessThanEqual;
5604 else
5605 binOp = spv::OpSLessThanEqual;
5606 break;
5607 case glslang::EOpGreaterThanEqual:
5608 if (isFloat)
5609 binOp = spv::OpFOrdGreaterThanEqual;
5610 else if (isUnsigned)
5611 binOp = spv::OpUGreaterThanEqual;
5612 else
5613 binOp = spv::OpSGreaterThanEqual;
5614 break;
5615 case glslang::EOpEqual:
5616 case glslang::EOpVectorEqual:
5617 if (isFloat)
5618 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005619 else if (isBool)
5620 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005621 else
5622 binOp = spv::OpIEqual;
5623 break;
5624 case glslang::EOpNotEqual:
5625 case glslang::EOpVectorNotEqual:
5626 if (isFloat)
Graeme Leese65ce5662020-06-05 13:32:51 +01005627 binOp = spv::OpFUnordNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005628 else if (isBool)
5629 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005630 else
5631 binOp = spv::OpINotEqual;
5632 break;
5633 default:
5634 break;
5635 }
5636
qining25262b32016-05-06 17:25:16 -04005637 if (binOp != spv::OpNop) {
5638 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005639 decorations.addNoContraction(builder, result);
5640 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005641 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005642 }
John Kessenich140f3df2015-06-26 16:58:36 -06005643
5644 return 0;
5645}
5646
John Kessenich04bb8a02015-12-12 12:28:14 -07005647//
5648// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5649// These can be any of:
5650//
5651// matrix * scalar
5652// scalar * matrix
5653// matrix * matrix linear algebraic
5654// matrix * vector
5655// vector * matrix
5656// matrix * matrix componentwise
5657// matrix op matrix op in {+, -, /}
5658// matrix op scalar op in {+, -, /}
5659// scalar op matrix op in {+, -, /}
5660//
John Kessenichead86222018-03-28 18:01:20 -06005661spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5662 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005663{
5664 bool firstClass = true;
5665
5666 // First, handle first-class matrix operations (* and matrix/scalar)
5667 switch (op) {
5668 case spv::OpFDiv:
5669 if (builder.isMatrix(left) && builder.isScalar(right)) {
5670 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005671 spv::Id resultType = builder.getTypeId(right);
5672 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005673 op = spv::OpMatrixTimesScalar;
5674 } else
5675 firstClass = false;
5676 break;
5677 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005678 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005679 std::swap(left, right);
5680 assert(builder.isScalar(right));
5681 break;
5682 case spv::OpVectorTimesMatrix:
5683 assert(builder.isVector(left));
5684 assert(builder.isMatrix(right));
5685 break;
5686 case spv::OpMatrixTimesVector:
5687 assert(builder.isMatrix(left));
5688 assert(builder.isVector(right));
5689 break;
5690 case spv::OpMatrixTimesMatrix:
5691 assert(builder.isMatrix(left));
5692 assert(builder.isMatrix(right));
5693 break;
5694 default:
5695 firstClass = false;
5696 break;
5697 }
5698
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005699 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5700 firstClass = true;
5701
qining25262b32016-05-06 17:25:16 -04005702 if (firstClass) {
5703 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005704 decorations.addNoContraction(builder, result);
5705 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005706 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005707 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005708
LoopDawg592860c2016-06-09 08:57:35 -06005709 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005710 // The result type of all of them is the same type as the (a) matrix operand.
5711 // The algorithm is to:
5712 // - break the matrix(es) into vectors
5713 // - smear any scalar to a vector
5714 // - do vector operations
5715 // - make a matrix out the vector results
5716 switch (op) {
5717 case spv::OpFAdd:
5718 case spv::OpFSub:
5719 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005720 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005721 case spv::OpFMul:
5722 {
5723 // one time set up...
5724 bool leftMat = builder.isMatrix(left);
5725 bool rightMat = builder.isMatrix(right);
5726 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5727 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5728 spv::Id scalarType = builder.getScalarTypeId(typeId);
5729 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5730 std::vector<spv::Id> results;
5731 spv::Id smearVec = spv::NoResult;
5732 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005733 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005734 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005735 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005736
5737 // do each vector op
5738 for (unsigned int c = 0; c < numCols; ++c) {
5739 std::vector<unsigned int> indexes;
5740 indexes.push_back(c);
5741 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5742 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005743 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005744 decorations.addNoContraction(builder, result);
5745 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005746 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005747 }
5748
5749 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005750 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005751 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005752 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005753 }
5754 default:
5755 assert(0);
5756 return spv::NoResult;
5757 }
5758}
5759
John Kessenichead86222018-03-28 18:01:20 -06005760spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005761 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005762{
5763 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005764 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005765 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005766 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5767 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005768
5769 switch (op) {
5770 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005771 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005772 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005773 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005774 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005775 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005776 unaryOp = spv::OpSNegate;
5777 break;
5778
5779 case glslang::EOpLogicalNot:
5780 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005781 unaryOp = spv::OpLogicalNot;
5782 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005783 case glslang::EOpBitwiseNot:
5784 unaryOp = spv::OpNot;
5785 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005786
John Kessenich140f3df2015-06-26 16:58:36 -06005787 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005788 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005789 break;
5790 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005791 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005792 break;
5793 case glslang::EOpTranspose:
5794 unaryOp = spv::OpTranspose;
5795 break;
5796
5797 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005798 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005799 break;
5800 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005801 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005802 break;
5803 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005804 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005805 break;
5806 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005807 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005808 break;
5809 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005810 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005811 break;
5812 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005813 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005814 break;
5815 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005816 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005817 break;
5818 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005819 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005820 break;
5821
5822 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005823 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005824 break;
5825 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005826 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005827 break;
5828 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005829 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005830 break;
5831 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005832 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005833 break;
5834 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005835 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005836 break;
5837 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005838 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005839 break;
5840
5841 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005842 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005843 break;
5844 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005845 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005846 break;
5847
5848 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005849 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005850 break;
5851 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005852 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005853 break;
5854 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005855 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005856 break;
5857 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005858 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005859 break;
5860 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005861 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005862 break;
5863 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005864 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005865 break;
5866
5867 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005868 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005869 break;
5870 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005871 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005872 break;
5873 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005874 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005875 break;
5876 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005877 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005878 break;
5879 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005880 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005881 break;
5882 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005883 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005884 break;
5885
5886 case glslang::EOpIsNan:
5887 unaryOp = spv::OpIsNan;
5888 break;
5889 case glslang::EOpIsInf:
5890 unaryOp = spv::OpIsInf;
5891 break;
LoopDawg592860c2016-06-09 08:57:35 -06005892 case glslang::EOpIsFinite:
5893 unaryOp = spv::OpIsFinite;
5894 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005895
Rex Xucbc426e2015-12-15 16:03:10 +08005896 case glslang::EOpFloatBitsToInt:
5897 case glslang::EOpFloatBitsToUint:
5898 case glslang::EOpIntBitsToFloat:
5899 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005900 case glslang::EOpDoubleBitsToInt64:
5901 case glslang::EOpDoubleBitsToUint64:
5902 case glslang::EOpInt64BitsToDouble:
5903 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005904 case glslang::EOpFloat16BitsToInt16:
5905 case glslang::EOpFloat16BitsToUint16:
5906 case glslang::EOpInt16BitsToFloat16:
5907 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005908 unaryOp = spv::OpBitcast;
5909 break;
5910
John Kessenich140f3df2015-06-26 16:58:36 -06005911 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005912 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005913 break;
5914 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005915 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005916 break;
5917 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005918 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005919 break;
5920 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005921 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005922 break;
5923 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005924 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005925 break;
5926 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005927 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005928 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005929#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005930 case glslang::EOpPackSnorm4x8:
5931 libCall = spv::GLSLstd450PackSnorm4x8;
5932 break;
5933 case glslang::EOpUnpackSnorm4x8:
5934 libCall = spv::GLSLstd450UnpackSnorm4x8;
5935 break;
5936 case glslang::EOpPackUnorm4x8:
5937 libCall = spv::GLSLstd450PackUnorm4x8;
5938 break;
5939 case glslang::EOpUnpackUnorm4x8:
5940 libCall = spv::GLSLstd450UnpackUnorm4x8;
5941 break;
5942 case glslang::EOpPackDouble2x32:
5943 libCall = spv::GLSLstd450PackDouble2x32;
5944 break;
5945 case glslang::EOpUnpackDouble2x32:
5946 libCall = spv::GLSLstd450UnpackDouble2x32;
5947 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005948#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005949
Rex Xu8ff43de2016-04-22 16:51:45 +08005950 case glslang::EOpPackInt2x32:
5951 case glslang::EOpUnpackInt2x32:
5952 case glslang::EOpPackUint2x32:
5953 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005954 case glslang::EOpPack16:
5955 case glslang::EOpPack32:
5956 case glslang::EOpPack64:
5957 case glslang::EOpUnpack32:
5958 case glslang::EOpUnpack16:
5959 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005960 case glslang::EOpPackInt2x16:
5961 case glslang::EOpUnpackInt2x16:
5962 case glslang::EOpPackUint2x16:
5963 case glslang::EOpUnpackUint2x16:
5964 case glslang::EOpPackInt4x16:
5965 case glslang::EOpUnpackInt4x16:
5966 case glslang::EOpPackUint4x16:
5967 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005968 case glslang::EOpPackFloat2x16:
5969 case glslang::EOpUnpackFloat2x16:
5970 unaryOp = spv::OpBitcast;
5971 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005972
John Kessenich140f3df2015-06-26 16:58:36 -06005973 case glslang::EOpDPdx:
5974 unaryOp = spv::OpDPdx;
5975 break;
5976 case glslang::EOpDPdy:
5977 unaryOp = spv::OpDPdy;
5978 break;
5979 case glslang::EOpFwidth:
5980 unaryOp = spv::OpFwidth;
5981 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005982
John Kessenich140f3df2015-06-26 16:58:36 -06005983 case glslang::EOpAny:
5984 unaryOp = spv::OpAny;
5985 break;
5986 case glslang::EOpAll:
5987 unaryOp = spv::OpAll;
5988 break;
5989
5990 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005991 if (isFloat)
5992 libCall = spv::GLSLstd450FAbs;
5993 else
5994 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005995 break;
5996 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005997 if (isFloat)
5998 libCall = spv::GLSLstd450FSign;
5999 else
6000 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06006001 break;
6002
John Kessenicha28f7a72019-08-06 07:00:58 -06006003#ifndef GLSLANG_WEB
6004 case glslang::EOpDPdxFine:
6005 unaryOp = spv::OpDPdxFine;
6006 break;
6007 case glslang::EOpDPdyFine:
6008 unaryOp = spv::OpDPdyFine;
6009 break;
6010 case glslang::EOpFwidthFine:
6011 unaryOp = spv::OpFwidthFine;
6012 break;
6013 case glslang::EOpDPdxCoarse:
6014 unaryOp = spv::OpDPdxCoarse;
6015 break;
6016 case glslang::EOpDPdyCoarse:
6017 unaryOp = spv::OpDPdyCoarse;
6018 break;
6019 case glslang::EOpFwidthCoarse:
6020 unaryOp = spv::OpFwidthCoarse;
6021 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04006022 case glslang::EOpRayQueryProceed:
6023 unaryOp = spv::OpRayQueryProceedKHR;
6024 break;
6025 case glslang::EOpRayQueryGetRayTMin:
6026 unaryOp = spv::OpRayQueryGetRayTMinKHR;
6027 break;
6028 case glslang::EOpRayQueryGetRayFlags:
6029 unaryOp = spv::OpRayQueryGetRayFlagsKHR;
6030 break;
6031 case glslang::EOpRayQueryGetWorldRayOrigin:
6032 unaryOp = spv::OpRayQueryGetWorldRayOriginKHR;
6033 break;
6034 case glslang::EOpRayQueryGetWorldRayDirection:
6035 unaryOp = spv::OpRayQueryGetWorldRayDirectionKHR;
6036 break;
6037 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
6038 unaryOp = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
6039 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006040 case glslang::EOpInterpolateAtCentroid:
6041 if (typeProxy == glslang::EbtFloat16)
6042 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6043 libCall = spv::GLSLstd450InterpolateAtCentroid;
6044 break;
John Kessenichfc51d282015-08-19 13:34:18 -06006045 case glslang::EOpAtomicCounterIncrement:
6046 case glslang::EOpAtomicCounterDecrement:
6047 case glslang::EOpAtomicCounter:
6048 {
6049 // Handle all of the atomics in one place, in createAtomicOperation()
6050 std::vector<spv::Id> operands;
6051 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006052 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06006053 }
6054
John Kessenichfc51d282015-08-19 13:34:18 -06006055 case glslang::EOpBitFieldReverse:
6056 unaryOp = spv::OpBitReverse;
6057 break;
6058 case glslang::EOpBitCount:
6059 unaryOp = spv::OpBitCount;
6060 break;
6061 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006062 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006063 break;
6064 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006065 if (isUnsigned)
6066 libCall = spv::GLSLstd450FindUMsb;
6067 else
6068 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006069 break;
6070
Ian Romanickb3bd4022019-01-21 08:57:25 -08006071 case glslang::EOpCountLeadingZeros:
6072 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6073 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6074 unaryOp = spv::OpUCountLeadingZerosINTEL;
6075 break;
6076
6077 case glslang::EOpCountTrailingZeros:
6078 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6079 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6080 unaryOp = spv::OpUCountTrailingZerosINTEL;
6081 break;
6082
Rex Xu574ab042016-04-14 16:53:07 +08006083 case glslang::EOpBallot:
6084 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006085 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006086 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08006087 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08006088 case glslang::EOpMinInvocations:
6089 case glslang::EOpMaxInvocations:
6090 case glslang::EOpAddInvocations:
6091 case glslang::EOpMinInvocationsNonUniform:
6092 case glslang::EOpMaxInvocationsNonUniform:
6093 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006094 case glslang::EOpMinInvocationsInclusiveScan:
6095 case glslang::EOpMaxInvocationsInclusiveScan:
6096 case glslang::EOpAddInvocationsInclusiveScan:
6097 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6098 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6099 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6100 case glslang::EOpMinInvocationsExclusiveScan:
6101 case glslang::EOpMaxInvocationsExclusiveScan:
6102 case glslang::EOpAddInvocationsExclusiveScan:
6103 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6104 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6105 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08006106 {
6107 std::vector<spv::Id> operands;
6108 operands.push_back(operand);
6109 return createInvocationsOperation(op, typeId, operands, typeProxy);
6110 }
John Kessenich66011cb2018-03-06 16:12:04 -07006111 case glslang::EOpSubgroupAll:
6112 case glslang::EOpSubgroupAny:
6113 case glslang::EOpSubgroupAllEqual:
6114 case glslang::EOpSubgroupBroadcastFirst:
6115 case glslang::EOpSubgroupBallot:
6116 case glslang::EOpSubgroupInverseBallot:
6117 case glslang::EOpSubgroupBallotBitCount:
6118 case glslang::EOpSubgroupBallotInclusiveBitCount:
6119 case glslang::EOpSubgroupBallotExclusiveBitCount:
6120 case glslang::EOpSubgroupBallotFindLSB:
6121 case glslang::EOpSubgroupBallotFindMSB:
6122 case glslang::EOpSubgroupAdd:
6123 case glslang::EOpSubgroupMul:
6124 case glslang::EOpSubgroupMin:
6125 case glslang::EOpSubgroupMax:
6126 case glslang::EOpSubgroupAnd:
6127 case glslang::EOpSubgroupOr:
6128 case glslang::EOpSubgroupXor:
6129 case glslang::EOpSubgroupInclusiveAdd:
6130 case glslang::EOpSubgroupInclusiveMul:
6131 case glslang::EOpSubgroupInclusiveMin:
6132 case glslang::EOpSubgroupInclusiveMax:
6133 case glslang::EOpSubgroupInclusiveAnd:
6134 case glslang::EOpSubgroupInclusiveOr:
6135 case glslang::EOpSubgroupInclusiveXor:
6136 case glslang::EOpSubgroupExclusiveAdd:
6137 case glslang::EOpSubgroupExclusiveMul:
6138 case glslang::EOpSubgroupExclusiveMin:
6139 case glslang::EOpSubgroupExclusiveMax:
6140 case glslang::EOpSubgroupExclusiveAnd:
6141 case glslang::EOpSubgroupExclusiveOr:
6142 case glslang::EOpSubgroupExclusiveXor:
6143 case glslang::EOpSubgroupQuadSwapHorizontal:
6144 case glslang::EOpSubgroupQuadSwapVertical:
6145 case glslang::EOpSubgroupQuadSwapDiagonal: {
6146 std::vector<spv::Id> operands;
6147 operands.push_back(operand);
6148 return createSubgroupOperation(op, typeId, operands, typeProxy);
6149 }
Rex Xu9d93a232016-05-05 12:30:44 +08006150 case glslang::EOpMbcnt:
6151 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6152 libCall = spv::MbcntAMD;
6153 break;
6154
6155 case glslang::EOpCubeFaceIndex:
6156 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6157 libCall = spv::CubeFaceIndexAMD;
6158 break;
6159
6160 case glslang::EOpCubeFaceCoord:
6161 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6162 libCall = spv::CubeFaceCoordAMD;
6163 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006164 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006165 unaryOp = spv::OpGroupNonUniformPartitionNV;
6166 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006167 case glslang::EOpConstructReference:
6168 unaryOp = spv::OpBitcast;
6169 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006170#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006171
6172 case glslang::EOpCopyObject:
6173 unaryOp = spv::OpCopyObject;
6174 break;
6175
John Kessenich140f3df2015-06-26 16:58:36 -06006176 default:
6177 return 0;
6178 }
6179
6180 spv::Id id;
6181 if (libCall >= 0) {
6182 std::vector<spv::Id> args;
6183 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006184 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006185 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006186 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006187 }
John Kessenich140f3df2015-06-26 16:58:36 -06006188
John Kessenichb9197c82019-08-11 07:41:45 -06006189 decorations.addNoContraction(builder, id);
6190 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006191 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006192}
6193
John Kessenich7a53f762016-01-20 11:19:27 -07006194// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006195spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6196 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006197{
6198 // Handle unary operations vector by vector.
6199 // The result type is the same type as the original type.
6200 // The algorithm is to:
6201 // - break the matrix into vectors
6202 // - apply the operation to each vector
6203 // - make a matrix out the vector results
6204
6205 // get the types sorted out
6206 int numCols = builder.getNumColumns(operand);
6207 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006208 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6209 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006210 std::vector<spv::Id> results;
6211
6212 // do each vector op
6213 for (int c = 0; c < numCols; ++c) {
6214 std::vector<unsigned int> indexes;
6215 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006216 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6217 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006218 decorations.addNoContraction(builder, destVec);
6219 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006220 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006221 }
6222
6223 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006224 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006225 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006226 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006227}
6228
John Kessenichad7645f2018-06-04 19:11:25 -06006229// For converting integers where both the bitwidth and the signedness could
6230// change, but only do the width change here. The caller is still responsible
6231// for the signedness conversion.
6232spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006233{
John Kessenichad7645f2018-06-04 19:11:25 -06006234 // Get the result type width, based on the type to convert to.
6235 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006236 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006237 case glslang::EOpConvInt16ToUint8:
6238 case glslang::EOpConvIntToUint8:
6239 case glslang::EOpConvInt64ToUint8:
6240 case glslang::EOpConvUint16ToInt8:
6241 case glslang::EOpConvUintToInt8:
6242 case glslang::EOpConvUint64ToInt8:
6243 width = 8;
6244 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006245 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006246 case glslang::EOpConvIntToUint16:
6247 case glslang::EOpConvInt64ToUint16:
6248 case glslang::EOpConvUint8ToInt16:
6249 case glslang::EOpConvUintToInt16:
6250 case glslang::EOpConvUint64ToInt16:
6251 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006252 break;
6253 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006254 case glslang::EOpConvInt16ToUint:
6255 case glslang::EOpConvInt64ToUint:
6256 case glslang::EOpConvUint8ToInt:
6257 case glslang::EOpConvUint16ToInt:
6258 case glslang::EOpConvUint64ToInt:
6259 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006260 break;
6261 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006262 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006263 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006264 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006265 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006266 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006267 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006268 break;
6269
6270 default:
6271 assert(false && "Default missing");
6272 break;
6273 }
6274
John Kessenichad7645f2018-06-04 19:11:25 -06006275 // Get the conversion operation and result type,
6276 // based on the target width, but the source type.
6277 spv::Id type = spv::NoType;
6278 spv::Op convOp = spv::OpNop;
6279 switch(op) {
6280 case glslang::EOpConvInt8ToUint16:
6281 case glslang::EOpConvInt8ToUint:
6282 case glslang::EOpConvInt8ToUint64:
6283 case glslang::EOpConvInt16ToUint8:
6284 case glslang::EOpConvInt16ToUint:
6285 case glslang::EOpConvInt16ToUint64:
6286 case glslang::EOpConvIntToUint8:
6287 case glslang::EOpConvIntToUint16:
6288 case glslang::EOpConvIntToUint64:
6289 case glslang::EOpConvInt64ToUint8:
6290 case glslang::EOpConvInt64ToUint16:
6291 case glslang::EOpConvInt64ToUint:
6292 convOp = spv::OpSConvert;
6293 type = builder.makeIntType(width);
6294 break;
6295 default:
6296 convOp = spv::OpUConvert;
6297 type = builder.makeUintType(width);
6298 break;
6299 }
6300
John Kessenich66011cb2018-03-06 16:12:04 -07006301 if (vectorSize > 0)
6302 type = builder.makeVectorType(type, vectorSize);
6303
John Kessenichad7645f2018-06-04 19:11:25 -06006304 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006305}
6306
John Kessenichead86222018-03-28 18:01:20 -06006307spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6308 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006309{
6310 spv::Op convOp = spv::OpNop;
6311 spv::Id zero = 0;
6312 spv::Id one = 0;
6313
6314 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6315
6316 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006317 case glslang::EOpConvIntToBool:
6318 case glslang::EOpConvUintToBool:
6319 zero = builder.makeUintConstant(0);
6320 zero = makeSmearedConstant(zero, vectorSize);
6321 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006322 case glslang::EOpConvFloatToBool:
6323 zero = builder.makeFloatConstant(0.0F);
6324 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006325 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006326 case glslang::EOpConvBoolToFloat:
6327 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006328 zero = builder.makeFloatConstant(0.0F);
6329 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006330 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006331
John Kessenich140f3df2015-06-26 16:58:36 -06006332 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006333 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006334#ifndef GLSLANG_WEB
6335 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006336 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006337 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006338 } else
6339#endif
6340 {
6341 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006342 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006343 }
Rex Xucabbb782017-03-24 13:41:14 +08006344
John Kessenich140f3df2015-06-26 16:58:36 -06006345 convOp = spv::OpSelect;
6346 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006347
John Kessenich140f3df2015-06-26 16:58:36 -06006348 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006349 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006350#ifndef GLSLANG_WEB
6351 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006352 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006353 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006354 } else
6355#endif
6356 {
6357 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006358 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006359 }
Rex Xucabbb782017-03-24 13:41:14 +08006360
John Kessenich140f3df2015-06-26 16:58:36 -06006361 convOp = spv::OpSelect;
6362 break;
6363
John Kessenich66011cb2018-03-06 16:12:04 -07006364 case glslang::EOpConvInt8ToFloat16:
6365 case glslang::EOpConvInt8ToFloat:
6366 case glslang::EOpConvInt8ToDouble:
6367 case glslang::EOpConvInt16ToFloat16:
6368 case glslang::EOpConvInt16ToFloat:
6369 case glslang::EOpConvInt16ToDouble:
6370 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006371 case glslang::EOpConvIntToFloat:
6372 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006373 case glslang::EOpConvInt64ToFloat:
6374 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006375 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006376 convOp = spv::OpConvertSToF;
6377 break;
6378
John Kessenich66011cb2018-03-06 16:12:04 -07006379 case glslang::EOpConvUint8ToFloat16:
6380 case glslang::EOpConvUint8ToFloat:
6381 case glslang::EOpConvUint8ToDouble:
6382 case glslang::EOpConvUint16ToFloat16:
6383 case glslang::EOpConvUint16ToFloat:
6384 case glslang::EOpConvUint16ToDouble:
6385 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006386 case glslang::EOpConvUintToFloat:
6387 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006388 case glslang::EOpConvUint64ToFloat:
6389 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006390 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006391 convOp = spv::OpConvertUToF;
6392 break;
6393
John Kessenich66011cb2018-03-06 16:12:04 -07006394 case glslang::EOpConvFloat16ToInt8:
6395 case glslang::EOpConvFloatToInt8:
6396 case glslang::EOpConvDoubleToInt8:
6397 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006398 case glslang::EOpConvFloatToInt16:
6399 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006400 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006401 case glslang::EOpConvFloatToInt:
6402 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006403 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006404 case glslang::EOpConvFloatToInt64:
6405 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006406 convOp = spv::OpConvertFToS;
6407 break;
6408
John Kessenich66011cb2018-03-06 16:12:04 -07006409 case glslang::EOpConvUint8ToInt8:
6410 case glslang::EOpConvInt8ToUint8:
6411 case glslang::EOpConvUint16ToInt16:
6412 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006413 case glslang::EOpConvUintToInt:
6414 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006415 case glslang::EOpConvUint64ToInt64:
6416 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006417 if (builder.isInSpecConstCodeGenMode()) {
6418 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006419#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006420 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6421 zero = builder.makeUint8Constant(0);
6422 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006423 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006424 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6425 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006426 } else
6427#endif
6428 {
Rex Xucabbb782017-03-24 13:41:14 +08006429 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006430 }
qining189b2032016-04-12 23:16:20 -04006431 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006432 // Use OpIAdd, instead of OpBitcast to do the conversion when
6433 // generating for OpSpecConstantOp instruction.
6434 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6435 }
6436 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006437 convOp = spv::OpBitcast;
6438 break;
6439
John Kessenich66011cb2018-03-06 16:12:04 -07006440 case glslang::EOpConvFloat16ToUint8:
6441 case glslang::EOpConvFloatToUint8:
6442 case glslang::EOpConvDoubleToUint8:
6443 case glslang::EOpConvFloat16ToUint16:
6444 case glslang::EOpConvFloatToUint16:
6445 case glslang::EOpConvDoubleToUint16:
6446 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006447 case glslang::EOpConvFloatToUint:
6448 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006449 case glslang::EOpConvFloatToUint64:
6450 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006451 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006452 convOp = spv::OpConvertFToU;
6453 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006454
John Kessenich39697cd2019-08-08 10:35:51 -06006455#ifndef GLSLANG_WEB
6456 case glslang::EOpConvInt8ToBool:
6457 case glslang::EOpConvUint8ToBool:
6458 zero = builder.makeUint8Constant(0);
6459 zero = makeSmearedConstant(zero, vectorSize);
6460 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6461 case glslang::EOpConvInt16ToBool:
6462 case glslang::EOpConvUint16ToBool:
6463 zero = builder.makeUint16Constant(0);
6464 zero = makeSmearedConstant(zero, vectorSize);
6465 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6466 case glslang::EOpConvInt64ToBool:
6467 case glslang::EOpConvUint64ToBool:
6468 zero = builder.makeUint64Constant(0);
6469 zero = makeSmearedConstant(zero, vectorSize);
6470 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6471 case glslang::EOpConvDoubleToBool:
6472 zero = builder.makeDoubleConstant(0.0);
6473 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006474 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006475 case glslang::EOpConvFloat16ToBool:
6476 zero = builder.makeFloat16Constant(0.0F);
6477 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006478 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006479 case glslang::EOpConvBoolToDouble:
6480 convOp = spv::OpSelect;
6481 zero = builder.makeDoubleConstant(0.0);
6482 one = builder.makeDoubleConstant(1.0);
6483 break;
6484 case glslang::EOpConvBoolToFloat16:
6485 convOp = spv::OpSelect;
6486 zero = builder.makeFloat16Constant(0.0F);
6487 one = builder.makeFloat16Constant(1.0F);
6488 break;
6489 case glslang::EOpConvBoolToInt8:
6490 zero = builder.makeInt8Constant(0);
6491 one = builder.makeInt8Constant(1);
6492 convOp = spv::OpSelect;
6493 break;
6494 case glslang::EOpConvBoolToUint8:
6495 zero = builder.makeUint8Constant(0);
6496 one = builder.makeUint8Constant(1);
6497 convOp = spv::OpSelect;
6498 break;
6499 case glslang::EOpConvBoolToInt16:
6500 zero = builder.makeInt16Constant(0);
6501 one = builder.makeInt16Constant(1);
6502 convOp = spv::OpSelect;
6503 break;
6504 case glslang::EOpConvBoolToUint16:
6505 zero = builder.makeUint16Constant(0);
6506 one = builder.makeUint16Constant(1);
6507 convOp = spv::OpSelect;
6508 break;
6509 case glslang::EOpConvDoubleToFloat:
6510 case glslang::EOpConvFloatToDouble:
6511 case glslang::EOpConvDoubleToFloat16:
6512 case glslang::EOpConvFloat16ToDouble:
6513 case glslang::EOpConvFloatToFloat16:
6514 case glslang::EOpConvFloat16ToFloat:
6515 convOp = spv::OpFConvert;
6516 if (builder.isMatrixType(destType))
6517 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6518 break;
6519
John Kessenich66011cb2018-03-06 16:12:04 -07006520 case glslang::EOpConvInt8ToInt16:
6521 case glslang::EOpConvInt8ToInt:
6522 case glslang::EOpConvInt8ToInt64:
6523 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006524 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006525 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006526 case glslang::EOpConvIntToInt8:
6527 case glslang::EOpConvIntToInt16:
6528 case glslang::EOpConvIntToInt64:
6529 case glslang::EOpConvInt64ToInt8:
6530 case glslang::EOpConvInt64ToInt16:
6531 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006532 convOp = spv::OpSConvert;
6533 break;
6534
John Kessenich66011cb2018-03-06 16:12:04 -07006535 case glslang::EOpConvUint8ToUint16:
6536 case glslang::EOpConvUint8ToUint:
6537 case glslang::EOpConvUint8ToUint64:
6538 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006539 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006540 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006541 case glslang::EOpConvUintToUint8:
6542 case glslang::EOpConvUintToUint16:
6543 case glslang::EOpConvUintToUint64:
6544 case glslang::EOpConvUint64ToUint8:
6545 case glslang::EOpConvUint64ToUint16:
6546 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006547 convOp = spv::OpUConvert;
6548 break;
6549
John Kessenich66011cb2018-03-06 16:12:04 -07006550 case glslang::EOpConvInt8ToUint16:
6551 case glslang::EOpConvInt8ToUint:
6552 case glslang::EOpConvInt8ToUint64:
6553 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006554 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006555 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006556 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006557 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006558 case glslang::EOpConvIntToUint64:
6559 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006560 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006561 case glslang::EOpConvInt64ToUint:
6562 case glslang::EOpConvUint8ToInt16:
6563 case glslang::EOpConvUint8ToInt:
6564 case glslang::EOpConvUint8ToInt64:
6565 case glslang::EOpConvUint16ToInt8:
6566 case glslang::EOpConvUint16ToInt:
6567 case glslang::EOpConvUint16ToInt64:
6568 case glslang::EOpConvUintToInt8:
6569 case glslang::EOpConvUintToInt16:
6570 case glslang::EOpConvUintToInt64:
6571 case glslang::EOpConvUint64ToInt8:
6572 case glslang::EOpConvUint64ToInt16:
6573 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006574 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006575 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006576
6577 if (builder.isInSpecConstCodeGenMode()) {
6578 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006579 switch(op) {
6580 case glslang::EOpConvInt16ToUint8:
6581 case glslang::EOpConvIntToUint8:
6582 case glslang::EOpConvInt64ToUint8:
6583 case glslang::EOpConvUint16ToInt8:
6584 case glslang::EOpConvUintToInt8:
6585 case glslang::EOpConvUint64ToInt8:
6586 zero = builder.makeUint8Constant(0);
6587 break;
6588 case glslang::EOpConvInt8ToUint16:
6589 case glslang::EOpConvIntToUint16:
6590 case glslang::EOpConvInt64ToUint16:
6591 case glslang::EOpConvUint8ToInt16:
6592 case glslang::EOpConvUintToInt16:
6593 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006594 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006595 break;
6596 case glslang::EOpConvInt8ToUint:
6597 case glslang::EOpConvInt16ToUint:
6598 case glslang::EOpConvInt64ToUint:
6599 case glslang::EOpConvUint8ToInt:
6600 case glslang::EOpConvUint16ToInt:
6601 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006602 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006603 break;
6604 case glslang::EOpConvInt8ToUint64:
6605 case glslang::EOpConvInt16ToUint64:
6606 case glslang::EOpConvIntToUint64:
6607 case glslang::EOpConvUint8ToInt64:
6608 case glslang::EOpConvUint16ToInt64:
6609 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006610 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006611 break;
6612 default:
6613 assert(false && "Default missing");
6614 break;
6615 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006616 zero = makeSmearedConstant(zero, vectorSize);
6617 // Use OpIAdd, instead of OpBitcast to do the conversion when
6618 // generating for OpSpecConstantOp instruction.
6619 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6620 }
6621 // For normal run-time conversion instruction, use OpBitcast.
6622 convOp = spv::OpBitcast;
6623 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006624 case glslang::EOpConvUint64ToPtr:
6625 convOp = spv::OpConvertUToPtr;
6626 break;
6627 case glslang::EOpConvPtrToUint64:
6628 convOp = spv::OpConvertPtrToU;
6629 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006630 case glslang::EOpConvPtrToUvec2:
6631 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006632 if (builder.isVector(operand))
6633 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6634 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006635 convOp = spv::OpBitcast;
6636 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006637#endif
6638
John Kessenich140f3df2015-06-26 16:58:36 -06006639 default:
6640 break;
6641 }
6642
6643 spv::Id result = 0;
6644 if (convOp == spv::OpNop)
6645 return result;
6646
6647 if (convOp == spv::OpSelect) {
6648 zero = makeSmearedConstant(zero, vectorSize);
6649 one = makeSmearedConstant(one, vectorSize);
6650 result = builder.createTriOp(convOp, destType, operand, one, zero);
6651 } else
6652 result = builder.createUnaryOp(convOp, destType, operand);
6653
John Kessenichead86222018-03-28 18:01:20 -06006654 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006655 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006656 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006657}
6658
6659spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6660{
6661 if (vectorSize == 0)
6662 return constant;
6663
6664 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6665 std::vector<spv::Id> components;
6666 for (int c = 0; c < vectorSize; ++c)
6667 components.push_back(constant);
6668 return builder.makeCompositeConstant(vectorTypeId, components);
6669}
6670
John Kessenich426394d2015-07-23 10:22:48 -06006671// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006672spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6673 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6674 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006675{
6676 spv::Op opCode = spv::OpNop;
6677
6678 switch (op) {
6679 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006680 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006681 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006682 opCode = spv::OpAtomicIAdd;
6683 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006684 case glslang::EOpAtomicCounterSubtract:
6685 opCode = spv::OpAtomicISub;
6686 break;
John Kessenich426394d2015-07-23 10:22:48 -06006687 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006688 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006689 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006690 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6691 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006692 break;
6693 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006694 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006695 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006696 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6697 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006698 break;
6699 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006700 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006701 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006702 opCode = spv::OpAtomicAnd;
6703 break;
6704 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006705 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006706 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006707 opCode = spv::OpAtomicOr;
6708 break;
6709 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006710 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006711 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006712 opCode = spv::OpAtomicXor;
6713 break;
6714 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006715 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006716 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006717 opCode = spv::OpAtomicExchange;
6718 break;
6719 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006720 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006721 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006722 opCode = spv::OpAtomicCompareExchange;
6723 break;
6724 case glslang::EOpAtomicCounterIncrement:
6725 opCode = spv::OpAtomicIIncrement;
6726 break;
6727 case glslang::EOpAtomicCounterDecrement:
6728 opCode = spv::OpAtomicIDecrement;
6729 break;
6730 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006731 case glslang::EOpImageAtomicLoad:
6732 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006733 opCode = spv::OpAtomicLoad;
6734 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006735 case glslang::EOpAtomicStore:
6736 case glslang::EOpImageAtomicStore:
6737 opCode = spv::OpAtomicStore;
6738 break;
John Kessenich426394d2015-07-23 10:22:48 -06006739 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006740 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006741 break;
6742 }
6743
Rex Xue8fe8b02017-09-26 15:42:56 +08006744 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6745 builder.addCapability(spv::CapabilityInt64Atomics);
6746
John Kessenich426394d2015-07-23 10:22:48 -06006747 // Sort out the operands
6748 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006749 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006750 // - compare-exchange swaps the value and comparator
6751 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006752 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006753 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6754 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6755 spv::Id scopeId;
6756 if (glslangIntermediate->usingVulkanMemoryModel()) {
6757 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6758 } else {
6759 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6760 }
6761 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006762 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6763 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006764 spv::MemorySemanticsVolatileMask :
6765 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006766 spv::Id semanticsId2 = semanticsId;
6767
6768 pointerId = operands[0];
6769 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6770 // no additional operands
6771 } else if (opCode == spv::OpAtomicCompareExchange) {
6772 compareId = operands[1];
6773 valueId = operands[2];
6774 if (operands.size() > 3) {
6775 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006776 semanticsId = builder.makeUintConstant(
6777 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6778 semanticsId2 = builder.makeUintConstant(
6779 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006780 }
6781 } else if (opCode == spv::OpAtomicLoad) {
6782 if (operands.size() > 1) {
6783 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006784 semanticsId = builder.makeUintConstant(
6785 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006786 }
6787 } else {
6788 // atomic store or RMW
6789 valueId = operands[1];
6790 if (operands.size() > 2) {
6791 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006792 semanticsId = builder.makeUintConstant
6793 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006794 }
Rex Xu04db3f52015-09-16 11:44:02 +08006795 }
John Kessenich426394d2015-07-23 10:22:48 -06006796
Jeff Bolz36831c92018-09-05 10:11:41 -05006797 // Check for capabilities
6798 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006799 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6800 spv::MemorySemanticsMakeVisibleKHRMask |
6801 spv::MemorySemanticsOutputMemoryKHRMask |
6802 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006803 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6804 }
John Kessenich426394d2015-07-23 10:22:48 -06006805
Jeff Bolz36831c92018-09-05 10:11:41 -05006806 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6807 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6808 }
John Kessenich48d6e792017-10-06 21:21:48 -06006809
Jeff Bolz36831c92018-09-05 10:11:41 -05006810 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6811 spvAtomicOperands.push_back(pointerId);
6812 spvAtomicOperands.push_back(scopeId);
6813 spvAtomicOperands.push_back(semanticsId);
6814 if (opCode == spv::OpAtomicCompareExchange) {
6815 spvAtomicOperands.push_back(semanticsId2);
6816 spvAtomicOperands.push_back(valueId);
6817 spvAtomicOperands.push_back(compareId);
6818 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6819 spvAtomicOperands.push_back(valueId);
6820 }
John Kessenich48d6e792017-10-06 21:21:48 -06006821
Jeff Bolz36831c92018-09-05 10:11:41 -05006822 if (opCode == spv::OpAtomicStore) {
6823 builder.createNoResultOp(opCode, spvAtomicOperands);
6824 return 0;
6825 } else {
6826 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6827
6828 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6829 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6830 if (op == glslang::EOpAtomicCounterDecrement)
6831 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6832
6833 return resultId;
6834 }
John Kessenich426394d2015-07-23 10:22:48 -06006835}
6836
John Kessenich91cef522016-05-05 16:45:40 -06006837// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07006838spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
6839 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006840{
John Kessenich66011cb2018-03-06 16:12:04 -07006841 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6842 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006843
Rex Xu51596642016-09-21 18:56:12 +08006844 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006845 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006846 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6847
chaocf200da82016-12-20 12:44:35 -08006848 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6849 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006850 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6851 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006852 } else if (op == glslang::EOpAnyInvocation ||
6853 op == glslang::EOpAllInvocations ||
6854 op == glslang::EOpAllInvocationsEqual) {
6855 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6856 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006857 } else {
6858 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006859 if (op == glslang::EOpMinInvocationsNonUniform ||
6860 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006861 op == glslang::EOpAddInvocationsNonUniform ||
6862 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6863 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6864 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6865 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6866 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6867 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006868 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006869
Rex Xu430ef402016-10-14 17:22:23 +08006870 switch (op) {
6871 case glslang::EOpMinInvocations:
6872 case glslang::EOpMaxInvocations:
6873 case glslang::EOpAddInvocations:
6874 case glslang::EOpMinInvocationsNonUniform:
6875 case glslang::EOpMaxInvocationsNonUniform:
6876 case glslang::EOpAddInvocationsNonUniform:
6877 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006878 break;
6879 case glslang::EOpMinInvocationsInclusiveScan:
6880 case glslang::EOpMaxInvocationsInclusiveScan:
6881 case glslang::EOpAddInvocationsInclusiveScan:
6882 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6883 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6884 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6885 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006886 break;
6887 case glslang::EOpMinInvocationsExclusiveScan:
6888 case glslang::EOpMaxInvocationsExclusiveScan:
6889 case glslang::EOpAddInvocationsExclusiveScan:
6890 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6891 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6892 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6893 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006894 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006895 default:
6896 break;
Rex Xu430ef402016-10-14 17:22:23 +08006897 }
John Kessenich149afc32018-08-14 13:31:43 -06006898 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6899 spvGroupOperands.push_back(scope);
6900 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006901 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006902 spvGroupOperands.push_back(groupOp);
6903 }
Rex Xu51596642016-09-21 18:56:12 +08006904 }
6905
John Kessenich149afc32018-08-14 13:31:43 -06006906 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6907 spv::IdImmediate op = { true, *opIt };
6908 spvGroupOperands.push_back(op);
6909 }
John Kessenich91cef522016-05-05 16:45:40 -06006910
6911 switch (op) {
6912 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006913 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006914 break;
John Kessenich91cef522016-05-05 16:45:40 -06006915 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006916 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006917 break;
John Kessenich91cef522016-05-05 16:45:40 -06006918 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006919 opCode = spv::OpSubgroupAllEqualKHR;
6920 break;
Rex Xu51596642016-09-21 18:56:12 +08006921 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006922 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006923 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006924 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006925 break;
6926 case glslang::EOpReadFirstInvocation:
6927 opCode = spv::OpSubgroupFirstInvocationKHR;
6928 break;
6929 case glslang::EOpBallot:
6930 {
6931 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6932 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6933 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6934 //
6935 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6936 //
6937 spv::Id uintType = builder.makeUintType(32);
6938 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6939 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6940
6941 std::vector<spv::Id> components;
6942 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6943 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6944
6945 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6946 return builder.createUnaryOp(spv::OpBitcast, typeId,
6947 builder.createCompositeConstruct(uvec2Type, components));
6948 }
6949
Rex Xu9d93a232016-05-05 12:30:44 +08006950 case glslang::EOpMinInvocations:
6951 case glslang::EOpMaxInvocations:
6952 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006953 case glslang::EOpMinInvocationsInclusiveScan:
6954 case glslang::EOpMaxInvocationsInclusiveScan:
6955 case glslang::EOpAddInvocationsInclusiveScan:
6956 case glslang::EOpMinInvocationsExclusiveScan:
6957 case glslang::EOpMaxInvocationsExclusiveScan:
6958 case glslang::EOpAddInvocationsExclusiveScan:
6959 if (op == glslang::EOpMinInvocations ||
6960 op == glslang::EOpMinInvocationsInclusiveScan ||
6961 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006962 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006963 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006964 else {
6965 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006966 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006967 else
Rex Xu51596642016-09-21 18:56:12 +08006968 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006969 }
Rex Xu430ef402016-10-14 17:22:23 +08006970 } else if (op == glslang::EOpMaxInvocations ||
6971 op == glslang::EOpMaxInvocationsInclusiveScan ||
6972 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006973 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006974 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006975 else {
6976 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006977 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006978 else
Rex Xu51596642016-09-21 18:56:12 +08006979 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006980 }
6981 } else {
6982 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006983 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006984 else
Rex Xu51596642016-09-21 18:56:12 +08006985 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006986 }
6987
Rex Xu2bbbe062016-08-23 15:41:05 +08006988 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006989 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006990
6991 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006992 case glslang::EOpMinInvocationsNonUniform:
6993 case glslang::EOpMaxInvocationsNonUniform:
6994 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006995 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6996 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6997 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6998 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6999 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
7000 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
7001 if (op == glslang::EOpMinInvocationsNonUniform ||
7002 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
7003 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007004 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007005 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007006 else {
7007 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007008 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007009 else
Rex Xu51596642016-09-21 18:56:12 +08007010 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007011 }
7012 }
Rex Xu430ef402016-10-14 17:22:23 +08007013 else if (op == glslang::EOpMaxInvocationsNonUniform ||
7014 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
7015 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007016 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007017 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007018 else {
7019 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007020 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007021 else
Rex Xu51596642016-09-21 18:56:12 +08007022 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007023 }
7024 }
7025 else {
7026 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007027 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007028 else
Rex Xu51596642016-09-21 18:56:12 +08007029 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007030 }
7031
Rex Xu2bbbe062016-08-23 15:41:05 +08007032 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007033 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007034
7035 break;
John Kessenich91cef522016-05-05 16:45:40 -06007036 default:
7037 logger->missingFunctionality("invocation operation");
7038 return spv::NoResult;
7039 }
Rex Xu51596642016-09-21 18:56:12 +08007040
7041 assert(opCode != spv::OpNop);
7042 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06007043}
7044
Rex Xu2bbbe062016-08-23 15:41:05 +08007045// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06007046spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
7047 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08007048{
7049 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
7050 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08007051 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08007052 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07007053 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
7054 op == spv::OpGroupSMinNonUniformAMD ||
7055 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
7056 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08007057 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
7058
7059 // Handle group invocation operations scalar by scalar.
7060 // The result type is the same type as the original type.
7061 // The algorithm is to:
7062 // - break the vector into scalars
7063 // - apply the operation to each scalar
7064 // - make a vector out the scalar results
7065
7066 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08007067 int numComponents = builder.getNumComponents(operands[0]);
7068 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08007069 std::vector<spv::Id> results;
7070
7071 // do each scalar op
7072 for (int comp = 0; comp < numComponents; ++comp) {
7073 std::vector<unsigned int> indexes;
7074 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06007075 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
7076 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08007077 if (op == spv::OpSubgroupReadInvocationKHR) {
7078 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007079 spv::IdImmediate operand = { true, operands[1] };
7080 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08007081 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06007082 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7083 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08007084 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007085 spv::IdImmediate operand = { true, operands[1] };
7086 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08007087 } else {
John Kessenich149afc32018-08-14 13:31:43 -06007088 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7089 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06007090 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007091 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08007092 spvGroupOperands.push_back(scalar);
7093 }
Rex Xu2bbbe062016-08-23 15:41:05 +08007094
Rex Xub7072052016-09-26 15:53:40 +08007095 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08007096 }
7097
7098 // put the pieces together
7099 return builder.createCompositeConstruct(typeId, results);
7100}
Rex Xu2bbbe062016-08-23 15:41:05 +08007101
John Kessenich66011cb2018-03-06 16:12:04 -07007102// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06007103spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
7104 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07007105{
7106 // Add the required capabilities.
7107 switch (op) {
7108 case glslang::EOpSubgroupElect:
7109 builder.addCapability(spv::CapabilityGroupNonUniform);
7110 break;
7111 case glslang::EOpSubgroupAll:
7112 case glslang::EOpSubgroupAny:
7113 case glslang::EOpSubgroupAllEqual:
7114 builder.addCapability(spv::CapabilityGroupNonUniform);
7115 builder.addCapability(spv::CapabilityGroupNonUniformVote);
7116 break;
7117 case glslang::EOpSubgroupBroadcast:
7118 case glslang::EOpSubgroupBroadcastFirst:
7119 case glslang::EOpSubgroupBallot:
7120 case glslang::EOpSubgroupInverseBallot:
7121 case glslang::EOpSubgroupBallotBitExtract:
7122 case glslang::EOpSubgroupBallotBitCount:
7123 case glslang::EOpSubgroupBallotInclusiveBitCount:
7124 case glslang::EOpSubgroupBallotExclusiveBitCount:
7125 case glslang::EOpSubgroupBallotFindLSB:
7126 case glslang::EOpSubgroupBallotFindMSB:
7127 builder.addCapability(spv::CapabilityGroupNonUniform);
7128 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
7129 break;
7130 case glslang::EOpSubgroupShuffle:
7131 case glslang::EOpSubgroupShuffleXor:
7132 builder.addCapability(spv::CapabilityGroupNonUniform);
7133 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
7134 break;
7135 case glslang::EOpSubgroupShuffleUp:
7136 case glslang::EOpSubgroupShuffleDown:
7137 builder.addCapability(spv::CapabilityGroupNonUniform);
7138 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
7139 break;
7140 case glslang::EOpSubgroupAdd:
7141 case glslang::EOpSubgroupMul:
7142 case glslang::EOpSubgroupMin:
7143 case glslang::EOpSubgroupMax:
7144 case glslang::EOpSubgroupAnd:
7145 case glslang::EOpSubgroupOr:
7146 case glslang::EOpSubgroupXor:
7147 case glslang::EOpSubgroupInclusiveAdd:
7148 case glslang::EOpSubgroupInclusiveMul:
7149 case glslang::EOpSubgroupInclusiveMin:
7150 case glslang::EOpSubgroupInclusiveMax:
7151 case glslang::EOpSubgroupInclusiveAnd:
7152 case glslang::EOpSubgroupInclusiveOr:
7153 case glslang::EOpSubgroupInclusiveXor:
7154 case glslang::EOpSubgroupExclusiveAdd:
7155 case glslang::EOpSubgroupExclusiveMul:
7156 case glslang::EOpSubgroupExclusiveMin:
7157 case glslang::EOpSubgroupExclusiveMax:
7158 case glslang::EOpSubgroupExclusiveAnd:
7159 case glslang::EOpSubgroupExclusiveOr:
7160 case glslang::EOpSubgroupExclusiveXor:
7161 builder.addCapability(spv::CapabilityGroupNonUniform);
7162 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
7163 break;
7164 case glslang::EOpSubgroupClusteredAdd:
7165 case glslang::EOpSubgroupClusteredMul:
7166 case glslang::EOpSubgroupClusteredMin:
7167 case glslang::EOpSubgroupClusteredMax:
7168 case glslang::EOpSubgroupClusteredAnd:
7169 case glslang::EOpSubgroupClusteredOr:
7170 case glslang::EOpSubgroupClusteredXor:
7171 builder.addCapability(spv::CapabilityGroupNonUniform);
7172 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7173 break;
7174 case glslang::EOpSubgroupQuadBroadcast:
7175 case glslang::EOpSubgroupQuadSwapHorizontal:
7176 case glslang::EOpSubgroupQuadSwapVertical:
7177 case glslang::EOpSubgroupQuadSwapDiagonal:
7178 builder.addCapability(spv::CapabilityGroupNonUniform);
7179 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7180 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007181 case glslang::EOpSubgroupPartitionedAdd:
7182 case glslang::EOpSubgroupPartitionedMul:
7183 case glslang::EOpSubgroupPartitionedMin:
7184 case glslang::EOpSubgroupPartitionedMax:
7185 case glslang::EOpSubgroupPartitionedAnd:
7186 case glslang::EOpSubgroupPartitionedOr:
7187 case glslang::EOpSubgroupPartitionedXor:
7188 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7189 case glslang::EOpSubgroupPartitionedInclusiveMul:
7190 case glslang::EOpSubgroupPartitionedInclusiveMin:
7191 case glslang::EOpSubgroupPartitionedInclusiveMax:
7192 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7193 case glslang::EOpSubgroupPartitionedInclusiveOr:
7194 case glslang::EOpSubgroupPartitionedInclusiveXor:
7195 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7196 case glslang::EOpSubgroupPartitionedExclusiveMul:
7197 case glslang::EOpSubgroupPartitionedExclusiveMin:
7198 case glslang::EOpSubgroupPartitionedExclusiveMax:
7199 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7200 case glslang::EOpSubgroupPartitionedExclusiveOr:
7201 case glslang::EOpSubgroupPartitionedExclusiveXor:
7202 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7203 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7204 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007205 default: assert(0 && "Unhandled subgroup operation!");
7206 }
7207
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007208
7209 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7210 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007211 const bool isBool = typeProxy == glslang::EbtBool;
7212
7213 spv::Op opCode = spv::OpNop;
7214
7215 // Figure out which opcode to use.
7216 switch (op) {
7217 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7218 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7219 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7220 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7221 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7222 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7223 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7224 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7225 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7226 case glslang::EOpSubgroupBallotBitCount:
7227 case glslang::EOpSubgroupBallotInclusiveBitCount:
7228 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7229 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7230 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7231 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7232 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7233 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7234 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7235 case glslang::EOpSubgroupAdd:
7236 case glslang::EOpSubgroupInclusiveAdd:
7237 case glslang::EOpSubgroupExclusiveAdd:
7238 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007239 case glslang::EOpSubgroupPartitionedAdd:
7240 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7241 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007242 if (isFloat) {
7243 opCode = spv::OpGroupNonUniformFAdd;
7244 } else {
7245 opCode = spv::OpGroupNonUniformIAdd;
7246 }
7247 break;
7248 case glslang::EOpSubgroupMul:
7249 case glslang::EOpSubgroupInclusiveMul:
7250 case glslang::EOpSubgroupExclusiveMul:
7251 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007252 case glslang::EOpSubgroupPartitionedMul:
7253 case glslang::EOpSubgroupPartitionedInclusiveMul:
7254 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007255 if (isFloat) {
7256 opCode = spv::OpGroupNonUniformFMul;
7257 } else {
7258 opCode = spv::OpGroupNonUniformIMul;
7259 }
7260 break;
7261 case glslang::EOpSubgroupMin:
7262 case glslang::EOpSubgroupInclusiveMin:
7263 case glslang::EOpSubgroupExclusiveMin:
7264 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007265 case glslang::EOpSubgroupPartitionedMin:
7266 case glslang::EOpSubgroupPartitionedInclusiveMin:
7267 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007268 if (isFloat) {
7269 opCode = spv::OpGroupNonUniformFMin;
7270 } else if (isUnsigned) {
7271 opCode = spv::OpGroupNonUniformUMin;
7272 } else {
7273 opCode = spv::OpGroupNonUniformSMin;
7274 }
7275 break;
7276 case glslang::EOpSubgroupMax:
7277 case glslang::EOpSubgroupInclusiveMax:
7278 case glslang::EOpSubgroupExclusiveMax:
7279 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007280 case glslang::EOpSubgroupPartitionedMax:
7281 case glslang::EOpSubgroupPartitionedInclusiveMax:
7282 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007283 if (isFloat) {
7284 opCode = spv::OpGroupNonUniformFMax;
7285 } else if (isUnsigned) {
7286 opCode = spv::OpGroupNonUniformUMax;
7287 } else {
7288 opCode = spv::OpGroupNonUniformSMax;
7289 }
7290 break;
7291 case glslang::EOpSubgroupAnd:
7292 case glslang::EOpSubgroupInclusiveAnd:
7293 case glslang::EOpSubgroupExclusiveAnd:
7294 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007295 case glslang::EOpSubgroupPartitionedAnd:
7296 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7297 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007298 if (isBool) {
7299 opCode = spv::OpGroupNonUniformLogicalAnd;
7300 } else {
7301 opCode = spv::OpGroupNonUniformBitwiseAnd;
7302 }
7303 break;
7304 case glslang::EOpSubgroupOr:
7305 case glslang::EOpSubgroupInclusiveOr:
7306 case glslang::EOpSubgroupExclusiveOr:
7307 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007308 case glslang::EOpSubgroupPartitionedOr:
7309 case glslang::EOpSubgroupPartitionedInclusiveOr:
7310 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007311 if (isBool) {
7312 opCode = spv::OpGroupNonUniformLogicalOr;
7313 } else {
7314 opCode = spv::OpGroupNonUniformBitwiseOr;
7315 }
7316 break;
7317 case glslang::EOpSubgroupXor:
7318 case glslang::EOpSubgroupInclusiveXor:
7319 case glslang::EOpSubgroupExclusiveXor:
7320 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007321 case glslang::EOpSubgroupPartitionedXor:
7322 case glslang::EOpSubgroupPartitionedInclusiveXor:
7323 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007324 if (isBool) {
7325 opCode = spv::OpGroupNonUniformLogicalXor;
7326 } else {
7327 opCode = spv::OpGroupNonUniformBitwiseXor;
7328 }
7329 break;
7330 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7331 case glslang::EOpSubgroupQuadSwapHorizontal:
7332 case glslang::EOpSubgroupQuadSwapVertical:
7333 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7334 default: assert(0 && "Unhandled subgroup operation!");
7335 }
7336
John Kessenich149afc32018-08-14 13:31:43 -06007337 // get the right Group Operation
7338 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007339 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007340 default:
7341 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007342 case glslang::EOpSubgroupBallotBitCount:
7343 case glslang::EOpSubgroupAdd:
7344 case glslang::EOpSubgroupMul:
7345 case glslang::EOpSubgroupMin:
7346 case glslang::EOpSubgroupMax:
7347 case glslang::EOpSubgroupAnd:
7348 case glslang::EOpSubgroupOr:
7349 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007350 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007351 break;
7352 case glslang::EOpSubgroupBallotInclusiveBitCount:
7353 case glslang::EOpSubgroupInclusiveAdd:
7354 case glslang::EOpSubgroupInclusiveMul:
7355 case glslang::EOpSubgroupInclusiveMin:
7356 case glslang::EOpSubgroupInclusiveMax:
7357 case glslang::EOpSubgroupInclusiveAnd:
7358 case glslang::EOpSubgroupInclusiveOr:
7359 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007360 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007361 break;
7362 case glslang::EOpSubgroupBallotExclusiveBitCount:
7363 case glslang::EOpSubgroupExclusiveAdd:
7364 case glslang::EOpSubgroupExclusiveMul:
7365 case glslang::EOpSubgroupExclusiveMin:
7366 case glslang::EOpSubgroupExclusiveMax:
7367 case glslang::EOpSubgroupExclusiveAnd:
7368 case glslang::EOpSubgroupExclusiveOr:
7369 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007370 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007371 break;
7372 case glslang::EOpSubgroupClusteredAdd:
7373 case glslang::EOpSubgroupClusteredMul:
7374 case glslang::EOpSubgroupClusteredMin:
7375 case glslang::EOpSubgroupClusteredMax:
7376 case glslang::EOpSubgroupClusteredAnd:
7377 case glslang::EOpSubgroupClusteredOr:
7378 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007379 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007380 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007381 case glslang::EOpSubgroupPartitionedAdd:
7382 case glslang::EOpSubgroupPartitionedMul:
7383 case glslang::EOpSubgroupPartitionedMin:
7384 case glslang::EOpSubgroupPartitionedMax:
7385 case glslang::EOpSubgroupPartitionedAnd:
7386 case glslang::EOpSubgroupPartitionedOr:
7387 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007388 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007389 break;
7390 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7391 case glslang::EOpSubgroupPartitionedInclusiveMul:
7392 case glslang::EOpSubgroupPartitionedInclusiveMin:
7393 case glslang::EOpSubgroupPartitionedInclusiveMax:
7394 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7395 case glslang::EOpSubgroupPartitionedInclusiveOr:
7396 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007397 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007398 break;
7399 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7400 case glslang::EOpSubgroupPartitionedExclusiveMul:
7401 case glslang::EOpSubgroupPartitionedExclusiveMin:
7402 case glslang::EOpSubgroupPartitionedExclusiveMax:
7403 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7404 case glslang::EOpSubgroupPartitionedExclusiveOr:
7405 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007406 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007407 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007408 }
7409
John Kessenich149afc32018-08-14 13:31:43 -06007410 // build the instruction
7411 std::vector<spv::IdImmediate> spvGroupOperands;
7412
7413 // Every operation begins with the Execution Scope operand.
7414 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7415 spvGroupOperands.push_back(executionScope);
7416
7417 // Next, for all operations that use a Group Operation, push that as an operand.
7418 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007419 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007420 spvGroupOperands.push_back(groupOperand);
7421 }
7422
John Kessenich66011cb2018-03-06 16:12:04 -07007423 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007424 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7425 spv::IdImmediate operand = { true, *opIt };
7426 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007427 }
7428
7429 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007430 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007431 switch (op) {
7432 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007433 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7434 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7435 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7436 }
7437 if (directionId != spv::NoResult) {
7438 spv::IdImmediate direction = { true, directionId };
7439 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007440 }
7441
7442 return builder.createOp(opCode, typeId, spvGroupOperands);
7443}
7444
John Kessenich8985fc92020-03-03 10:25:07 -07007445spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7446 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007447{
John Kessenich66011cb2018-03-06 16:12:04 -07007448 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7449 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007450
John Kessenich140f3df2015-06-26 16:58:36 -06007451 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007452 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007453 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007454 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007455 spv::Id typeId0 = 0;
7456 if (consumedOperands > 0)
7457 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007458 spv::Id typeId1 = 0;
7459 if (consumedOperands > 1)
7460 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007461 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007462
7463 switch (op) {
7464 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007465 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007466 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007467 else if (isUnsigned)
7468 libCall = spv::GLSLstd450UMin;
7469 else
7470 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007471 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007472 break;
7473 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007474 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007475 break;
7476 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007477 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007478 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007479 else if (isUnsigned)
7480 libCall = spv::GLSLstd450UMax;
7481 else
7482 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007483 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007484 break;
7485 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007486 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007487 break;
7488 case glslang::EOpDot:
7489 opCode = spv::OpDot;
7490 break;
7491 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007492 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007493 break;
7494
7495 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007496 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007497 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007498 else if (isUnsigned)
7499 libCall = spv::GLSLstd450UClamp;
7500 else
7501 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007502 builder.promoteScalar(precision, operands.front(), operands[1]);
7503 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007504 break;
7505 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007506 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7507 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007508 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007509 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007510 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007511 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007512 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007513 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007514 break;
7515 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007516 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007517 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007518 break;
7519 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007520 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007521 builder.promoteScalar(precision, operands[0], operands[2]);
7522 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007523 break;
7524
7525 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007526 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007527 break;
7528 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007529 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007530 break;
7531 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007532 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007533 break;
7534 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007535 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007536 break;
7537 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007538 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007539 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007540 case glslang::EOpBarrier:
7541 {
7542 // This is for the extended controlBarrier function, with four operands.
7543 // The unextended barrier() goes through createNoArgOperation.
7544 assert(operands.size() == 4);
7545 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7546 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7547 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007548 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7549 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007550 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7551 spv::MemorySemanticsMakeVisibleKHRMask |
7552 spv::MemorySemanticsOutputMemoryKHRMask |
7553 spv::MemorySemanticsVolatileMask)) {
7554 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7555 }
John Kessenich8985fc92020-03-03 10:25:07 -07007556 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7557 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007558 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7559 }
7560 return 0;
7561 }
7562 break;
7563 case glslang::EOpMemoryBarrier:
7564 {
7565 // This is for the extended memoryBarrier function, with three operands.
7566 // The unextended memoryBarrier() goes through createNoArgOperation.
7567 assert(operands.size() == 3);
7568 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7569 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7570 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7571 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7572 spv::MemorySemanticsMakeVisibleKHRMask |
7573 spv::MemorySemanticsOutputMemoryKHRMask |
7574 spv::MemorySemanticsVolatileMask)) {
7575 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7576 }
7577 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7578 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7579 }
7580 return 0;
7581 }
7582 break;
7583
John Kessenicha28f7a72019-08-06 07:00:58 -06007584#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007585 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007586 if (typeProxy == glslang::EbtFloat16)
7587 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007588 libCall = spv::GLSLstd450InterpolateAtSample;
7589 break;
7590 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007591 if (typeProxy == glslang::EbtFloat16)
7592 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007593 libCall = spv::GLSLstd450InterpolateAtOffset;
7594 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007595 case glslang::EOpAddCarry:
7596 opCode = spv::OpIAddCarry;
7597 typeId = builder.makeStructResultType(typeId0, typeId0);
7598 consumedOperands = 2;
7599 break;
7600 case glslang::EOpSubBorrow:
7601 opCode = spv::OpISubBorrow;
7602 typeId = builder.makeStructResultType(typeId0, typeId0);
7603 consumedOperands = 2;
7604 break;
7605 case glslang::EOpUMulExtended:
7606 opCode = spv::OpUMulExtended;
7607 typeId = builder.makeStructResultType(typeId0, typeId0);
7608 consumedOperands = 2;
7609 break;
7610 case glslang::EOpIMulExtended:
7611 opCode = spv::OpSMulExtended;
7612 typeId = builder.makeStructResultType(typeId0, typeId0);
7613 consumedOperands = 2;
7614 break;
7615 case glslang::EOpBitfieldExtract:
7616 if (isUnsigned)
7617 opCode = spv::OpBitFieldUExtract;
7618 else
7619 opCode = spv::OpBitFieldSExtract;
7620 break;
7621 case glslang::EOpBitfieldInsert:
7622 opCode = spv::OpBitFieldInsert;
7623 break;
7624
7625 case glslang::EOpFma:
7626 libCall = spv::GLSLstd450Fma;
7627 break;
7628 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007629 {
7630 libCall = spv::GLSLstd450FrexpStruct;
7631 assert(builder.isPointerType(typeId1));
7632 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007633 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007634 if (width == 16)
7635 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7636 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007637 if (builder.getNumComponents(operands[0]) == 1)
7638 frexpIntType = builder.makeIntegerType(width, true);
7639 else
John Kessenich8985fc92020-03-03 10:25:07 -07007640 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7641 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007642 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7643 consumedOperands = 1;
7644 }
John Kessenich55e7d112015-11-15 21:33:39 -07007645 break;
7646 case glslang::EOpLdexp:
7647 libCall = spv::GLSLstd450Ldexp;
7648 break;
7649
Rex Xu574ab042016-04-14 16:53:07 +08007650 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007651 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007652
John Kessenich66011cb2018-03-06 16:12:04 -07007653 case glslang::EOpSubgroupBroadcast:
7654 case glslang::EOpSubgroupBallotBitExtract:
7655 case glslang::EOpSubgroupShuffle:
7656 case glslang::EOpSubgroupShuffleXor:
7657 case glslang::EOpSubgroupShuffleUp:
7658 case glslang::EOpSubgroupShuffleDown:
7659 case glslang::EOpSubgroupClusteredAdd:
7660 case glslang::EOpSubgroupClusteredMul:
7661 case glslang::EOpSubgroupClusteredMin:
7662 case glslang::EOpSubgroupClusteredMax:
7663 case glslang::EOpSubgroupClusteredAnd:
7664 case glslang::EOpSubgroupClusteredOr:
7665 case glslang::EOpSubgroupClusteredXor:
7666 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007667 case glslang::EOpSubgroupPartitionedAdd:
7668 case glslang::EOpSubgroupPartitionedMul:
7669 case glslang::EOpSubgroupPartitionedMin:
7670 case glslang::EOpSubgroupPartitionedMax:
7671 case glslang::EOpSubgroupPartitionedAnd:
7672 case glslang::EOpSubgroupPartitionedOr:
7673 case glslang::EOpSubgroupPartitionedXor:
7674 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7675 case glslang::EOpSubgroupPartitionedInclusiveMul:
7676 case glslang::EOpSubgroupPartitionedInclusiveMin:
7677 case glslang::EOpSubgroupPartitionedInclusiveMax:
7678 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7679 case glslang::EOpSubgroupPartitionedInclusiveOr:
7680 case glslang::EOpSubgroupPartitionedInclusiveXor:
7681 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7682 case glslang::EOpSubgroupPartitionedExclusiveMul:
7683 case glslang::EOpSubgroupPartitionedExclusiveMin:
7684 case glslang::EOpSubgroupPartitionedExclusiveMax:
7685 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7686 case glslang::EOpSubgroupPartitionedExclusiveOr:
7687 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007688 return createSubgroupOperation(op, typeId, operands, typeProxy);
7689
Rex Xu9d93a232016-05-05 12:30:44 +08007690 case glslang::EOpSwizzleInvocations:
7691 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7692 libCall = spv::SwizzleInvocationsAMD;
7693 break;
7694 case glslang::EOpSwizzleInvocationsMasked:
7695 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7696 libCall = spv::SwizzleInvocationsMaskedAMD;
7697 break;
7698 case glslang::EOpWriteInvocation:
7699 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7700 libCall = spv::WriteInvocationAMD;
7701 break;
7702
7703 case glslang::EOpMin3:
7704 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7705 if (isFloat)
7706 libCall = spv::FMin3AMD;
7707 else {
7708 if (isUnsigned)
7709 libCall = spv::UMin3AMD;
7710 else
7711 libCall = spv::SMin3AMD;
7712 }
7713 break;
7714 case glslang::EOpMax3:
7715 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7716 if (isFloat)
7717 libCall = spv::FMax3AMD;
7718 else {
7719 if (isUnsigned)
7720 libCall = spv::UMax3AMD;
7721 else
7722 libCall = spv::SMax3AMD;
7723 }
7724 break;
7725 case glslang::EOpMid3:
7726 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7727 if (isFloat)
7728 libCall = spv::FMid3AMD;
7729 else {
7730 if (isUnsigned)
7731 libCall = spv::UMid3AMD;
7732 else
7733 libCall = spv::SMid3AMD;
7734 }
7735 break;
7736
7737 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007738 if (typeProxy == glslang::EbtFloat16)
7739 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007740 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7741 libCall = spv::InterpolateAtVertexAMD;
7742 break;
Chao Chen3c366992018-09-19 11:41:59 -07007743
Daniel Kochdb32b242020-03-17 20:42:47 -04007744 case glslang::EOpReportIntersection:
Chao Chenb50c02e2018-09-19 11:42:24 -07007745 typeId = builder.makeBoolType();
Daniel Kochdb32b242020-03-17 20:42:47 -04007746 opCode = spv::OpReportIntersectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007747 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04007748 case glslang::EOpTrace:
Daniel Kochdb32b242020-03-17 20:42:47 -04007749 builder.createNoResultOp(spv::OpTraceRayKHR, operands);
Ashwin Leleff1783d2018-10-22 16:41:44 -07007750 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04007751 case glslang::EOpExecuteCallable:
Daniel Kochdb32b242020-03-17 20:42:47 -04007752 builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007753 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007754
7755 case glslang::EOpRayQueryInitialize:
Torosdagli06c2eee2020-03-19 11:09:57 -04007756 builder.createNoResultOp(spv::OpRayQueryInitializeKHR, operands);
7757 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007758 case glslang::EOpRayQueryTerminate:
Torosdagli06c2eee2020-03-19 11:09:57 -04007759 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operands);
7760 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007761 case glslang::EOpRayQueryGenerateIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007762 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR, operands);
7763 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007764 case glslang::EOpRayQueryConfirmIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007765 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operands);
7766 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007767 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04007768 typeId = builder.makeBoolType();
7769 opCode = spv::OpRayQueryProceedKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007770 break;
7771 case glslang::EOpRayQueryGetIntersectionType:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007772 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007773 opCode = spv::OpRayQueryGetIntersectionTypeKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007774 break;
7775 case glslang::EOpRayQueryGetRayTMin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007776 typeId = builder.makeFloatType(32);
7777 opCode = spv::OpRayQueryGetRayTMinKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007778 break;
7779 case glslang::EOpRayQueryGetRayFlags:
Torosdagli06c2eee2020-03-19 11:09:57 -04007780 typeId = builder.makeIntType(32);
7781 opCode = spv::OpRayQueryGetRayFlagsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007782 break;
7783 case glslang::EOpRayQueryGetIntersectionT:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007784 typeId = builder.makeFloatType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007785 opCode = spv::OpRayQueryGetIntersectionTKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007786 break;
7787 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007788 typeId = builder.makeIntType(32);
7789 opCode = spv::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007790 break;
7791 case glslang::EOpRayQueryGetIntersectionInstanceId:
Torosdagli06c2eee2020-03-19 11:09:57 -04007792 typeId = builder.makeIntType(32);
7793 opCode = spv::OpRayQueryGetIntersectionInstanceIdKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007794 break;
7795 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
Torosdagli06c2eee2020-03-19 11:09:57 -04007796 typeId = builder.makeIntType(32);
7797 opCode = spv::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007798 break;
7799 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007800 typeId = builder.makeIntType(32);
7801 opCode = spv::OpRayQueryGetIntersectionGeometryIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007802 break;
7803 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007804 typeId = builder.makeIntType(32);
7805 opCode = spv::OpRayQueryGetIntersectionPrimitiveIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007806 break;
7807 case glslang::EOpRayQueryGetIntersectionBarycentrics:
Torosdagli06c2eee2020-03-19 11:09:57 -04007808 typeId = builder.makeVectorType(builder.makeFloatType(32), 2);
7809 opCode = spv::OpRayQueryGetIntersectionBarycentricsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007810 break;
7811 case glslang::EOpRayQueryGetIntersectionFrontFace:
Torosdagli06c2eee2020-03-19 11:09:57 -04007812 typeId = builder.makeBoolType();
7813 opCode = spv::OpRayQueryGetIntersectionFrontFaceKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007814 break;
7815 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
Torosdagli06c2eee2020-03-19 11:09:57 -04007816 typeId = builder.makeBoolType();
7817 opCode = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007818 break;
7819 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007820 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7821 opCode = spv::OpRayQueryGetIntersectionObjectRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007822 break;
7823 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007824 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7825 opCode = spv::OpRayQueryGetIntersectionObjectRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007826 break;
7827 case glslang::EOpRayQueryGetWorldRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007828 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7829 opCode = spv::OpRayQueryGetWorldRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007830 break;
7831 case glslang::EOpRayQueryGetWorldRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007832 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7833 opCode = spv::OpRayQueryGetWorldRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007834 break;
7835 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
Torosdagli06c2eee2020-03-19 11:09:57 -04007836 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007837 opCode = spv::OpRayQueryGetIntersectionObjectToWorldKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007838 break;
7839 case glslang::EOpRayQueryGetIntersectionWorldToObject:
Torosdagli06c2eee2020-03-19 11:09:57 -04007840 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007841 opCode = spv::OpRayQueryGetIntersectionWorldToObjectKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007842 break;
Chao Chen3c366992018-09-19 11:41:59 -07007843 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7844 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7845 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007846 case glslang::EOpCooperativeMatrixMulAdd:
7847 opCode = spv::OpCooperativeMatrixMulAddNV;
7848 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007849#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007850 default:
7851 return 0;
7852 }
7853
7854 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007855 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007856 // Use an extended instruction from the standard library.
7857 // Construct the call arguments, without modifying the original operands vector.
7858 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7859 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007860 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007861 } else if (opCode == spv::OpDot && !isFloat) {
7862 // int dot(int, int)
7863 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7864 const int componentCount = builder.getNumComponents(operands[0]);
7865 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7866 builder.setPrecision(mulOp, precision);
7867 id = builder.createCompositeExtract(mulOp, typeId, 0);
7868 for (int i = 1; i < componentCount; ++i) {
7869 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07007870 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01007871 }
John Kessenich2359bd02015-12-06 19:29:11 -07007872 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007873 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007874 case 0:
7875 // should all be handled by visitAggregate and createNoArgOperation
7876 assert(0);
7877 return 0;
7878 case 1:
7879 // should all be handled by createUnaryOperation
7880 assert(0);
7881 return 0;
7882 case 2:
7883 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7884 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007885 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007886 // anything 3 or over doesn't have l-value operands, so all should be consumed
7887 assert(consumedOperands == operands.size());
7888 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007889 break;
7890 }
7891 }
7892
John Kessenichb9197c82019-08-11 07:41:45 -06007893#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007894 // Decode the return types that were structures
7895 switch (op) {
7896 case glslang::EOpAddCarry:
7897 case glslang::EOpSubBorrow:
7898 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7899 id = builder.createCompositeExtract(id, typeId0, 0);
7900 break;
7901 case glslang::EOpUMulExtended:
7902 case glslang::EOpIMulExtended:
7903 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7904 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7905 break;
7906 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007907 {
7908 assert(operands.size() == 2);
7909 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7910 // "exp" is floating-point type (from HLSL intrinsic)
7911 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7912 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7913 builder.createStore(member1, operands[1]);
7914 } else
7915 // "exp" is integer type (from GLSL built-in function)
7916 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7917 id = builder.createCompositeExtract(id, typeId0, 0);
7918 }
John Kessenich55e7d112015-11-15 21:33:39 -07007919 break;
7920 default:
7921 break;
7922 }
John Kessenichb9197c82019-08-11 07:41:45 -06007923#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007924
John Kessenich32cfd492016-02-02 12:37:46 -07007925 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007926}
7927
Rex Xu9d93a232016-05-05 12:30:44 +08007928// Intrinsics with no arguments (or no return value, and no precision).
7929spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007930{
Jeff Bolz36831c92018-09-05 10:11:41 -05007931 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07007932 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
7933 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007934
7935 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007936 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007937 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007938 if (glslangIntermediate->usingVulkanMemoryModel()) {
7939 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7940 spv::MemorySemanticsOutputMemoryKHRMask |
7941 spv::MemorySemanticsAcquireReleaseMask);
7942 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7943 } else {
7944 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7945 }
John Kessenich82979362017-12-11 04:02:24 -07007946 } else {
7947 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7948 spv::MemorySemanticsWorkgroupMemoryMask |
7949 spv::MemorySemanticsAcquireReleaseMask);
7950 }
John Kessenich140f3df2015-06-26 16:58:36 -06007951 return 0;
7952 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007953 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7954 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007955 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007956 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007957 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7958 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007959 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007960 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007961 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7962 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007963 return 0;
7964 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007965 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7966 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007967 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007968#ifndef GLSLANG_WEB
7969 case glslang::EOpMemoryBarrierAtomicCounter:
7970 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7971 spv::MemorySemanticsAcquireReleaseMask);
7972 return 0;
7973 case glslang::EOpMemoryBarrierImage:
7974 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7975 spv::MemorySemanticsAcquireReleaseMask);
7976 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007977 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007978 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007979 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007980 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007981 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007982 case glslang::EOpDeviceMemoryBarrier:
7983 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7984 spv::MemorySemanticsImageMemoryMask |
7985 spv::MemorySemanticsAcquireReleaseMask);
7986 return 0;
7987 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7988 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7989 spv::MemorySemanticsImageMemoryMask |
7990 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007991 return 0;
7992 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007993 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7994 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007995 return 0;
7996 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007997 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7998 spv::MemorySemanticsWorkgroupMemoryMask |
7999 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008000 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07008001 case glslang::EOpSubgroupBarrier:
8002 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8003 spv::MemorySemanticsAcquireReleaseMask);
8004 return spv::NoResult;
8005 case glslang::EOpSubgroupMemoryBarrier:
8006 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8007 spv::MemorySemanticsAcquireReleaseMask);
8008 return spv::NoResult;
8009 case glslang::EOpSubgroupMemoryBarrierBuffer:
8010 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
8011 spv::MemorySemanticsAcquireReleaseMask);
8012 return spv::NoResult;
8013 case glslang::EOpSubgroupMemoryBarrierImage:
8014 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
8015 spv::MemorySemanticsAcquireReleaseMask);
8016 return spv::NoResult;
8017 case glslang::EOpSubgroupMemoryBarrierShared:
8018 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8019 spv::MemorySemanticsAcquireReleaseMask);
8020 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06008021
8022 case glslang::EOpEmitVertex:
8023 builder.createNoResultOp(spv::OpEmitVertex);
8024 return 0;
8025 case glslang::EOpEndPrimitive:
8026 builder.createNoResultOp(spv::OpEndPrimitive);
8027 return 0;
8028
John Kessenich66011cb2018-03-06 16:12:04 -07008029 case glslang::EOpSubgroupElect: {
8030 std::vector<spv::Id> operands;
8031 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
8032 }
Rex Xu9d93a232016-05-05 12:30:44 +08008033 case glslang::EOpTime:
8034 {
8035 std::vector<spv::Id> args; // Dummy arguments
8036 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
8037 return builder.setPrecision(id, precision);
8038 }
Daniel Kochdb32b242020-03-17 20:42:47 -04008039 case glslang::EOpIgnoreIntersection:
8040 builder.createNoResultOp(spv::OpIgnoreIntersectionKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008041 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04008042 case glslang::EOpTerminateRay:
8043 builder.createNoResultOp(spv::OpTerminateRayKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008044 return 0;
Torosdagli06c2eee2020-03-19 11:09:57 -04008045 case glslang::EOpRayQueryInitialize:
8046 builder.createNoResultOp(spv::OpRayQueryInitializeKHR);
8047 return 0;
8048 case glslang::EOpRayQueryTerminate:
8049 builder.createNoResultOp(spv::OpRayQueryTerminateKHR);
8050 return 0;
8051 case glslang::EOpRayQueryGenerateIntersection:
8052 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR);
8053 return 0;
8054 case glslang::EOpRayQueryConfirmIntersection:
8055 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR);
8056 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05008057 case glslang::EOpBeginInvocationInterlock:
8058 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
8059 return 0;
8060 case glslang::EOpEndInvocationInterlock:
8061 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
8062 return 0;
8063
Jeff Bolzba6170b2019-07-01 09:23:23 -05008064 case glslang::EOpIsHelperInvocation:
8065 {
8066 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08008067 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
8068 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
8069 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05008070 }
8071
amhagan91fb0092019-07-10 21:14:38 -04008072 case glslang::EOpReadClockSubgroupKHR: {
8073 std::vector<spv::Id> args;
8074 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
8075 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8076 builder.addCapability(spv::CapabilityShaderClockKHR);
8077 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8078 }
8079
8080 case glslang::EOpReadClockDeviceKHR: {
8081 std::vector<spv::Id> args;
8082 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
8083 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8084 builder.addCapability(spv::CapabilityShaderClockKHR);
8085 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8086 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06008087#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008088 default:
John Kessenich155d3512019-08-08 23:29:20 -06008089 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008090 }
John Kessenich155d3512019-08-08 23:29:20 -06008091
8092 logger->missingFunctionality("unknown operation with no arguments");
8093
8094 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008095}
8096
8097spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
8098{
John Kessenich2f273362015-07-18 22:34:27 -06008099 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06008100 spv::Id id;
8101 if (symbolValues.end() != iter) {
8102 id = iter->second;
8103 return id;
8104 }
8105
8106 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06008107 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
Daniel Kochdb32b242020-03-17 20:42:47 -04008108 auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06008109 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06008110 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06008111 if (forcedType.second != spv::NoType)
8112 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06008113
Rex Xuc884b4a2016-06-29 15:03:44 +08008114 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008115 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
8116 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
8117 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06008118#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008119 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06008120 if (symbol->getQualifier().hasComponent())
8121 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
8122 if (symbol->getQualifier().hasIndex())
8123 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07008124#endif
John Kessenich6c292d32016-02-15 20:58:50 -07008125 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07008126 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06008127 // atomic counters use this:
8128 if (symbol->getQualifier().hasOffset())
8129 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008130 }
8131
scygan2c864272016-05-18 18:09:17 +02008132 if (symbol->getQualifier().hasLocation())
8133 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07008134 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07008135 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07008136 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06008137 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07008138 }
John Kessenich140f3df2015-06-26 16:58:36 -06008139 if (symbol->getQualifier().hasSet())
8140 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07008141 else if (IsDescriptorResource(symbol->getType())) {
8142 // default to 0
8143 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
8144 }
John Kessenich140f3df2015-06-26 16:58:36 -06008145 if (symbol->getQualifier().hasBinding())
8146 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06008147 else if (IsDescriptorResource(symbol->getType())) {
8148 // default to 0
8149 builder.addDecoration(id, spv::DecorationBinding, 0);
8150 }
John Kessenich6c292d32016-02-15 20:58:50 -07008151 if (symbol->getQualifier().hasAttachment())
8152 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06008153 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07008154 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07008155 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008156 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07008157 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
8158 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
8159 builder.addDecoration(id, spv::DecorationXfbStride, stride);
8160 }
8161 if (symbol->getQualifier().hasXfbOffset())
8162 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008163 }
8164
John Kessenichb9197c82019-08-11 07:41:45 -06008165 // add built-in variable decoration
8166 if (builtIn != spv::BuiltInMax) {
8167 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
8168 }
8169
8170#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08008171 if (symbol->getType().isImage()) {
8172 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07008173 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
8174 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08008175 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07008176 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08008177 }
8178
John Kessenich5611c6d2018-04-05 11:25:02 -06008179 // nonuniform
8180 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
8181
chaoc0ad6a4e2016-12-19 16:29:34 -08008182 if (builtIn == spv::BuiltInSampleMask) {
8183 spv::Decoration decoration;
8184 // GL_NV_sample_mask_override_coverage extension
8185 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08008186 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08008187 else
8188 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07008189 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08008190 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07008191 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08008192 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
8193 }
8194 }
chaoc771d89f2017-01-13 01:10:53 -08008195 else if (builtIn == spv::BuiltInLayer) {
8196 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06008197 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008198 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08008199 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
8200 builder.addExtension(spv::E_SPV_NV_viewport_array2);
8201 }
John Kessenichb41bff62017-08-11 13:07:17 -06008202 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008203 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
8204 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08008205 builder.addCapability(spv::CapabilityShaderStereoViewNV);
8206 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
8207 }
8208 }
8209
chaoc6e5acae2016-12-20 13:28:52 -08008210 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008211 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08008212 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08008213 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
8214 }
Chao Chen9eada4b2018-09-19 11:39:56 -07008215 if (symbol->getQualifier().pervertexNV) {
8216 builder.addDecoration(id, spv::DecorationPerVertexNV);
8217 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
8218 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
8219 }
chaoc0ad6a4e2016-12-19 16:29:34 -08008220
John Kessenich5d610ee2018-03-07 18:05:55 -07008221 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
8222 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
8223 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
8224 symbol->getType().getQualifier().semanticName);
8225 }
8226
John Kessenich7015bd62019-08-01 03:28:08 -06008227 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07008228 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
8229 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008230 }
John Kessenichb9197c82019-08-11 07:41:45 -06008231#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008232
John Kessenich140f3df2015-06-26 16:58:36 -06008233 return id;
8234}
8235
John Kessenicha28f7a72019-08-06 07:00:58 -06008236#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008237// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
8238void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
8239{
8240 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07008241 if (qualifier.perPrimitiveNV) {
8242 // Need to add capability/extension for fragment shader.
8243 // Mesh shader already adds this by default.
8244 if (glslangIntermediate->getStage() == EShLangFragment) {
8245 builder.addCapability(spv::CapabilityMeshShadingNV);
8246 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8247 }
Chao Chen3c366992018-09-19 11:41:59 -07008248 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008249 }
Chao Chen3c366992018-09-19 11:41:59 -07008250 if (qualifier.perViewNV)
8251 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
8252 if (qualifier.perTaskNV)
8253 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
8254 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07008255 if (qualifier.perPrimitiveNV) {
8256 // Need to add capability/extension for fragment shader.
8257 // Mesh shader already adds this by default.
8258 if (glslangIntermediate->getStage() == EShLangFragment) {
8259 builder.addCapability(spv::CapabilityMeshShadingNV);
8260 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8261 }
Chao Chen3c366992018-09-19 11:41:59 -07008262 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008263 }
Chao Chen3c366992018-09-19 11:41:59 -07008264 if (qualifier.perViewNV)
8265 builder.addDecoration(id, spv::DecorationPerViewNV);
8266 if (qualifier.perTaskNV)
8267 builder.addDecoration(id, spv::DecorationPerTaskNV);
8268 }
8269}
8270#endif
8271
John Kessenich55e7d112015-11-15 21:33:39 -07008272// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008273// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008274//
8275// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8276//
8277// Recursively walk the nodes. The nodes form a tree whose leaves are
8278// regular constants, which themselves are trees that createSpvConstant()
8279// recursively walks. So, this function walks the "top" of the tree:
8280// - emit specialization constant-building instructions for specConstant
8281// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008282spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008283{
John Kessenich7cc0e282016-03-20 00:46:02 -06008284 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008285
qining4f4bb812016-04-03 23:55:17 -04008286 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008287 if (! node.getQualifier().specConstant) {
8288 // hand off to the non-spec-constant path
8289 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8290 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008291 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8292 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8293 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008294 }
8295
8296 // We now know we have a specialization constant to build
8297
Ricardo Garcia232ba0d2020-06-03 15:52:55 +02008298 // Extra capabilities may be needed.
8299 if (node.getType().contains8BitInt())
8300 builder.addCapability(spv::CapabilityInt8);
8301 if (node.getType().contains16BitFloat())
8302 builder.addCapability(spv::CapabilityFloat16);
8303 if (node.getType().contains16BitInt())
8304 builder.addCapability(spv::CapabilityInt16);
8305 if (node.getType().contains64BitInt())
8306 builder.addCapability(spv::CapabilityInt64);
8307 if (node.getType().containsDouble())
8308 builder.addCapability(spv::CapabilityFloat64);
8309
John Kessenichd94c0032016-05-30 19:29:40 -06008310 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008311 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8312 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8313 std::vector<spv::Id> dimConstId;
8314 for (int dim = 0; dim < 3; ++dim) {
8315 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8316 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008317 if (specConst) {
8318 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8319 glslangIntermediate->getLocalSizeSpecId(dim));
8320 }
qining4f4bb812016-04-03 23:55:17 -04008321 }
8322 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8323 }
8324
8325 // An AST node labelled as specialization constant should be a symbol node.
8326 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8327 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008328 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008329 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008330 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8331 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8332 // will set the builder into spec constant op instruction generating mode.
8333 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008334 result = accessChainLoad(sub_tree->getType());
8335 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008336 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008337 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008338 } else {
8339 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008340 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008341 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008342 builder.addName(result, sn->getName().c_str());
8343 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008344 }
qining4f4bb812016-04-03 23:55:17 -04008345
8346 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8347 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008348 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008349 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008350}
8351
John Kessenich140f3df2015-06-26 16:58:36 -06008352// Use 'consts' as the flattened glslang source of scalar constants to recursively
8353// build the aggregate SPIR-V constant.
8354//
8355// If there are not enough elements present in 'consts', 0 will be substituted;
8356// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8357//
John Kessenich8985fc92020-03-03 10:25:07 -07008358spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8359 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008360{
8361 // vector of constants for SPIR-V
8362 std::vector<spv::Id> spvConsts;
8363
8364 // Type is used for struct and array constants
8365 spv::Id typeId = convertGlslangToSpvType(glslangType);
8366
8367 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008368 glslang::TType elementType(glslangType, 0);
8369 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008370 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008371 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008372 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008373 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008374 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008375 } else if (glslangType.isCoopMat()) {
8376 glslang::TType componentType(glslangType.getBasicType());
8377 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008378 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008379 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8380 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008381 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008382 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008383 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8384 bool zero = nextConst >= consts.size();
8385 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008386 case glslang::EbtInt:
8387 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8388 break;
8389 case glslang::EbtUint:
8390 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8391 break;
8392 case glslang::EbtFloat:
8393 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8394 break;
8395 case glslang::EbtBool:
8396 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8397 break;
8398#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008399 case glslang::EbtInt8:
8400 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8401 break;
8402 case glslang::EbtUint8:
8403 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8404 break;
8405 case glslang::EbtInt16:
8406 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8407 break;
8408 case glslang::EbtUint16:
8409 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8410 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008411 case glslang::EbtInt64:
8412 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8413 break;
8414 case glslang::EbtUint64:
8415 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8416 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008417 case glslang::EbtDouble:
8418 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8419 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008420 case glslang::EbtFloat16:
8421 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8422 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008423#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008424 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008425 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008426 break;
8427 }
8428 ++nextConst;
8429 }
8430 } else {
8431 // we have a non-aggregate (scalar) constant
8432 bool zero = nextConst >= consts.size();
8433 spv::Id scalar = 0;
8434 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008435 case glslang::EbtInt:
8436 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8437 break;
8438 case glslang::EbtUint:
8439 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8440 break;
8441 case glslang::EbtFloat:
8442 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8443 break;
8444 case glslang::EbtBool:
8445 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8446 break;
8447#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008448 case glslang::EbtInt8:
8449 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8450 break;
8451 case glslang::EbtUint8:
8452 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8453 break;
8454 case glslang::EbtInt16:
8455 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8456 break;
8457 case glslang::EbtUint16:
8458 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8459 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008460 case glslang::EbtInt64:
8461 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8462 break;
8463 case glslang::EbtUint64:
8464 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8465 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008466 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008467 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008468 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008469 case glslang::EbtFloat16:
8470 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8471 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008472 case glslang::EbtReference:
8473 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8474 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8475 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008476#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008477 case glslang::EbtString:
8478 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8479 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008480 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008481 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008482 break;
8483 }
8484 ++nextConst;
8485 return scalar;
8486 }
8487
8488 return builder.makeCompositeConstant(typeId, spvConsts);
8489}
8490
John Kessenich7c1aa102015-10-15 13:29:11 -06008491// Return true if the node is a constant or symbol whose reading has no
8492// non-trivial observable cost or effect.
8493bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8494{
8495 // don't know what this is
8496 if (node == nullptr)
8497 return false;
8498
8499 // a constant is safe
8500 if (node->getAsConstantUnion() != nullptr)
8501 return true;
8502
8503 // not a symbol means non-trivial
8504 if (node->getAsSymbolNode() == nullptr)
8505 return false;
8506
8507 // a symbol, depends on what's being read
8508 switch (node->getType().getQualifier().storage) {
8509 case glslang::EvqTemporary:
8510 case glslang::EvqGlobal:
8511 case glslang::EvqIn:
8512 case glslang::EvqInOut:
8513 case glslang::EvqConst:
8514 case glslang::EvqConstReadOnly:
8515 case glslang::EvqUniform:
8516 return true;
8517 default:
8518 return false;
8519 }
qining25262b32016-05-06 17:25:16 -04008520}
John Kessenich7c1aa102015-10-15 13:29:11 -06008521
8522// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008523// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008524// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008525// Return true if trivial.
8526bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8527{
8528 if (node == nullptr)
8529 return false;
8530
John Kessenich84cc15f2017-05-24 16:44:47 -06008531 // count non scalars as trivial, as well as anything coming from HLSL
8532 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008533 return true;
8534
John Kessenich7c1aa102015-10-15 13:29:11 -06008535 // symbols and constants are trivial
8536 if (isTrivialLeaf(node))
8537 return true;
8538
8539 // otherwise, it needs to be a simple operation or one or two leaf nodes
8540
8541 // not a simple operation
8542 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8543 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8544 if (binaryNode == nullptr && unaryNode == nullptr)
8545 return false;
8546
8547 // not on leaf nodes
8548 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8549 return false;
8550
8551 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8552 return false;
8553 }
8554
8555 switch (node->getAsOperator()->getOp()) {
8556 case glslang::EOpLogicalNot:
8557 case glslang::EOpConvIntToBool:
8558 case glslang::EOpConvUintToBool:
8559 case glslang::EOpConvFloatToBool:
8560 case glslang::EOpConvDoubleToBool:
8561 case glslang::EOpEqual:
8562 case glslang::EOpNotEqual:
8563 case glslang::EOpLessThan:
8564 case glslang::EOpGreaterThan:
8565 case glslang::EOpLessThanEqual:
8566 case glslang::EOpGreaterThanEqual:
8567 case glslang::EOpIndexDirect:
8568 case glslang::EOpIndexDirectStruct:
8569 case glslang::EOpLogicalXor:
8570 case glslang::EOpAny:
8571 case glslang::EOpAll:
8572 return true;
8573 default:
8574 return false;
8575 }
8576}
8577
8578// Emit short-circuiting code, where 'right' is never evaluated unless
8579// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008580spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8581 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008582{
8583 spv::Id boolTypeId = builder.makeBoolType();
8584
8585 // emit left operand
8586 builder.clearAccessChain();
8587 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008588 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008589
8590 // Operands to accumulate OpPhi operands
8591 std::vector<spv::Id> phiOperands;
8592 // accumulate left operand's phi information
8593 phiOperands.push_back(leftId);
8594 phiOperands.push_back(builder.getBuildPoint()->getId());
8595
8596 // Make the two kinds of operation symmetric with a "!"
8597 // || => emit "if (! left) result = right"
8598 // && => emit "if ( left) result = right"
8599 //
8600 // TODO: this runtime "not" for || could be avoided by adding functionality
8601 // to 'builder' to have an "else" without an "then"
8602 if (op == glslang::EOpLogicalOr)
8603 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8604
8605 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008606 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008607
8608 // emit right operand as the "then" part of the "if"
8609 builder.clearAccessChain();
8610 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008611 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008612
8613 // accumulate left operand's phi information
8614 phiOperands.push_back(rightId);
8615 phiOperands.push_back(builder.getBuildPoint()->getId());
8616
8617 // finish the "if"
8618 ifBuilder.makeEndIf();
8619
8620 // phi together the two results
8621 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8622}
8623
John Kessenicha28f7a72019-08-06 07:00:58 -06008624#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008625// Return type Id of the imported set of extended instructions corresponds to the name.
8626// Import this set if it has not been imported yet.
8627spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8628{
8629 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8630 return extBuiltinMap[name];
8631 else {
Rex Xu51596642016-09-21 18:56:12 +08008632 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008633 spv::Id extBuiltins = builder.import(name);
8634 extBuiltinMap[name] = extBuiltins;
8635 return extBuiltins;
8636 }
8637}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008638#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008639
John Kessenich140f3df2015-06-26 16:58:36 -06008640}; // end anonymous namespace
8641
8642namespace glslang {
8643
John Kessenich68d78fd2015-07-12 19:28:10 -06008644void GetSpirvVersion(std::string& version)
8645{
John Kessenich9e55f632015-07-15 10:03:39 -06008646 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008647 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008648 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008649 version = buf;
8650}
8651
John Kessenicha372a3e2017-11-02 22:32:14 -06008652// For low-order part of the generator's magic number. Bump up
8653// when there is a change in the style (e.g., if SSA form changes,
8654// or a different instruction sequence to do something gets used).
8655int GetSpirvGeneratorVersion()
8656{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008657 // return 1; // start
8658 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008659 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008660 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008661 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008662 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8663 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008664 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenich3641ff72020-06-10 07:38:31 -06008665 // return 8; // switch to new dead block eliminator; use OpUnreachable
Graeme Leese060882f2020-06-22 11:03:46 +01008666 // return 9; // don't include opaque function parameters in OpEntryPoint global's operand list
8667 return 10; // Generate OpFUnordNotEqual for != comparisons
John Kessenicha372a3e2017-11-02 22:32:14 -06008668}
8669
John Kessenich140f3df2015-06-26 16:58:36 -06008670// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008671void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008672{
8673 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008674 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008675 if (out.fail())
8676 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008677 for (int i = 0; i < (int)spirv.size(); ++i) {
8678 unsigned int word = spirv[i];
8679 out.write((const char*)&word, 4);
8680 }
8681 out.close();
8682}
8683
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008684// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008685void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008686{
John Kessenich155d3512019-08-08 23:29:20 -06008687#ifndef GLSLANG_WEB
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008688 std::ofstream out;
8689 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008690 if (out.fail())
8691 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008692 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008693 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008694 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008695 if (varName != nullptr) {
8696 out << "\t #pragma once" << std::endl;
8697 out << "const uint32_t " << varName << "[] = {" << std::endl;
8698 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008699 const int WORDS_PER_LINE = 8;
8700 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8701 out << "\t";
8702 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8703 const unsigned int word = spirv[i + j];
8704 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8705 if (i + j + 1 < (int)spirv.size()) {
8706 out << ",";
8707 }
8708 }
8709 out << std::endl;
8710 }
Flavio15017db2017-02-15 14:29:33 -08008711 if (varName != nullptr) {
8712 out << "};";
8713 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008714 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008715#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008716}
8717
John Kessenich140f3df2015-06-26 16:58:36 -06008718//
8719// Set up the glslang traversal
8720//
John Kessenich4e11b612018-08-30 16:56:59 -06008721void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008722{
Lei Zhang17535f72016-05-04 15:55:59 -04008723 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008724 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008725}
8726
John Kessenich4e11b612018-08-30 16:56:59 -06008727void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008728 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008729{
John Kessenich140f3df2015-06-26 16:58:36 -06008730 TIntermNode* root = intermediate.getTreeRoot();
8731
8732 if (root == 0)
8733 return;
8734
John Kessenich4e11b612018-08-30 16:56:59 -06008735 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008736 if (options == nullptr)
8737 options = &defaultOptions;
8738
John Kessenich4e11b612018-08-30 16:56:59 -06008739 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008740
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008741 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008742 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008743 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008744 it.dumpSpv(spirv);
8745
GregFfb03a552018-03-29 11:49:14 -06008746#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008747 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8748 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008749 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008750 if ((prelegalization || options->optimizeSize) && !options->disableOptimizer) {
8751 SpirvToolsTransform(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008752 prelegalization = false;
8753 }
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008754 else if (options->stripDebugInfo) {
8755 // Strip debug info even if optimization is disabled.
8756 SpirvToolsStripDebugInfo(intermediate, spirv, logger);
8757 }
John Kessenich717c80a2018-08-23 15:17:10 -06008758
John Kessenich4e11b612018-08-30 16:56:59 -06008759 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008760 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008761
John Kessenich717c80a2018-08-23 15:17:10 -06008762 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008763 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008764
GregFcd1f1692017-09-21 18:40:22 -06008765#endif
8766
John Kessenich4e11b612018-08-30 16:56:59 -06008767 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008768}
8769
8770}; // end namespace glslang