blob: d17c9664d68944a72f697856d1e38724ebbd9615 [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.
1295 if (type.getBasicType() == glslang::EbtSampler)
1296 return type.getQualifier().isUniformOrBuffer();
1297
1298 // None of the above.
1299 return false;
1300}
1301
John Kesseniche0b6cad2015-12-24 10:30:13 -07001302void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1303{
1304 if (child.layoutMatrix == glslang::ElmNone)
1305 child.layoutMatrix = parent.layoutMatrix;
1306
1307 if (parent.invariant)
1308 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001309 if (parent.flat)
1310 child.flat = true;
1311 if (parent.centroid)
1312 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001313#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001314 if (parent.nopersp)
1315 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001316 if (parent.explicitInterp)
1317 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001318 if (parent.perPrimitiveNV)
1319 child.perPrimitiveNV = true;
1320 if (parent.perViewNV)
1321 child.perViewNV = true;
1322 if (parent.perTaskNV)
1323 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001324 if (parent.patch)
1325 child.patch = true;
1326 if (parent.sample)
1327 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001328 if (parent.coherent)
1329 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001330 if (parent.devicecoherent)
1331 child.devicecoherent = true;
1332 if (parent.queuefamilycoherent)
1333 child.queuefamilycoherent = true;
1334 if (parent.workgroupcoherent)
1335 child.workgroupcoherent = true;
1336 if (parent.subgroupcoherent)
1337 child.subgroupcoherent = true;
Daniel Kochdb32b242020-03-17 20:42:47 -04001338 if (parent.shadercallcoherent)
1339 child.shadercallcoherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001340 if (parent.nonprivate)
1341 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001342 if (parent.volatil)
1343 child.volatil = true;
1344 if (parent.restrict)
1345 child.restrict = true;
1346 if (parent.readonly)
1347 child.readonly = true;
1348 if (parent.writeonly)
1349 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001350#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001351}
1352
John Kessenichf2b7f332016-09-01 17:05:23 -06001353bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001354{
John Kessenich7b9fa252016-01-21 18:56:57 -07001355 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001356 // - struct members might inherit from a struct declaration
1357 // (note that non-block structs don't explicitly inherit,
1358 // only implicitly, meaning no decoration involved)
1359 // - affect decorations on the struct members
1360 // (note smooth does not, and expecting something like volatile
1361 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001362 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001363 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001364}
1365
John Kessenich140f3df2015-06-26 16:58:36 -06001366//
1367// Implement the TGlslangToSpvTraverser class.
1368//
1369
John Kessenich8985fc92020-03-03 10:25:07 -07001370TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion,
1371 const glslang::TIntermediate* glslangIntermediate,
1372 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options) :
1373 TIntermTraverser(true, false, true),
1374 options(options),
1375 shaderEntry(nullptr), currentFunction(nullptr),
1376 sequenceDepth(0), logger(buildLogger),
1377 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
1378 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
1379 glslangIntermediate(glslangIntermediate),
Jeff Bolz04d73732019-05-31 13:06:01 -05001380 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp()),
1381 nonSemanticDebugPrintf(0)
John Kessenich140f3df2015-06-26 16:58:36 -06001382{
1383 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1384
1385 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001386 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1387 glslangIntermediate->getVersion());
1388
John Kessenich121853f2017-05-31 17:11:16 -06001389 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001390 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001391 builder.setSourceFile(glslangIntermediate->getSourceFile());
1392
1393 // Set the source shader's text. If for SPV version 1.0, include
1394 // a preamble in comments stating the OpModuleProcessed instructions.
1395 // Otherwise, emit those as actual instructions.
1396 std::string text;
1397 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1398 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001399 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001400 text.append("// OpModuleProcessed ");
1401 text.append(processes[p]);
1402 text.append("\n");
1403 } else
1404 builder.addModuleProcessed(processes[p]);
1405 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001406 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001407 text.append("#line 1\n");
1408 text.append(glslangIntermediate->getSourceText());
1409 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001410 // Pass name and text for all included files
1411 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1412 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1413 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001414 }
John Kessenich140f3df2015-06-26 16:58:36 -06001415 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001416
1417 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1418 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1419
1420 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1421 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
John Kessenich1ff0c182019-10-10 12:01:13 -06001422 builder.addIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001423 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
John Kessenich8985fc92020-03-03 10:25:07 -07001424 }
Jeff Bolz36831c92018-09-05 10:11:41 -05001425 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001426 memoryModel = spv::MemoryModelVulkanKHR;
1427 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001428 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001429 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001430 builder.setMemoryModel(addressingModel, memoryModel);
1431
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001432 if (glslangIntermediate->usingVariablePointers()) {
1433 builder.addCapability(spv::CapabilityVariablePointers);
1434 }
1435
John Kessenicheee9d532016-09-19 18:09:30 -06001436 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1437 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001438
1439 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001440 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1441 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001442 builder.addSourceExtension(it->c_str());
1443
1444 // Add the top-level modes for this shader.
1445
John Kessenich92187592016-02-01 13:45:25 -07001446 if (glslangIntermediate->getXfbMode()) {
1447 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001448 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001449 }
John Kessenich140f3df2015-06-26 16:58:36 -06001450
1451 unsigned int mode;
1452 switch (glslangIntermediate->getStage()) {
1453 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001454 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001455 break;
1456
John Kessenicha28f7a72019-08-06 07:00:58 -06001457 case EShLangFragment:
1458 builder.addCapability(spv::CapabilityShader);
1459 if (glslangIntermediate->getPixelCenterInteger())
1460 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1461
1462 if (glslangIntermediate->getOriginUpperLeft())
1463 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1464 else
1465 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1466
1467 if (glslangIntermediate->getEarlyFragmentTests())
1468 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1469
1470 if (glslangIntermediate->getPostDepthCoverage()) {
1471 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1472 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1473 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1474 }
1475
John Kessenichb9197c82019-08-11 07:41:45 -06001476 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1477 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1478
1479#ifndef GLSLANG_WEB
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001480
John Kessenicha28f7a72019-08-06 07:00:58 -06001481 switch(glslangIntermediate->getDepth()) {
1482 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1483 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1484 default: mode = spv::ExecutionModeMax; break;
1485 }
1486 if (mode != spv::ExecutionModeMax)
1487 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001488 switch (glslangIntermediate->getInterlockOrdering()) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001489 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT;
1490 break;
1491 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT;
1492 break;
1493 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT;
1494 break;
1495 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT;
1496 break;
1497 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT;
1498 break;
1499 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT;
1500 break;
1501 default: mode = spv::ExecutionModeMax;
1502 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001503 }
1504 if (mode != spv::ExecutionModeMax) {
1505 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1506 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1507 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1508 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1509 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1510 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1511 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1512 } else {
1513 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1514 }
1515 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1516 }
John Kessenichb9197c82019-08-11 07:41:45 -06001517#endif
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001518 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001519
John Kessenicha28f7a72019-08-06 07:00:58 -06001520 case EShLangCompute:
1521 builder.addCapability(spv::CapabilityShader);
1522 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1523 glslangIntermediate->getLocalSize(1),
1524 glslangIntermediate->getLocalSize(2));
1525 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1526 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1527 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1528 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1529 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1530 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1531 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1532 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1533 }
1534 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001535#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001536 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001537 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001538 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001539
steve-lunarge7412492017-03-23 11:56:07 -06001540 glslang::TLayoutGeometry primitive;
1541
1542 if (glslangIntermediate->getStage() == EShLangTessControl) {
John Kessenich8985fc92020-03-03 10:25:07 -07001543 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1544 glslangIntermediate->getVertices());
steve-lunarge7412492017-03-23 11:56:07 -06001545 primitive = glslangIntermediate->getOutputPrimitive();
1546 } else {
1547 primitive = glslangIntermediate->getInputPrimitive();
1548 }
1549
1550 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001551 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1552 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1553 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001554 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001555 }
John Kessenich4016e382016-07-15 11:53:56 -06001556 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001557 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1558
John Kesseniche6903322015-10-13 16:29:02 -06001559 switch (glslangIntermediate->getVertexSpacing()) {
1560 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1561 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1562 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001563 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001564 }
John Kessenich4016e382016-07-15 11:53:56 -06001565 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001566 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1567
1568 switch (glslangIntermediate->getVertexOrder()) {
1569 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1570 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001571 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001572 }
John Kessenich4016e382016-07-15 11:53:56 -06001573 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001574 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1575
1576 if (glslangIntermediate->getPointMode())
1577 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001578 break;
1579
1580 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001581 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001582 switch (glslangIntermediate->getInputPrimitive()) {
1583 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1584 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1585 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001586 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001587 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001588 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001589 }
John Kessenich4016e382016-07-15 11:53:56 -06001590 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001591 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001592
John Kessenich140f3df2015-06-26 16:58:36 -06001593 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1594
1595 switch (glslangIntermediate->getOutputPrimitive()) {
1596 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1597 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1598 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001599 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001600 }
John Kessenich4016e382016-07-15 11:53:56 -06001601 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001602 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1603 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1604 break;
1605
Daniel Kochdb32b242020-03-17 20:42:47 -04001606 case EShLangRayGen:
1607 case EShLangIntersect:
1608 case EShLangAnyHit:
1609 case EShLangClosestHit:
1610 case EShLangMiss:
1611 case EShLangCallable:
1612 {
1613 auto& extensions = glslangIntermediate->getRequestedExtensions();
1614 if (extensions.find("GL_NV_ray_tracing") == extensions.end()) {
1615 builder.addCapability(spv::CapabilityRayTracingProvisionalKHR);
1616 builder.addExtension("SPV_KHR_ray_tracing");
1617 }
1618 else {
1619 builder.addCapability(spv::CapabilityRayTracingNV);
1620 builder.addExtension("SPV_NV_ray_tracing");
1621 }
Chao Chenb50c02e2018-09-19 11:42:24 -07001622 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04001623 }
Chao Chen3c366992018-09-19 11:41:59 -07001624 case EShLangTaskNV:
1625 case EShLangMeshNV:
1626 builder.addCapability(spv::CapabilityMeshShadingNV);
1627 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1628 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1629 glslangIntermediate->getLocalSize(1),
1630 glslangIntermediate->getLocalSize(2));
1631 if (glslangIntermediate->getStage() == EShLangMeshNV) {
John Kessenich8985fc92020-03-03 10:25:07 -07001632 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1633 glslangIntermediate->getVertices());
1634 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV,
1635 glslangIntermediate->getPrimitives());
Chao Chen3c366992018-09-19 11:41:59 -07001636
1637 switch (glslangIntermediate->getOutputPrimitive()) {
1638 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1639 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1640 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1641 default: mode = spv::ExecutionModeMax; break;
1642 }
1643 if (mode != spv::ExecutionModeMax)
1644 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1645 }
1646 break;
1647#endif
1648
John Kessenich140f3df2015-06-26 16:58:36 -06001649 default:
1650 break;
1651 }
John Kessenich140f3df2015-06-26 16:58:36 -06001652}
1653
John Kessenichfca82622016-11-26 13:23:20 -07001654// Finish creating SPV, after the traversal is complete.
1655void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001656{
John Kessenichf04c51b2018-08-03 15:56:12 -06001657 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001658 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001659 builder.setBuildPoint(shaderEntry->getLastBlock());
1660 builder.leaveFunction();
1661 }
1662
John Kessenich7ba63412015-12-20 17:37:07 -07001663 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001664 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1665 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001666
David Neto8c3d5b42019-10-21 14:50:31 -04001667 // Add capabilities, extensions, remove unneeded decorations, etc.,
John Kessenichf04c51b2018-08-03 15:56:12 -06001668 // based on the resulting SPIR-V.
David Neto8c3d5b42019-10-21 14:50:31 -04001669 // Note: WebGPU code generation must have the opportunity to aggressively
1670 // prune unreachable merge blocks and continue targets.
John Kessenichf04c51b2018-08-03 15:56:12 -06001671 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001672}
1673
John Kessenichfca82622016-11-26 13:23:20 -07001674// Write the SPV into 'out'.
1675void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001676{
John Kessenichfca82622016-11-26 13:23:20 -07001677 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001678}
1679
1680//
1681// Implement the traversal functions.
1682//
1683// Return true from interior nodes to have the external traversal
1684// continue on to children. Return false if children were
1685// already processed.
1686//
1687
1688//
qining25262b32016-05-06 17:25:16 -04001689// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001690// - uniform/input reads
1691// - output writes
1692// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1693// - something simple that degenerates into the last bullet
1694//
1695void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1696{
qining75d1d802016-04-06 14:42:01 -04001697 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
Roy05a5b532020-01-03 16:21:34 +08001698 if (symbol->getType().isStruct())
1699 glslangTypeToIdMap[symbol->getType().getStruct()] = symbol->getId();
1700
qining75d1d802016-04-06 14:42:01 -04001701 if (symbol->getType().getQualifier().isSpecConstant())
1702 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1703
John Kessenich140f3df2015-06-26 16:58:36 -06001704 // getSymbolId() will set up all the IO decorations on the first call.
1705 // Formal function parameters were mapped during makeFunctions().
1706 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001707
John Kessenich7ba63412015-12-20 17:37:07 -07001708 if (builder.isPointer(id)) {
John Kessenich9c14f772019-06-17 08:38:35 -06001709 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
John Kessenich7c7731e2019-01-04 16:47:06 +07001710 // Consider adding to the OpEntryPoint interface list.
1711 // Only looking at structures if they have at least one member.
1712 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1713 spv::StorageClass sc = builder.getStorageClass(id);
1714 // Before SPIR-V 1.4, we only want to include Input and Output.
1715 // Starting with SPIR-V 1.4, we want all globals.
1716 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1717 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001718 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001719 }
John Kessenich5f77d862017-09-19 11:09:59 -06001720 }
John Kessenich9c14f772019-06-17 08:38:35 -06001721
Daniel Kochdb32b242020-03-17 20:42:47 -04001722 // If the SPIR-V type is required to be different than the AST type
1723 // (for ex SubgroupMasks or 3x4 ObjectToWorld/WorldToObject matrices),
John Kessenich9c14f772019-06-17 08:38:35 -06001724 // translate now from the SPIR-V type to the AST type, for the consuming
1725 // operation.
1726 // Note this turns it from an l-value to an r-value.
1727 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1728 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1729 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001730 }
1731
1732 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001733 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001734 // Prepare to generate code for the access
1735
1736 // L-value chains will be computed left to right. We're on the symbol now,
1737 // which is the left-most part of the access chain, so now is "clear" time,
1738 // followed by setting the base.
1739 builder.clearAccessChain();
1740
1741 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001742 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001743 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001744 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001745 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001746 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001747 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001748 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001749 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1750 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001751 builder.setAccessChainRValue(id);
1752 else
1753 builder.setAccessChainLValue(id);
1754 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001755
John Kessenichb9197c82019-08-11 07:41:45 -06001756#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001757 // Process linkage-only nodes for any special additional interface work.
1758 if (linkageOnly) {
1759 if (glslangIntermediate->getHlslFunctionality1()) {
1760 // Map implicit counter buffers to their originating buffers, which should have been
1761 // seen by now, given earlier pruning of unused counters, and preservation of order
1762 // of declaration.
1763 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1764 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1765 // Save possible originating buffers for counter buffers, keyed by
1766 // making the potential counter-buffer name.
1767 std::string keyName = symbol->getName().c_str();
1768 keyName = glslangIntermediate->addCounterBufferName(keyName);
1769 counterOriginator[keyName] = symbol;
1770 } else {
1771 // Handle a counter buffer, by finding the saved originating buffer.
1772 std::string keyName = symbol->getName().c_str();
1773 auto it = counterOriginator.find(keyName);
1774 if (it != counterOriginator.end()) {
1775 id = getSymbolId(it->second);
1776 if (id != spv::NoResult) {
1777 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001778 if (counterId != spv::NoResult) {
1779 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001780 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001781 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001782 }
1783 }
1784 }
1785 }
1786 }
1787 }
John Kessenich155d3512019-08-08 23:29:20 -06001788#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001789}
1790
1791bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1792{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001793 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Roy05a5b532020-01-03 16:21:34 +08001794 if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
1795 glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
1796 }
1797 if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
1798 glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
1799 }
John Kesseniche485c7a2017-05-31 18:50:53 -06001800
qining40887662016-04-03 22:20:42 -04001801 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1802 if (node->getType().getQualifier().isSpecConstant())
1803 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1804
John Kessenich140f3df2015-06-26 16:58:36 -06001805 // First, handle special cases
1806 switch (node->getOp()) {
1807 case glslang::EOpAssign:
1808 case glslang::EOpAddAssign:
1809 case glslang::EOpSubAssign:
1810 case glslang::EOpMulAssign:
1811 case glslang::EOpVectorTimesMatrixAssign:
1812 case glslang::EOpVectorTimesScalarAssign:
1813 case glslang::EOpMatrixTimesScalarAssign:
1814 case glslang::EOpMatrixTimesMatrixAssign:
1815 case glslang::EOpDivAssign:
1816 case glslang::EOpModAssign:
1817 case glslang::EOpAndAssign:
1818 case glslang::EOpInclusiveOrAssign:
1819 case glslang::EOpExclusiveOrAssign:
1820 case glslang::EOpLeftShiftAssign:
1821 case glslang::EOpRightShiftAssign:
1822 // A bin-op assign "a += b" means the same thing as "a = a + b"
1823 // where a is evaluated before b. For a simple assignment, GLSL
1824 // says to evaluate the left before the right. So, always, left
1825 // node then right node.
1826 {
1827 // get the left l-value, save it away
1828 builder.clearAccessChain();
1829 node->getLeft()->traverse(this);
1830 spv::Builder::AccessChain lValue = builder.getAccessChain();
1831
1832 // evaluate the right
1833 builder.clearAccessChain();
1834 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001835 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001836
1837 if (node->getOp() != glslang::EOpAssign) {
1838 // the left is also an r-value
1839 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001840 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001841
1842 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001843 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001844 TranslateNoContractionDecoration(node->getType().getQualifier()),
1845 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001846 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001847 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1848 node->getType().getBasicType());
1849
1850 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001851 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001852 }
1853
1854 // store the result
1855 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001856 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001857
1858 // assignments are expressions having an rValue after they are evaluated...
1859 builder.clearAccessChain();
1860 builder.setAccessChainRValue(rValue);
1861 }
1862 return false;
1863 case glslang::EOpIndexDirect:
1864 case glslang::EOpIndexDirectStruct:
1865 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001866 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001867 // Get the left part of the access chain.
1868 node->getLeft()->traverse(this);
1869
1870 // Add the next element in the chain
1871
David Netoa901ffe2016-06-08 14:11:40 +01001872 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001873 if (! node->getLeft()->getType().isArray() &&
1874 node->getLeft()->getType().isVector() &&
1875 node->getOp() == glslang::EOpIndexDirect) {
1876 // This is essentially a hard-coded vector swizzle of size 1,
1877 // so short circuit the access-chain stuff with a swizzle.
1878 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001879 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001880 int dummySize;
1881 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1882 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001883 glslangIntermediate->getBaseAlignmentScalar(
1884 node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001885 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001886
1887 // Load through a block reference is performed with a dot operator that
1888 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1889 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001890 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001891 !node->getLeft()->getType().isArray() &&
1892 node->getOp() == glslang::EOpIndexDirectStruct)
1893 {
1894 spv::Id left = accessChainLoad(node->getLeft()->getType());
1895 builder.clearAccessChain();
1896 builder.setAccessChainLValue(left);
1897 }
1898
David Netoa901ffe2016-06-08 14:11:40 +01001899 int spvIndex = glslangIndex;
1900 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1901 node->getOp() == glslang::EOpIndexDirectStruct)
1902 {
1903 // This may be, e.g., an anonymous block-member selection, which generally need
1904 // index remapping due to hidden members in anonymous blocks.
Roy05a5b532020-01-03 16:21:34 +08001905 int glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
1906 if (memberRemapper.find(glslangId) != memberRemapper.end()) {
1907 std::vector<int>& remapper = memberRemapper[glslangId];
1908 assert(remapper.size() > 0);
1909 spvIndex = remapper[glslangIndex];
1910 }
David Netoa901ffe2016-06-08 14:11:40 +01001911 }
John Kessenichebb50532016-05-16 19:22:05 -06001912
David Netoa901ffe2016-06-08 14:11:40 +01001913 // normal case for indexing array or structure or block
John Kessenich8985fc92020-03-03 10:25:07 -07001914 builder.accessChainPush(builder.makeIntConstant(spvIndex),
1915 TranslateCoherent(node->getLeft()->getType()),
1916 node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001917
1918 // Add capabilities here for accessing PointSize and clip/cull distance.
1919 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001920 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001921 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001922 }
1923 }
1924 return false;
1925 case glslang::EOpIndexIndirect:
1926 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001927 // Array, matrix, or vector indirection with variable index.
1928 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001929 // matrices are arrays of vectors, so will also work for a matrix.
1930 // Will use the access chain's 'component' for variable index into a vector.
1931
1932 // This adapter is building access chains left to right.
1933 // Set up the access chain to the left.
1934 node->getLeft()->traverse(this);
1935
1936 // save it so that computing the right side doesn't trash it
1937 spv::Builder::AccessChain partial = builder.getAccessChain();
1938
1939 // compute the next index in the chain
1940 builder.clearAccessChain();
1941 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001942 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001943
John Kessenich5611c6d2018-04-05 11:25:02 -06001944 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1945
John Kessenich140f3df2015-06-26 16:58:36 -06001946 // restore the saved access chain
1947 builder.setAccessChain(partial);
1948
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001949 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1950 int dummySize;
1951 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1952 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001953 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1954 dummySize));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001955 } else
John Kessenich8985fc92020-03-03 10:25:07 -07001956 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()),
1957 node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001958 }
1959 return false;
1960 case glslang::EOpVectorSwizzle:
1961 {
1962 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001963 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001964 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001965 int dummySize;
1966 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1967 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001968 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1969 dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001970 }
1971 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001972 case glslang::EOpMatrixSwizzle:
1973 logger->missingFunctionality("matrix swizzle");
1974 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001975 case glslang::EOpLogicalOr:
1976 case glslang::EOpLogicalAnd:
1977 {
1978
1979 // These may require short circuiting, but can sometimes be done as straight
1980 // binary operations. The right operand must be short circuited if it has
1981 // side effects, and should probably be if it is complex.
1982 if (isTrivial(node->getRight()->getAsTyped()))
1983 break; // handle below as a normal binary operation
1984 // otherwise, we need to do dynamic short circuiting on the right operand
John Kessenich8985fc92020-03-03 10:25:07 -07001985 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(),
1986 *node->getRight()->getAsTyped());
John Kessenich7c1aa102015-10-15 13:29:11 -06001987 builder.clearAccessChain();
1988 builder.setAccessChainRValue(result);
1989 }
1990 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001991 default:
1992 break;
1993 }
1994
1995 // Assume generic binary op...
1996
John Kessenich32cfd492016-02-02 12:37:46 -07001997 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001998 builder.clearAccessChain();
1999 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002000 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002001
John Kessenich32cfd492016-02-02 12:37:46 -07002002 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06002003 builder.clearAccessChain();
2004 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002005 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002006
John Kessenich32cfd492016-02-02 12:37:46 -07002007 // get result
John Kessenichead86222018-03-28 18:01:20 -06002008 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002009 TranslateNoContractionDecoration(node->getType().getQualifier()),
2010 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002011 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07002012 convertGlslangToSpvType(node->getType()), left, right,
2013 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002014
John Kessenich50e57562015-12-21 21:21:11 -07002015 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06002016 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002017 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07002018 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06002019 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06002020 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06002021 return false;
2022 }
John Kessenich140f3df2015-06-26 16:58:36 -06002023}
2024
John Kessenich9c14f772019-06-17 08:38:35 -06002025// Figure out what, if any, type changes are needed when accessing a specific built-in.
2026// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
2027// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
Daniel Kochdb32b242020-03-17 20:42:47 -04002028std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(glslang::TBuiltInVariable glslangBuiltIn,
John Kessenich9c14f772019-06-17 08:38:35 -06002029 const glslang::TType& glslangType)
2030{
Daniel Kochdb32b242020-03-17 20:42:47 -04002031 switch(glslangBuiltIn)
John Kessenich9c14f772019-06-17 08:38:35 -06002032 {
Daniel Kochdb32b242020-03-17 20:42:47 -04002033 case glslang::EbvSubGroupEqMask:
2034 case glslang::EbvSubGroupGeMask:
2035 case glslang::EbvSubGroupGtMask:
2036 case glslang::EbvSubGroupLeMask:
2037 case glslang::EbvSubGroupLtMask: {
John Kessenich9c14f772019-06-17 08:38:35 -06002038 // these require changing a 64-bit scaler -> a vector of 32-bit components
2039 if (glslangType.isVector())
2040 break;
2041 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
2042 builder.makeUintType(64));
2043 return ret;
2044 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002045 // There are no SPIR-V builtins defined for these and map onto original non-transposed
2046 // builtins. During visitBinary we insert a transpose
2047 case glslang::EbvWorldToObject3x4:
2048 case glslang::EbvObjectToWorld3x4: {
2049 std::pair<spv::Id, spv::Id> ret(builder.makeMatrixType(builder.makeFloatType(32), 4, 3),
2050 builder.makeMatrixType(builder.makeFloatType(32), 3, 4)
2051 );
2052 return ret;
2053 }
John Kessenich9c14f772019-06-17 08:38:35 -06002054 default:
2055 break;
2056 }
2057
2058 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2059 return ret;
2060}
2061
2062// For an object previously identified (see getForcedType() and forceType)
2063// as needing type translations, do the translation needed for a load, turning
2064// an L-value into in R-value.
2065spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2066{
2067 const auto forceIt = forceType.find(object);
2068 if (forceIt == forceType.end())
2069 return object;
2070
2071 spv::Id desiredTypeId = forceIt->second;
2072 spv::Id objectTypeId = builder.getTypeId(object);
2073 assert(builder.isPointerType(objectTypeId));
2074 objectTypeId = builder.getContainedTypeId(objectTypeId);
2075 if (builder.isVectorType(objectTypeId) &&
2076 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2077 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2078 // handle 32-bit v.xy* -> 64-bit
2079 builder.clearAccessChain();
2080 builder.setAccessChainLValue(object);
2081 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2082 std::vector<spv::Id> components;
2083 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2084 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2085
2086 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2087 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2088 builder.createCompositeConstruct(vecType, components));
2089 } else {
2090 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2091 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002092 } else if (builder.isMatrixType(objectTypeId)) {
2093 // There are no SPIR-V builtins defined for 3x4 variants of ObjectToWorld/WorldToObject
2094 // and we insert a transpose after loading the original non-transposed builtins
2095 builder.clearAccessChain();
2096 builder.setAccessChainLValue(object);
2097 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2098 return builder.createUnaryOp(spv::OpTranspose, desiredTypeId, object);
2099
2100 } else {
John Kessenich9c14f772019-06-17 08:38:35 -06002101 logger->missingFunctionality("forcing non 32-bit vector type");
2102 }
2103
2104 return object;
2105}
2106
John Kessenich140f3df2015-06-26 16:58:36 -06002107bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2108{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002109 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002110
qining40887662016-04-03 22:20:42 -04002111 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2112 if (node->getType().getQualifier().isSpecConstant())
2113 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2114
John Kessenichfc51d282015-08-19 13:34:18 -06002115 spv::Id result = spv::NoResult;
2116
2117 // try texturing first
2118 result = createImageTextureFunctionCall(node);
2119 if (result != spv::NoResult) {
2120 builder.clearAccessChain();
2121 builder.setAccessChainRValue(result);
2122
2123 return false; // done with this node
2124 }
2125
2126 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002127
2128 if (node->getOp() == glslang::EOpArrayLength) {
2129 // Quite special; won't want to evaluate the operand.
2130
John Kessenich5611c6d2018-04-05 11:25:02 -06002131 // Currently, the front-end does not allow .length() on an array until it is sized,
2132 // except for the last block membeor of an SSBO.
2133 // TODO: If this changes, link-time sized arrays might show up here, and need their
2134 // size extracted.
2135
John Kessenichc9a80832015-09-12 12:17:44 -06002136 // Normal .length() would have been constant folded by the front-end.
2137 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002138 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002139
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002140 spv::Id length;
2141 if (node->getOperand()->getType().isCoopMat()) {
2142 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2143
2144 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2145 assert(builder.isCooperativeMatrixType(typeId));
2146
2147 length = builder.createCooperativeMatrixLength(typeId);
2148 } else {
2149 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2150 block->traverse(this);
John Kessenich8985fc92020-03-03 10:25:07 -07002151 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()
2152 ->getConstArray()[0].getUConst();
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002153 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2154 }
John Kessenichc9a80832015-09-12 12:17:44 -06002155
John Kessenich8c869672018-11-28 07:01:37 -07002156 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2157 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2158 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002159 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2160 if (builder.isInSpecConstCodeGenMode()) {
2161 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2162 } else {
2163 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2164 }
2165 }
John Kessenich8c869672018-11-28 07:01:37 -07002166
John Kessenichc9a80832015-09-12 12:17:44 -06002167 builder.clearAccessChain();
2168 builder.setAccessChainRValue(length);
2169
2170 return false;
2171 }
2172
John Kessenichfc51d282015-08-19 13:34:18 -06002173 // Start by evaluating the operand
2174
John Kessenich8c8505c2016-07-26 12:50:38 -06002175 // Does it need a swizzle inversion? If so, evaluation is inverted;
2176 // operate first on the swizzle base, then apply the swizzle.
2177 spv::Id invertedType = spv::NoType;
John Kessenich8985fc92020-03-03 10:25:07 -07002178 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2179 invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenich8c8505c2016-07-26 12:50:38 -06002180 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2181 invertedType = getInvertedSwizzleType(*node->getOperand());
2182
John Kessenich140f3df2015-06-26 16:58:36 -06002183 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002184 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002185 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002186 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002187 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002188 operandNode = node->getOperand();
2189
2190 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002191
Rex Xufc618912015-09-09 16:42:49 +08002192 spv::Id operand = spv::NoResult;
2193
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002194 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2195
John Kessenichfb4f2332019-08-09 03:49:15 -06002196#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002197 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2198 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002199 node->getOp() == glslang::EOpAtomicCounter ||
Neslisah Torosdagli7d37a682020-03-26 10:52:33 -04002200 node->getOp() == glslang::EOpInterpolateAtCentroid ||
2201 node->getOp() == glslang::EOpRayQueryProceed ||
2202 node->getOp() == glslang::EOpRayQueryGetRayTMin ||
2203 node->getOp() == glslang::EOpRayQueryGetRayFlags ||
2204 node->getOp() == glslang::EOpRayQueryGetWorldRayOrigin ||
2205 node->getOp() == glslang::EOpRayQueryGetWorldRayDirection ||
2206 node->getOp() == glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque ||
2207 node->getOp() == glslang::EOpRayQueryTerminate ||
2208 node->getOp() == glslang::EOpRayQueryConfirmIntersection) {
Rex Xufc618912015-09-09 16:42:49 +08002209 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002210 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2211 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2212 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002213#endif
2214 {
John Kessenich32cfd492016-02-02 12:37:46 -07002215 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002216 }
John Kessenich140f3df2015-06-26 16:58:36 -06002217
John Kessenichead86222018-03-28 18:01:20 -06002218 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002219 TranslateNoContractionDecoration(node->getType().getQualifier()),
2220 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002221
2222 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002223 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002224 result = createConversion(node->getOp(), decorations, resultType(), operand,
2225 node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002226
2227 // if not, then possibly an operation
2228 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002229 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand,
2230 node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002231
2232 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002233 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002234 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002235 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002236 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002237
John Kessenich140f3df2015-06-26 16:58:36 -06002238 builder.clearAccessChain();
2239 builder.setAccessChainRValue(result);
2240
2241 return false; // done with this node
2242 }
2243
2244 // it must be a special case, check...
2245 switch (node->getOp()) {
2246 case glslang::EOpPostIncrement:
2247 case glslang::EOpPostDecrement:
2248 case glslang::EOpPreIncrement:
2249 case glslang::EOpPreDecrement:
2250 {
2251 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002252 spv::Id one = 0;
2253 if (node->getBasicType() == glslang::EbtFloat)
2254 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002255#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002256 else if (node->getBasicType() == glslang::EbtDouble)
2257 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002258 else if (node->getBasicType() == glslang::EbtFloat16)
2259 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002260 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2261 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002262 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2263 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002264 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2265 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002266#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002267 else
2268 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002269 glslang::TOperator op;
2270 if (node->getOp() == glslang::EOpPreIncrement ||
2271 node->getOp() == glslang::EOpPostIncrement)
2272 op = glslang::EOpAdd;
2273 else
2274 op = glslang::EOpSub;
2275
John Kessenichead86222018-03-28 18:01:20 -06002276 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002277 convertGlslangToSpvType(node->getType()), operand, one,
2278 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002279 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002280
2281 // The result of operation is always stored, but conditionally the
2282 // consumed result. The consumed result is always an r-value.
2283 builder.accessChainStore(result);
2284 builder.clearAccessChain();
2285 if (node->getOp() == glslang::EOpPreIncrement ||
2286 node->getOp() == glslang::EOpPreDecrement)
2287 builder.setAccessChainRValue(result);
2288 else
2289 builder.setAccessChainRValue(operand);
2290 }
2291
2292 return false;
2293
John Kessenich155d3512019-08-08 23:29:20 -06002294#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002295 case glslang::EOpEmitStreamVertex:
2296 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2297 return false;
2298 case glslang::EOpEndStreamPrimitive:
2299 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2300 return false;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002301 case glslang::EOpRayQueryTerminate:
2302 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operand);
2303 return false;
2304 case glslang::EOpRayQueryConfirmIntersection:
2305 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operand);
2306 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002307#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002308
2309 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002310 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002311 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002312 }
John Kessenich140f3df2015-06-26 16:58:36 -06002313}
2314
Jeff Bolz53134492019-06-25 13:31:10 -05002315// Construct a composite object, recursively copying members if their types don't match
2316spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2317{
2318 for (int c = 0; c < (int)constituents.size(); ++c) {
2319 spv::Id& constituent = constituents[c];
2320 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2321 spv::Id rType = builder.getTypeId(constituent);
2322 if (lType != rType) {
2323 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2324 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2325 } else if (builder.isStructType(rType)) {
2326 std::vector<spv::Id> rTypeConstituents;
2327 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2328 for (int i = 0; i < numrTypeConstituents; ++i) {
John Kessenich8985fc92020-03-03 10:25:07 -07002329 rTypeConstituents.push_back(builder.createCompositeExtract(constituent,
2330 builder.getContainedTypeId(rType, i), i));
Jeff Bolz53134492019-06-25 13:31:10 -05002331 }
2332 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2333 } else {
2334 assert(builder.isArrayType(rType));
2335 std::vector<spv::Id> rTypeConstituents;
2336 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2337
2338 spv::Id elementRType = builder.getContainedTypeId(rType);
2339 for (int i = 0; i < numrTypeConstituents; ++i) {
2340 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2341 }
2342 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2343 }
2344 }
2345 }
2346 return builder.createCompositeConstruct(resultTypeId, constituents);
2347}
2348
John Kessenich140f3df2015-06-26 16:58:36 -06002349bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2350{
qining27e04a02016-04-14 16:40:20 -04002351 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2352 if (node->getType().getQualifier().isSpecConstant())
2353 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2354
John Kessenichfc51d282015-08-19 13:34:18 -06002355 spv::Id result = spv::NoResult;
John Kessenichbbbd9a22020-03-03 07:21:37 -07002356 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
John Kessenich8985fc92020-03-03 10:25:07 -07002357 spv::Builder::AccessChain complexLvalue; // for holding swizzling l-values too complex for SPIR-V,
2358 // for at out parameter
John Kessenichbbbd9a22020-03-03 07:21:37 -07002359 spv::Id temporaryLvalue = spv::NoResult; // temporary to pass, as proxy for complexLValue
2360
John Kessenich8985fc92020-03-03 10:25:07 -07002361 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2362 invertedType :
2363 convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002364
2365 // try texturing
2366 result = createImageTextureFunctionCall(node);
2367 if (result != spv::NoResult) {
2368 builder.clearAccessChain();
2369 builder.setAccessChainRValue(result);
2370
2371 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002372 }
2373#ifndef GLSLANG_WEB
2374 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002375 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002376 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002377 // "imageStore" is a special case, which has no result
2378 return false;
2379 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002380#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002381
John Kessenich140f3df2015-06-26 16:58:36 -06002382 glslang::TOperator binOp = glslang::EOpNull;
2383 bool reduceComparison = true;
2384 bool isMatrix = false;
2385 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002386 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002387
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002388 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2389
John Kessenich140f3df2015-06-26 16:58:36 -06002390 assert(node->getOp());
2391
John Kessenichf6640762016-08-01 19:44:00 -06002392 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002393
2394 switch (node->getOp()) {
2395 case glslang::EOpSequence:
2396 {
2397 if (preVisit)
2398 ++sequenceDepth;
2399 else
2400 --sequenceDepth;
2401
2402 if (sequenceDepth == 1) {
2403 // If this is the parent node of all the functions, we want to see them
2404 // early, so all call points have actual SPIR-V functions to reference.
2405 // In all cases, still let the traverser visit the children for us.
2406 makeFunctions(node->getAsAggregate()->getSequence());
2407
John Kessenich6fccb3c2016-09-19 16:01:41 -06002408 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002409 // anything else gets there, so visit out of order, doing them all now.
2410 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2411
John Kessenich6a60c2f2016-12-08 21:01:59 -07002412 // Initializers are done, don't want to visit again, but functions and link objects need to be processed,
John Kessenich140f3df2015-06-26 16:58:36 -06002413 // so do them manually.
2414 visitFunctions(node->getAsAggregate()->getSequence());
2415
2416 return false;
2417 }
2418
2419 return true;
2420 }
2421 case glslang::EOpLinkerObjects:
2422 {
2423 if (visit == glslang::EvPreVisit)
2424 linkageOnly = true;
2425 else
2426 linkageOnly = false;
2427
2428 return true;
2429 }
2430 case glslang::EOpComma:
2431 {
2432 // processing from left to right naturally leaves the right-most
2433 // lying around in the access chain
2434 glslang::TIntermSequence& glslangOperands = node->getSequence();
2435 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2436 glslangOperands[i]->traverse(this);
2437
2438 return false;
2439 }
2440 case glslang::EOpFunction:
2441 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002442 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002443 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002444 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002445 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002446 } else {
2447 handleFunctionEntry(node);
2448 }
2449 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002450 if (inEntryPoint)
2451 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002452 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002453 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002454 }
2455
2456 return true;
2457 case glslang::EOpParameters:
2458 // Parameters will have been consumed by EOpFunction processing, but not
2459 // the body, so we still visited the function node's children, making this
2460 // child redundant.
2461 return false;
2462 case glslang::EOpFunctionCall:
2463 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002464 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002465 if (node->isUserDefined())
2466 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07002467 if (result) {
2468 builder.clearAccessChain();
2469 builder.setAccessChainRValue(result);
2470 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002471 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002472
2473 return false;
2474 }
2475 case glslang::EOpConstructMat2x2:
2476 case glslang::EOpConstructMat2x3:
2477 case glslang::EOpConstructMat2x4:
2478 case glslang::EOpConstructMat3x2:
2479 case glslang::EOpConstructMat3x3:
2480 case glslang::EOpConstructMat3x4:
2481 case glslang::EOpConstructMat4x2:
2482 case glslang::EOpConstructMat4x3:
2483 case glslang::EOpConstructMat4x4:
2484 case glslang::EOpConstructDMat2x2:
2485 case glslang::EOpConstructDMat2x3:
2486 case glslang::EOpConstructDMat2x4:
2487 case glslang::EOpConstructDMat3x2:
2488 case glslang::EOpConstructDMat3x3:
2489 case glslang::EOpConstructDMat3x4:
2490 case glslang::EOpConstructDMat4x2:
2491 case glslang::EOpConstructDMat4x3:
2492 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002493 case glslang::EOpConstructIMat2x2:
2494 case glslang::EOpConstructIMat2x3:
2495 case glslang::EOpConstructIMat2x4:
2496 case glslang::EOpConstructIMat3x2:
2497 case glslang::EOpConstructIMat3x3:
2498 case glslang::EOpConstructIMat3x4:
2499 case glslang::EOpConstructIMat4x2:
2500 case glslang::EOpConstructIMat4x3:
2501 case glslang::EOpConstructIMat4x4:
2502 case glslang::EOpConstructUMat2x2:
2503 case glslang::EOpConstructUMat2x3:
2504 case glslang::EOpConstructUMat2x4:
2505 case glslang::EOpConstructUMat3x2:
2506 case glslang::EOpConstructUMat3x3:
2507 case glslang::EOpConstructUMat3x4:
2508 case glslang::EOpConstructUMat4x2:
2509 case glslang::EOpConstructUMat4x3:
2510 case glslang::EOpConstructUMat4x4:
2511 case glslang::EOpConstructBMat2x2:
2512 case glslang::EOpConstructBMat2x3:
2513 case glslang::EOpConstructBMat2x4:
2514 case glslang::EOpConstructBMat3x2:
2515 case glslang::EOpConstructBMat3x3:
2516 case glslang::EOpConstructBMat3x4:
2517 case glslang::EOpConstructBMat4x2:
2518 case glslang::EOpConstructBMat4x3:
2519 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002520 case glslang::EOpConstructF16Mat2x2:
2521 case glslang::EOpConstructF16Mat2x3:
2522 case glslang::EOpConstructF16Mat2x4:
2523 case glslang::EOpConstructF16Mat3x2:
2524 case glslang::EOpConstructF16Mat3x3:
2525 case glslang::EOpConstructF16Mat3x4:
2526 case glslang::EOpConstructF16Mat4x2:
2527 case glslang::EOpConstructF16Mat4x3:
2528 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002529 isMatrix = true;
2530 // fall through
2531 case glslang::EOpConstructFloat:
2532 case glslang::EOpConstructVec2:
2533 case glslang::EOpConstructVec3:
2534 case glslang::EOpConstructVec4:
2535 case glslang::EOpConstructDouble:
2536 case glslang::EOpConstructDVec2:
2537 case glslang::EOpConstructDVec3:
2538 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002539 case glslang::EOpConstructFloat16:
2540 case glslang::EOpConstructF16Vec2:
2541 case glslang::EOpConstructF16Vec3:
2542 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002543 case glslang::EOpConstructBool:
2544 case glslang::EOpConstructBVec2:
2545 case glslang::EOpConstructBVec3:
2546 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002547 case glslang::EOpConstructInt8:
2548 case glslang::EOpConstructI8Vec2:
2549 case glslang::EOpConstructI8Vec3:
2550 case glslang::EOpConstructI8Vec4:
2551 case glslang::EOpConstructUint8:
2552 case glslang::EOpConstructU8Vec2:
2553 case glslang::EOpConstructU8Vec3:
2554 case glslang::EOpConstructU8Vec4:
2555 case glslang::EOpConstructInt16:
2556 case glslang::EOpConstructI16Vec2:
2557 case glslang::EOpConstructI16Vec3:
2558 case glslang::EOpConstructI16Vec4:
2559 case glslang::EOpConstructUint16:
2560 case glslang::EOpConstructU16Vec2:
2561 case glslang::EOpConstructU16Vec3:
2562 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002563 case glslang::EOpConstructInt:
2564 case glslang::EOpConstructIVec2:
2565 case glslang::EOpConstructIVec3:
2566 case glslang::EOpConstructIVec4:
2567 case glslang::EOpConstructUint:
2568 case glslang::EOpConstructUVec2:
2569 case glslang::EOpConstructUVec3:
2570 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002571 case glslang::EOpConstructInt64:
2572 case glslang::EOpConstructI64Vec2:
2573 case glslang::EOpConstructI64Vec3:
2574 case glslang::EOpConstructI64Vec4:
2575 case glslang::EOpConstructUint64:
2576 case glslang::EOpConstructU64Vec2:
2577 case glslang::EOpConstructU64Vec3:
2578 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002579 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002580 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002581 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002582 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002583 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002584 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002585 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002586 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002587 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002588 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002589 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002590 else if (node->getOp() == glslang::EOpConstructStruct ||
2591 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2592 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002593 std::vector<spv::Id> constituents;
2594 for (int c = 0; c < (int)arguments.size(); ++c)
2595 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002596 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002597 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002598 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002599 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002600 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002601
2602 builder.clearAccessChain();
2603 builder.setAccessChainRValue(constructed);
2604
2605 return false;
2606 }
2607
2608 // These six are component-wise compares with component-wise results.
2609 // Forward on to createBinaryOperation(), requesting a vector result.
2610 case glslang::EOpLessThan:
2611 case glslang::EOpGreaterThan:
2612 case glslang::EOpLessThanEqual:
2613 case glslang::EOpGreaterThanEqual:
2614 case glslang::EOpVectorEqual:
2615 case glslang::EOpVectorNotEqual:
2616 {
2617 // Map the operation to a binary
2618 binOp = node->getOp();
2619 reduceComparison = false;
2620 switch (node->getOp()) {
2621 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2622 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2623 default: binOp = node->getOp(); break;
2624 }
2625
2626 break;
2627 }
2628 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002629 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002630 binOp = glslang::EOpMul;
2631 break;
2632 case glslang::EOpOuterProduct:
2633 // two vectors multiplied to make a matrix
2634 binOp = glslang::EOpOuterProduct;
2635 break;
2636 case glslang::EOpDot:
2637 {
qining25262b32016-05-06 17:25:16 -04002638 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002639 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002640 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002641 binOp = glslang::EOpMul;
2642 break;
2643 }
2644 case glslang::EOpMod:
2645 // when an aggregate, this is the floating-point mod built-in function,
2646 // which can be emitted by the one in createBinaryOperation()
2647 binOp = glslang::EOpMod;
2648 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002649
John Kessenich140f3df2015-06-26 16:58:36 -06002650 case glslang::EOpEmitVertex:
2651 case glslang::EOpEndPrimitive:
2652 case glslang::EOpBarrier:
2653 case glslang::EOpMemoryBarrier:
2654 case glslang::EOpMemoryBarrierAtomicCounter:
2655 case glslang::EOpMemoryBarrierBuffer:
2656 case glslang::EOpMemoryBarrierImage:
2657 case glslang::EOpMemoryBarrierShared:
2658 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002659 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002660 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002661 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002662 case glslang::EOpWorkgroupMemoryBarrier:
2663 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002664 case glslang::EOpSubgroupBarrier:
2665 case glslang::EOpSubgroupMemoryBarrier:
2666 case glslang::EOpSubgroupMemoryBarrierBuffer:
2667 case glslang::EOpSubgroupMemoryBarrierImage:
2668 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002669 noReturnValue = true;
2670 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2671 break;
2672
John Kessenich426394d2015-07-23 10:22:48 -06002673 case glslang::EOpAtomicAdd:
2674 case glslang::EOpAtomicMin:
2675 case glslang::EOpAtomicMax:
2676 case glslang::EOpAtomicAnd:
2677 case glslang::EOpAtomicOr:
2678 case glslang::EOpAtomicXor:
2679 case glslang::EOpAtomicExchange:
2680 case glslang::EOpAtomicCompSwap:
2681 atomic = true;
2682 break;
2683
John Kesseniche5eee8f2019-10-18 01:03:11 -06002684#ifndef GLSLANG_WEB
2685 case glslang::EOpAtomicStore:
2686 noReturnValue = true;
2687 // fallthrough
2688 case glslang::EOpAtomicLoad:
2689 atomic = true;
2690 break;
2691
John Kessenich0d0c6d32017-07-23 16:08:26 -06002692 case glslang::EOpAtomicCounterAdd:
2693 case glslang::EOpAtomicCounterSubtract:
2694 case glslang::EOpAtomicCounterMin:
2695 case glslang::EOpAtomicCounterMax:
2696 case glslang::EOpAtomicCounterAnd:
2697 case glslang::EOpAtomicCounterOr:
2698 case glslang::EOpAtomicCounterXor:
2699 case glslang::EOpAtomicCounterExchange:
2700 case glslang::EOpAtomicCounterCompSwap:
2701 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2702 builder.addCapability(spv::CapabilityAtomicStorageOps);
2703 atomic = true;
2704 break;
2705
Ian Romanickb3bd4022019-01-21 08:57:25 -08002706 case glslang::EOpAbsDifference:
2707 case glslang::EOpAddSaturate:
2708 case glslang::EOpSubSaturate:
2709 case glslang::EOpAverage:
2710 case glslang::EOpAverageRounded:
2711 case glslang::EOpMul32x16:
2712 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2713 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2714 binOp = node->getOp();
2715 break;
2716
Daniel Kochdb32b242020-03-17 20:42:47 -04002717 case glslang::EOpIgnoreIntersection:
2718 case glslang::EOpTerminateRay:
2719 case glslang::EOpTrace:
2720 case glslang::EOpExecuteCallable:
Chao Chen3c366992018-09-19 11:41:59 -07002721 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2722 noReturnValue = true;
2723 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04002724 case glslang::EOpRayQueryInitialize:
2725 case glslang::EOpRayQueryTerminate:
2726 case glslang::EOpRayQueryGenerateIntersection:
2727 case glslang::EOpRayQueryConfirmIntersection:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002728 builder.addExtension("SPV_KHR_ray_query");
2729 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
Torosdagli06c2eee2020-03-19 11:09:57 -04002730 noReturnValue = true;
2731 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002732 case glslang::EOpRayQueryProceed:
2733 case glslang::EOpRayQueryGetIntersectionType:
2734 case glslang::EOpRayQueryGetRayTMin:
2735 case glslang::EOpRayQueryGetRayFlags:
2736 case glslang::EOpRayQueryGetIntersectionT:
2737 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2738 case glslang::EOpRayQueryGetIntersectionInstanceId:
2739 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2740 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2741 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2742 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2743 case glslang::EOpRayQueryGetIntersectionFrontFace:
2744 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
2745 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2746 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2747 case glslang::EOpRayQueryGetWorldRayDirection:
2748 case glslang::EOpRayQueryGetWorldRayOrigin:
2749 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2750 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2751 builder.addExtension("SPV_KHR_ray_query");
2752 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
2753 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002754 case glslang::EOpCooperativeMatrixLoad:
2755 case glslang::EOpCooperativeMatrixStore:
2756 noReturnValue = true;
2757 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002758 case glslang::EOpBeginInvocationInterlock:
2759 case glslang::EOpEndInvocationInterlock:
2760 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2761 noReturnValue = true;
2762 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002763#endif
Chao Chen3c366992018-09-19 11:41:59 -07002764
Jeff Bolz04d73732019-05-31 13:06:01 -05002765 case glslang::EOpDebugPrintf:
2766 noReturnValue = true;
2767 break;
2768
John Kessenich140f3df2015-06-26 16:58:36 -06002769 default:
2770 break;
2771 }
2772
2773 //
2774 // See if it maps to a regular operation.
2775 //
John Kessenich140f3df2015-06-26 16:58:36 -06002776 if (binOp != glslang::EOpNull) {
2777 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2778 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2779 assert(left && right);
2780
2781 builder.clearAccessChain();
2782 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002783 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002784
2785 builder.clearAccessChain();
2786 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002787 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002788
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002789 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002790 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002791 TranslateNoContractionDecoration(node->getType().getQualifier()),
2792 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002793 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002794 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002795 left->getType().getBasicType(), reduceComparison);
2796
2797 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002798 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002799 builder.clearAccessChain();
2800 builder.setAccessChainRValue(result);
2801
2802 return false;
2803 }
2804
John Kessenich426394d2015-07-23 10:22:48 -06002805 //
2806 // Create the list of operands.
2807 //
John Kessenich140f3df2015-06-26 16:58:36 -06002808 glslang::TIntermSequence& glslangOperands = node->getSequence();
2809 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002810 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002811 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002812 // special case l-value operands; there are just a few
2813 bool lvalue = false;
2814 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002815 case glslang::EOpModf:
2816 if (arg == 1)
2817 lvalue = true;
2818 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002819
Torosdagli06c2eee2020-03-19 11:09:57 -04002820 case glslang::EOpRayQueryInitialize:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002821 case glslang::EOpRayQueryTerminate:
2822 case glslang::EOpRayQueryConfirmIntersection:
2823 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04002824 case glslang::EOpRayQueryGenerateIntersection:
2825 case glslang::EOpRayQueryGetIntersectionType:
2826 case glslang::EOpRayQueryGetIntersectionT:
2827 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2828 case glslang::EOpRayQueryGetIntersectionInstanceId:
2829 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2830 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2831 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2832 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2833 case glslang::EOpRayQueryGetIntersectionFrontFace:
2834 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2835 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2836 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2837 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2838 if (arg == 0)
2839 lvalue = true;
2840 break;
2841
John Kesseniche5eee8f2019-10-18 01:03:11 -06002842 case glslang::EOpAtomicAdd:
2843 case glslang::EOpAtomicMin:
2844 case glslang::EOpAtomicMax:
2845 case glslang::EOpAtomicAnd:
2846 case glslang::EOpAtomicOr:
2847 case glslang::EOpAtomicXor:
2848 case glslang::EOpAtomicExchange:
2849 case glslang::EOpAtomicCompSwap:
2850 if (arg == 0)
2851 lvalue = true;
2852 break;
2853
John Kessenicha28f7a72019-08-06 07:00:58 -06002854#ifndef GLSLANG_WEB
2855 case glslang::EOpFrexp:
2856 if (arg == 1)
2857 lvalue = true;
2858 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002859 case glslang::EOpInterpolateAtSample:
2860 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002861 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002862 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002863 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002864
2865 // Does it need a swizzle inversion? If so, evaluation is inverted;
2866 // operate first on the swizzle base, then apply the swizzle.
John Kessenichbbbd9a22020-03-03 07:21:37 -07002867 // That is, we transform
2868 //
2869 // interpolate(v.zy) -> interpolate(v).zy
2870 //
John Kessenichecba76f2017-01-06 00:34:48 -07002871 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002872 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
John Kessenich8985fc92020-03-03 10:25:07 -07002873 invertedType = convertGlslangToSpvType(
2874 glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
John Kessenich8c8505c2016-07-26 12:50:38 -06002875 }
Rex Xu7a26c172015-12-08 17:12:09 +08002876 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002877 case glslang::EOpAtomicLoad:
2878 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002879 case glslang::EOpAtomicCounterAdd:
2880 case glslang::EOpAtomicCounterSubtract:
2881 case glslang::EOpAtomicCounterMin:
2882 case glslang::EOpAtomicCounterMax:
2883 case glslang::EOpAtomicCounterAnd:
2884 case glslang::EOpAtomicCounterOr:
2885 case glslang::EOpAtomicCounterXor:
2886 case glslang::EOpAtomicCounterExchange:
2887 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002888 if (arg == 0)
2889 lvalue = true;
2890 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002891 case glslang::EOpAddCarry:
2892 case glslang::EOpSubBorrow:
2893 if (arg == 2)
2894 lvalue = true;
2895 break;
2896 case glslang::EOpUMulExtended:
2897 case glslang::EOpIMulExtended:
2898 if (arg >= 2)
2899 lvalue = true;
2900 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002901 case glslang::EOpCooperativeMatrixLoad:
2902 if (arg == 0 || arg == 1)
2903 lvalue = true;
2904 break;
2905 case glslang::EOpCooperativeMatrixStore:
2906 if (arg == 1)
2907 lvalue = true;
2908 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002909#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002910 default:
2911 break;
2912 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002913 builder.clearAccessChain();
2914 if (invertedType != spv::NoType && arg == 0)
2915 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2916 else
2917 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002918
John Kessenichb9197c82019-08-11 07:41:45 -06002919#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002920 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2921 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2922
2923 if (arg == 1) {
2924 // fold "element" parameter into the access chain
2925 spv::Builder::AccessChain save = builder.getAccessChain();
2926 builder.clearAccessChain();
2927 glslangOperands[2]->traverse(this);
2928
2929 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2930
2931 builder.setAccessChain(save);
2932
2933 // Point to the first element of the array.
John Kessenich8985fc92020-03-03 10:25:07 -07002934 builder.accessChainPush(elementId,
2935 TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
2936 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002937
2938 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2939 unsigned int alignment = builder.getAccessChain().alignment;
2940
2941 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2942 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2943 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2944 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2945 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
John Kessenich8985fc92020-03-03 10:25:07 -07002946 if (builder.getStorageClass(builder.getAccessChain().base) ==
2947 spv::StorageClassPhysicalStorageBufferEXT) {
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002948 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2949 }
2950
2951 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2952
2953 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2954 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2955 }
2956
John Kessenich8985fc92020-03-03 10:25:07 -07002957 if (memoryAccess &
2958 (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2959 memoryAccessOperands.push_back(spv::IdImmediate(true,
2960 builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002961 }
2962 } else if (arg == 2) {
2963 continue;
2964 }
2965 }
John Kessenichb9197c82019-08-11 07:41:45 -06002966#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002967
John Kessenichbbbd9a22020-03-03 07:21:37 -07002968 // for l-values, pass the address, for r-values, pass the value
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002969 if (lvalue) {
John Kessenichbbbd9a22020-03-03 07:21:37 -07002970 if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
2971 // SPIR-V cannot represent an l-value containing a swizzle that doesn't
2972 // reduce to a simple access chain. So, we need a temporary vector to
2973 // receive the result, and must later swizzle that into the original
2974 // l-value.
2975 complexLvalue = builder.getAccessChain();
John Kessenich8985fc92020-03-03 10:25:07 -07002976 temporaryLvalue = builder.createVariable(spv::StorageClassFunction,
2977 builder.accessChainGetInferredType(), "swizzleTemp");
John Kessenichbbbd9a22020-03-03 07:21:37 -07002978 operands.push_back(temporaryLvalue);
2979 } else {
2980 operands.push_back(builder.accessChainGetLValue());
2981 }
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002982 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2983 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2984 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002985 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Torosdagli06c2eee2020-03-19 11:09:57 -04002986 glslang::TOperator glslangOp = node->getOp();
2987 if (arg == 1 &&
2988 (glslangOp == glslang::EOpRayQueryGetIntersectionType ||
2989 glslangOp == glslang::EOpRayQueryGetIntersectionT ||
2990 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceCustomIndex ||
2991 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceId ||
2992 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset ||
2993 glslangOp == glslang::EOpRayQueryGetIntersectionGeometryIndex ||
2994 glslangOp == glslang::EOpRayQueryGetIntersectionPrimitiveIndex ||
2995 glslangOp == glslang::EOpRayQueryGetIntersectionBarycentrics ||
2996 glslangOp == glslang::EOpRayQueryGetIntersectionFrontFace ||
2997 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayDirection ||
2998 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayOrigin ||
2999 glslangOp == glslang::EOpRayQueryGetIntersectionObjectToWorld ||
3000 glslangOp == glslang::EOpRayQueryGetIntersectionWorldToObject
3001 )) {
3002 bool cond = glslangOperands[arg]->getAsConstantUnion()->getConstArray()[0].getBConst();
3003 operands.push_back(builder.makeIntConstant(cond ? 1 : 0));
3004 }
3005 else {
3006 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
3007 }
3008
John Kesseniche485c7a2017-05-31 18:50:53 -06003009 }
John Kessenich140f3df2015-06-26 16:58:36 -06003010 }
John Kessenich426394d2015-07-23 10:22:48 -06003011
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003012 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06003013#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003014 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
3015 std::vector<spv::IdImmediate> idImmOps;
3016
3017 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3018 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3019 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3020 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3021 // get the pointee type
3022 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
3023 assert(builder.isCooperativeMatrixType(typeId));
3024 // do the op
3025 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
3026 // store the result to the pointer (out param 'm')
3027 builder.createStore(result, operands[0]);
3028 result = 0;
3029 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
3030 std::vector<spv::IdImmediate> idImmOps;
3031
3032 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3033 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
3034 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3035 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3036 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3037
3038 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
3039 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06003040 } else
3041#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06003042 if (atomic) {
3043 // Handle all atomics
John Kessenich8985fc92020-03-03 10:25:07 -07003044 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
3045 lvalueCoherentFlags);
Jeff Bolz04d73732019-05-31 13:06:01 -05003046 } else if (node->getOp() == glslang::EOpDebugPrintf) {
3047 if (!nonSemanticDebugPrintf) {
3048 nonSemanticDebugPrintf = builder.import("NonSemantic.DebugPrintf");
3049 }
3050 result = builder.createBuiltinCall(builder.makeVoidType(), nonSemanticDebugPrintf, spv::NonSemanticDebugPrintfDebugPrintf, operands);
3051 builder.addExtension(spv::E_SPV_KHR_non_semantic_info);
John Kesseniche5eee8f2019-10-18 01:03:11 -06003052 } else {
John Kessenich426394d2015-07-23 10:22:48 -06003053 // Pass through to generic operations.
3054 switch (glslangOperands.size()) {
3055 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06003056 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06003057 break;
3058 case 1:
John Kessenichead86222018-03-28 18:01:20 -06003059 {
3060 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06003061 TranslateNoContractionDecoration(node->getType().getQualifier()),
3062 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06003063 result = createUnaryOperation(
3064 node->getOp(), decorations,
3065 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003066 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06003067 }
John Kessenich426394d2015-07-23 10:22:48 -06003068 break;
3069 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06003070 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06003071 break;
3072 }
John Kessenichbbbd9a22020-03-03 07:21:37 -07003073 if (invertedType != spv::NoResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003074 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenichbbbd9a22020-03-03 07:21:37 -07003075 else if (temporaryLvalue != spv::NoResult) {
3076 builder.setAccessChain(complexLvalue);
3077 builder.accessChainStore(builder.createLoad(temporaryLvalue));
3078 }
John Kessenich140f3df2015-06-26 16:58:36 -06003079 }
3080
3081 if (noReturnValue)
3082 return false;
3083
3084 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04003085 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07003086 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06003087 } else {
3088 builder.clearAccessChain();
3089 builder.setAccessChainRValue(result);
3090 return false;
3091 }
3092}
3093
John Kessenich433e9ff2017-01-26 20:31:11 -07003094// This path handles both if-then-else and ?:
3095// The if-then-else has a node type of void, while
3096// ?: has either a void or a non-void node type
3097//
3098// Leaving the result, when not void:
3099// GLSL only has r-values as the result of a :?, but
3100// if we have an l-value, that can be more efficient if it will
3101// become the base of a complex r-value expression, because the
3102// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06003103bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
3104{
John Kessenich0c1e71a2019-01-10 18:23:06 +07003105 // see if OpSelect can handle it
3106 const auto isOpSelectable = [&]() {
3107 if (node->getBasicType() == glslang::EbtVoid)
3108 return false;
3109 // OpSelect can do all other types starting with SPV 1.4
3110 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
3111 // pre-1.4, only scalars and vectors can be handled
3112 if ((!node->getType().isScalar() && !node->getType().isVector()))
3113 return false;
3114 }
3115 return true;
3116 };
3117
John Kessenich4bee5312018-02-20 21:29:05 -07003118 // See if it simple and safe, or required, to execute both sides.
3119 // Crucially, side effects must be either semantically required or avoided,
3120 // and there are performance trade-offs.
3121 // Return true if required or a good idea (and safe) to execute both sides,
3122 // false otherwise.
3123 const auto bothSidesPolicy = [&]() -> bool {
3124 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07003125 if (node->getTrueBlock() == nullptr ||
3126 node->getFalseBlock() == nullptr)
3127 return false;
3128
John Kessenich4bee5312018-02-20 21:29:05 -07003129 // required? (unless we write additional code to look for side effects
3130 // and make performance trade-offs if none are present)
3131 if (!node->getShortCircuit())
3132 return true;
3133
3134 // if not required to execute both, decide based on performance/practicality...
3135
John Kessenich0c1e71a2019-01-10 18:23:06 +07003136 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07003137 return false;
3138
John Kessenich433e9ff2017-01-26 20:31:11 -07003139 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
3140 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
3141
3142 // return true if a single operand to ? : is okay for OpSelect
3143 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003144 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07003145 };
3146
3147 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
3148 operandOkay(node->getFalseBlock()->getAsTyped());
3149 };
3150
John Kessenich4bee5312018-02-20 21:29:05 -07003151 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
3152 // emit the condition before doing anything with selection
3153 node->getCondition()->traverse(this);
3154 spv::Id condition = accessChainLoad(node->getCondition()->getType());
3155
3156 // Find a way of executing both sides and selecting the right result.
3157 const auto executeBothSides = [&]() -> void {
3158 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07003159 node->getTrueBlock()->traverse(this);
3160 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3161 node->getFalseBlock()->traverse(this);
3162 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3163
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003164 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003165
John Kessenich4bee5312018-02-20 21:29:05 -07003166 // done if void
3167 if (node->getBasicType() == glslang::EbtVoid)
3168 return;
John Kesseniche434ad92017-03-30 10:09:28 -06003169
John Kessenich4bee5312018-02-20 21:29:05 -07003170 // emit code to select between trueValue and falseValue
3171
3172 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07003173 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07003174 // Emit OpSelect for this selection.
3175
3176 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07003177 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
3178 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07003179 condition = builder.smearScalar(spv::NoPrecision, condition,
3180 builder.makeVectorType(builder.makeBoolType(),
3181 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07003182 }
John Kessenich4bee5312018-02-20 21:29:05 -07003183
3184 // OpSelect
3185 result = builder.createTriOp(spv::OpSelect,
3186 convertGlslangToSpvType(node->getType()), condition,
3187 trueValue, falseValue);
3188
3189 builder.clearAccessChain();
3190 builder.setAccessChainRValue(result);
3191 } else {
3192 // We need control flow to select the result.
3193 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
3194 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
3195
3196 // Selection control:
3197 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3198
3199 // make an "if" based on the value created by the condition
3200 spv::Builder::If ifBuilder(condition, control, builder);
3201
3202 // emit the "then" statement
3203 builder.createStore(trueValue, result);
3204 ifBuilder.makeBeginElse();
3205 // emit the "else" statement
3206 builder.createStore(falseValue, result);
3207
3208 // finish off the control flow
3209 ifBuilder.makeEndIf();
3210
3211 builder.clearAccessChain();
3212 builder.setAccessChainLValue(result);
3213 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003214 };
3215
John Kessenich4bee5312018-02-20 21:29:05 -07003216 // Execute the one side needed, as per the condition
3217 const auto executeOneSide = [&]() {
3218 // Always emit control flow.
3219 if (node->getBasicType() != glslang::EbtVoid)
3220 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07003221
John Kessenich4bee5312018-02-20 21:29:05 -07003222 // Selection control:
3223 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3224
3225 // make an "if" based on the value created by the condition
3226 spv::Builder::If ifBuilder(condition, control, builder);
3227
3228 // emit the "then" statement
3229 if (node->getTrueBlock() != nullptr) {
3230 node->getTrueBlock()->traverse(this);
3231 if (result != spv::NoResult)
3232 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3233 }
3234
3235 if (node->getFalseBlock() != nullptr) {
3236 ifBuilder.makeBeginElse();
3237 // emit the "else" statement
3238 node->getFalseBlock()->traverse(this);
3239 if (result != spv::NoResult)
3240 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3241 }
3242
3243 // finish off the control flow
3244 ifBuilder.makeEndIf();
3245
3246 if (result != spv::NoResult) {
3247 builder.clearAccessChain();
3248 builder.setAccessChainLValue(result);
3249 }
3250 };
3251
3252 // Try for OpSelect (or a requirement to execute both sides)
3253 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003254 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3255 if (node->getType().getQualifier().isSpecConstant())
3256 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003257 executeBothSides();
3258 } else
3259 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003260
3261 return false;
3262}
3263
3264bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3265{
3266 // emit and get the condition before doing anything with switch
3267 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003268 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003269
Rex Xu57e65922017-07-04 23:23:40 +08003270 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003271 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003272
John Kessenich140f3df2015-06-26 16:58:36 -06003273 // browse the children to sort out code segments
3274 int defaultSegment = -1;
3275 std::vector<TIntermNode*> codeSegments;
3276 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3277 std::vector<int> caseValues;
3278 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3279 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3280 TIntermNode* child = *c;
3281 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003282 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003283 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003284 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich8985fc92020-03-03 10:25:07 -07003285 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()
3286 ->getConstArray()[0].getIConst());
John Kessenich140f3df2015-06-26 16:58:36 -06003287 } else
3288 codeSegments.push_back(child);
3289 }
3290
qining25262b32016-05-06 17:25:16 -04003291 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003292 // statements between the last case and the end of the switch statement
3293 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3294 (int)codeSegments.size() == defaultSegment)
3295 codeSegments.push_back(nullptr);
3296
3297 // make the switch statement
3298 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
John Kessenich8985fc92020-03-03 10:25:07 -07003299 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment,
3300 segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003301
3302 // emit all the code in the segments
3303 breakForLoop.push(false);
3304 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3305 builder.nextSwitchSegment(segmentBlocks, s);
3306 if (codeSegments[s])
3307 codeSegments[s]->traverse(this);
3308 else
3309 builder.addSwitchBreak();
3310 }
3311 breakForLoop.pop();
3312
3313 builder.endSwitch(segmentBlocks);
3314
3315 return false;
3316}
3317
3318void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3319{
3320 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003321 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003322
3323 builder.clearAccessChain();
3324 builder.setAccessChainRValue(constant);
3325}
3326
3327bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3328{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003329 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003330 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003331
3332 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003333 std::vector<unsigned int> operands;
3334 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003335
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003336 // Spec requires back edges to target header blocks, and every header block
3337 // must dominate its merge block. Make a header block first to ensure these
3338 // conditions are met. By definition, it will contain OpLoopMerge, followed
3339 // by a block-ending branch. But we don't want to put any other body/test
3340 // instructions in it, since the body/test may have arbitrary instructions,
3341 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003342 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003343 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003344 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003345 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003346 spv::Block& test = builder.makeNewBlock();
3347 builder.createBranch(&test);
3348
3349 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003350 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003351 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003352 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3353
3354 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003355 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003356 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003357 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003358 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003359 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003360
3361 builder.setBuildPoint(&blocks.continue_target);
3362 if (node->getTerminal())
3363 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003364 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003365 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003366 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003367 builder.createBranch(&blocks.body);
3368
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003369 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003370 builder.setBuildPoint(&blocks.body);
3371 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003372 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003373 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003374 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003375
3376 builder.setBuildPoint(&blocks.continue_target);
3377 if (node->getTerminal())
3378 node->getTerminal()->traverse(this);
3379 if (node->getTest()) {
3380 node->getTest()->traverse(this);
3381 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003382 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003383 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003384 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003385 // TODO: unless there was a break/return/discard instruction
3386 // somewhere in the body, this is an infinite loop, so we should
3387 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003388 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003389 }
John Kessenich140f3df2015-06-26 16:58:36 -06003390 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003391 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003392 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003393 return false;
3394}
3395
3396bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3397{
3398 if (node->getExpression())
3399 node->getExpression()->traverse(this);
3400
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003401 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003402
John Kessenich140f3df2015-06-26 16:58:36 -06003403 switch (node->getFlowOp()) {
3404 case glslang::EOpKill:
3405 builder.makeDiscard();
3406 break;
3407 case glslang::EOpBreak:
3408 if (breakForLoop.top())
3409 builder.createLoopExit();
3410 else
3411 builder.addSwitchBreak();
3412 break;
3413 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003414 builder.createLoopContinue();
3415 break;
3416 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003417 if (node->getExpression()) {
3418 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3419 spv::Id returnId = accessChainLoad(glslangReturnType);
3420 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3421 builder.clearAccessChain();
3422 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3423 builder.setAccessChainLValue(copyId);
3424 multiTypeStore(glslangReturnType, returnId);
3425 returnId = builder.createLoad(copyId);
3426 }
3427 builder.makeReturn(false, returnId);
3428 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003429 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003430
3431 builder.clearAccessChain();
3432 break;
3433
John Kessenichb9197c82019-08-11 07:41:45 -06003434#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003435 case glslang::EOpDemote:
3436 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3437 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3438 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3439 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003440#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003441
John Kessenich140f3df2015-06-26 16:58:36 -06003442 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003443 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003444 break;
3445 }
3446
3447 return false;
3448}
3449
John Kessenich9c14f772019-06-17 08:38:35 -06003450spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003451{
qining25262b32016-05-06 17:25:16 -04003452 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003453 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003454 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003455 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003456 spv::Id result = createSpvConstant(*node);
3457 if (result != spv::NoResult)
3458 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003459 }
3460
3461 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003462 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003463 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3464 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003465
John Kessenichb9197c82019-08-11 07:41:45 -06003466 const bool contains16BitType = node->getType().contains16BitFloat() ||
3467 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003468 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003469 switch (storageClass) {
3470 case spv::StorageClassInput:
3471 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003472 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003473 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003474 break;
John Kessenich18310872018-05-14 22:08:53 -06003475 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003476 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003477 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3478 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003479 else
3480 builder.addCapability(spv::CapabilityStorageUniform16);
3481 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003482#ifndef GLSLANG_WEB
3483 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003484 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003485 builder.addCapability(spv::CapabilityStoragePushConstant16);
3486 break;
John Kessenich18310872018-05-14 22:08:53 -06003487 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003488 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003489 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003490 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3491 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003492#endif
John Kessenich18310872018-05-14 22:08:53 -06003493 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003494 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003495 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003496 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003497 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003498 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003499 }
3500 }
Rex Xuf89ad982017-04-07 23:22:33 +08003501
John Kessenichb9197c82019-08-11 07:41:45 -06003502 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003503 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003504 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003505 builder.addCapability(spv::CapabilityStoragePushConstant8);
3506 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003507 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003508 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003509 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003510 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003511 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003512 } else {
3513 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003514 }
3515 }
3516
John Kessenich140f3df2015-06-26 16:58:36 -06003517 const char* name = node->getName().c_str();
3518 if (glslang::IsAnonymous(name))
3519 name = "";
3520
3521 return builder.createVariable(storageClass, spvType, name);
3522}
3523
3524// Return type Id of the sampled type.
3525spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3526{
3527 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003528 case glslang::EbtInt: return builder.makeIntType(32);
3529 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003530 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003531#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003532 case glslang::EbtFloat16:
3533 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3534 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3535 return builder.makeFloatType(16);
3536#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003537 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003538 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003539 return builder.makeFloatType(32);
3540 }
3541}
3542
John Kessenich8c8505c2016-07-26 12:50:38 -06003543// If node is a swizzle operation, return the type that should be used if
3544// the swizzle base is first consumed by another operation, before the swizzle
3545// is applied.
3546spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3547{
John Kessenichecba76f2017-01-06 00:34:48 -07003548 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003549 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3550 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3551 else
3552 return spv::NoType;
3553}
3554
3555// When inverting a swizzle with a parent op, this function
3556// will apply the swizzle operation to a completed parent operation.
John Kessenich8985fc92020-03-03 10:25:07 -07003557spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
3558 spv::Id parentResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003559{
3560 std::vector<unsigned> swizzle;
3561 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3562 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3563}
3564
John Kessenich8c8505c2016-07-26 12:50:38 -06003565// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3566void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3567{
3568 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3569 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3570 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3571}
3572
John Kessenich3ac051e2015-12-20 11:29:16 -07003573// Convert from a glslang type to an SPV type, by calling into a
3574// recursive version of this function. This establishes the inherited
3575// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003576spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003577{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003578 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003579}
3580
3581// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003582// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003583// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003584spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003585 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3586 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003587{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003588 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003589
3590 switch (type.getBasicType()) {
3591 case glslang::EbtVoid:
3592 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003593 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003594 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003595 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003596 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3597 // a 32-bit int where non-0 means true.
3598 if (explicitLayout != glslang::ElpNone)
3599 spvType = builder.makeUintType(32);
3600 else
3601 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003602 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003603 case glslang::EbtInt:
3604 spvType = builder.makeIntType(32);
3605 break;
3606 case glslang::EbtUint:
3607 spvType = builder.makeUintType(32);
3608 break;
3609 case glslang::EbtFloat:
3610 spvType = builder.makeFloatType(32);
3611 break;
3612#ifndef GLSLANG_WEB
3613 case glslang::EbtDouble:
3614 spvType = builder.makeFloatType(64);
3615 break;
3616 case glslang::EbtFloat16:
3617 spvType = builder.makeFloatType(16);
3618 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003619 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003620 spvType = builder.makeIntType(8);
3621 break;
3622 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003623 spvType = builder.makeUintType(8);
3624 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003625 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003626 spvType = builder.makeIntType(16);
3627 break;
3628 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003629 spvType = builder.makeUintType(16);
3630 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003631 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003632 spvType = builder.makeIntType(64);
3633 break;
3634 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003635 spvType = builder.makeUintType(64);
3636 break;
John Kessenich426394d2015-07-23 10:22:48 -06003637 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003638 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003639 spvType = builder.makeUintType(32);
3640 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04003641 case glslang::EbtAccStruct:
3642 spvType = builder.makeAccelerationStructureType();
Chao Chenb50c02e2018-09-19 11:42:24 -07003643 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04003644 case glslang::EbtRayQuery:
3645 spvType = builder.makeRayQueryType();
3646 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003647 case glslang::EbtReference:
3648 {
3649 // Make the forward pointer, then recurse to convert the structure type, then
3650 // patch up the forward pointer with a real pointer type.
3651 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3652 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3653 forwardPointers[type.getReferentType()] = forwardId;
3654 }
3655 spvType = forwardPointers[type.getReferentType()];
3656 if (!forwardReferenceOnly) {
3657 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3658 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3659 forwardPointers[type.getReferentType()],
3660 referentType);
3661 }
3662 }
3663 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003664#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003665 case glslang::EbtSampler:
3666 {
3667 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003668 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003669 spvType = builder.makeSamplerType();
3670 } else {
3671 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003672 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3673 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3674 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3675 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003676 // already has both image and sampler, make the combined type
3677 spvType = builder.makeSampledImageType(spvType);
3678 }
John Kessenich55e7d112015-11-15 21:33:39 -07003679 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003680 }
John Kessenich140f3df2015-06-26 16:58:36 -06003681 break;
3682 case glslang::EbtStruct:
3683 case glslang::EbtBlock:
3684 {
3685 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003686 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003687
3688 // Try to share structs for different layouts, but not yet for other
3689 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003690 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003691 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003692 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003693 break;
3694
3695 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003696 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003697 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003698 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003699 }
3700 break;
Jeff Bolz04d73732019-05-31 13:06:01 -05003701 case glslang::EbtString:
3702 // no type used for OpString
3703 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003704 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003705 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003706 break;
3707 }
3708
3709 if (type.isMatrix())
3710 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3711 else {
3712 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3713 if (type.getVectorSize() > 1)
3714 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3715 }
3716
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003717 if (type.isCoopMat()) {
3718 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3719 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3720 if (type.getBasicType() == glslang::EbtFloat16)
3721 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003722 if (type.getBasicType() == glslang::EbtUint8 ||
3723 type.getBasicType() == glslang::EbtInt8) {
3724 builder.addCapability(spv::CapabilityInt8);
3725 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003726
3727 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3728 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3729 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3730
3731 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3732 }
3733
John Kessenich140f3df2015-06-26 16:58:36 -06003734 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003735 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3736
John Kessenichc9a80832015-09-12 12:17:44 -06003737 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003738 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003739 // We need to decorate array strides for types needing explicit layout, except blocks.
3740 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003741 // Use a dummy glslang type for querying internal strides of
3742 // arrays of arrays, but using just a one-dimensional array.
3743 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003744 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3745 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003746
3747 // Will compute the higher-order strides here, rather than making a whole
3748 // pile of types and doing repetitive recursion on their contents.
3749 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3750 }
John Kessenichf8842e52016-01-04 19:22:56 -07003751
3752 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003753 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003754 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003755 if (stride > 0)
3756 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003757 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003758 }
3759 } else {
3760 // single-dimensional array, and don't yet have stride
3761
John Kessenichf8842e52016-01-04 19:22:56 -07003762 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003763 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3764 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003765 }
John Kessenich31ed4832015-09-09 17:51:38 -06003766
John Kessenichead86222018-03-28 18:01:20 -06003767 // Do the outer dimension, which might not be known for a runtime-sized array.
3768 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3769 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003770 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003771 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003772#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003773 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003774 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003775 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3776 }
John Kessenichb9197c82019-08-11 07:41:45 -06003777#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003778 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003779 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003780 if (stride > 0)
3781 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003782 }
3783
3784 return spvType;
3785}
3786
John Kessenich0e737842017-03-24 18:38:16 -06003787// TODO: this functionality should exist at a higher level, in creating the AST
3788//
3789// Identify interface members that don't have their required extension turned on.
3790//
3791bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3792{
John Kessenicha28f7a72019-08-06 07:00:58 -06003793#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003794 auto& extensions = glslangIntermediate->getRequestedExtensions();
3795
Rex Xubcf291a2017-03-29 23:01:36 +08003796 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3797 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3798 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003799 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3800 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3801 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003802
3803 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3804 if (member.getFieldName() == "gl_ViewportMask" &&
3805 extensions.find("GL_NV_viewport_array2") == extensions.end())
3806 return true;
3807 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3808 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3809 return true;
3810 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3811 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3812 return true;
3813 }
3814#endif
John Kessenich0e737842017-03-24 18:38:16 -06003815
3816 return false;
3817};
3818
John Kessenich6090df02016-06-30 21:18:02 -06003819// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3820// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3821// Mutually recursive with convertGlslangToSpvType().
3822spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3823 const glslang::TTypeList* glslangMembers,
3824 glslang::TLayoutPacking explicitLayout,
3825 const glslang::TQualifier& qualifier)
3826{
3827 // Create a vector of struct types for SPIR-V to consume
3828 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07003829 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
3830 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003831 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003832 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3833 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3834 if (glslangMember.hiddenMember()) {
3835 ++memberDelta;
3836 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003837 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06003838 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003839 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003840 if (filterMember(glslangMember)) {
3841 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08003842 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003843 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003844 }
Roy05a5b532020-01-03 16:21:34 +08003845 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003846 }
John Kessenich6090df02016-06-30 21:18:02 -06003847 // modify just this child's view of the qualifier
3848 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3849 InheritQualifiers(memberQualifier, qualifier);
3850
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003851 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003852 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003853 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003854
3855 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003856 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3857 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003858
3859 // Make forward pointers for any pointer members, and create a list of members to
3860 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003861 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003862 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3863 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3864 }
3865 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003866 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3867 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003868 } else {
3869 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003870 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3871 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003872 }
John Kessenich6090df02016-06-30 21:18:02 -06003873 }
3874 }
3875
3876 // Make the SPIR-V type
3877 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003878 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003879 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3880
3881 // Decorate it
3882 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3883
John Kessenichd72f4882019-01-16 14:55:37 +07003884 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003885 auto it = deferredForwardPointers[i];
3886 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3887 }
3888
John Kessenich6090df02016-06-30 21:18:02 -06003889 return spvType;
3890}
3891
3892void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3893 const glslang::TTypeList* glslangMembers,
3894 glslang::TLayoutPacking explicitLayout,
3895 const glslang::TQualifier& qualifier,
3896 spv::Id spvType)
3897{
3898 // Name and decorate the non-hidden members
3899 int offset = -1;
3900 int locationOffset = 0; // for use within the members of this struct
3901 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3902 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3903 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003904 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08003905 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06003906 if (filterMember(glslangMember))
3907 continue;
3908 }
John Kessenich6090df02016-06-30 21:18:02 -06003909
3910 // modify just this child's view of the qualifier
3911 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3912 InheritQualifiers(memberQualifier, qualifier);
3913
3914 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003915 if (member < 0)
3916 continue;
3917
3918 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3919 builder.addMemberDecoration(spvType, member,
3920 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3921 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3922 // Add interpolation and auxiliary storage decorations only to
3923 // top-level members of Input and Output storage classes
3924 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3925 type.getQualifier().storage == glslang::EvqVaryingOut) {
3926 if (type.getBasicType() == glslang::EbtBlock ||
3927 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3928 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3929 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003930#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003931 addMeshNVDecoration(spvType, member, memberQualifier);
3932#endif
John Kessenich6090df02016-06-30 21:18:02 -06003933 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003934 }
3935 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003936
John Kessenichb9197c82019-08-11 07:41:45 -06003937#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003938 if (type.getBasicType() == glslang::EbtBlock &&
3939 qualifier.storage == glslang::EvqBuffer) {
3940 // Add memory decorations only to top-level members of shader storage block
3941 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003942 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003943 for (unsigned int i = 0; i < memory.size(); ++i)
3944 builder.addMemberDecoration(spvType, member, memory[i]);
3945 }
John Kessenichf8d1d742019-10-21 06:55:11 -06003946
John Kessenichb9197c82019-08-11 07:41:45 -06003947#endif
John Kessenich6090df02016-06-30 21:18:02 -06003948
John Kessenich5d610ee2018-03-07 18:05:55 -07003949 // Location assignment was already completed correctly by the front end,
3950 // just track whether a member needs to be decorated.
3951 // Ignore member locations if the container is an array, as that's
3952 // ill-specified and decisions have been made to not allow this.
3953 if (! type.isArray() && memberQualifier.hasLocation())
3954 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003955
John Kessenich5d610ee2018-03-07 18:05:55 -07003956 if (qualifier.hasLocation()) // track for upcoming inheritance
3957 locationOffset += glslangIntermediate->computeTypeLocationSize(
3958 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003959
John Kessenich5d610ee2018-03-07 18:05:55 -07003960 // component, XFB, others
3961 if (glslangMember.getQualifier().hasComponent())
3962 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3963 glslangMember.getQualifier().layoutComponent);
3964 if (glslangMember.getQualifier().hasXfbOffset())
3965 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3966 glslangMember.getQualifier().layoutXfbOffset);
3967 else if (explicitLayout != glslang::ElpNone) {
3968 // figure out what to do with offset, which is accumulating
3969 int nextOffset;
3970 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3971 if (offset >= 0)
3972 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3973 offset = nextOffset;
3974 }
John Kessenich6090df02016-06-30 21:18:02 -06003975
John Kessenich5d610ee2018-03-07 18:05:55 -07003976 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3977 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3978 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003979
John Kessenich5d610ee2018-03-07 18:05:55 -07003980 // built-in variable decorations
3981 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3982 if (builtIn != spv::BuiltInMax)
3983 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003984
John Kessenichb9197c82019-08-11 07:41:45 -06003985#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003986 // nonuniform
3987 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3988
John Kessenichead86222018-03-28 18:01:20 -06003989 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3990 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3991 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3992 memberQualifier.semanticName);
3993 }
3994
John Kessenich5d610ee2018-03-07 18:05:55 -07003995 if (builtIn == spv::BuiltInLayer) {
3996 // SPV_NV_viewport_array2 extension
3997 if (glslangMember.getQualifier().layoutViewportRelative){
3998 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3999 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4000 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08004001 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004002 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
4003 builder.addMemberDecoration(spvType, member,
4004 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
4005 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
4006 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4007 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08004008 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004009 }
4010 if (glslangMember.getQualifier().layoutPassthrough) {
4011 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
4012 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
4013 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4014 }
chaoc771d89f2017-01-13 01:10:53 -08004015#endif
John Kessenich6090df02016-06-30 21:18:02 -06004016 }
4017
4018 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07004019 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
4020 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06004021}
4022
John Kessenich6c292d32016-02-15 20:58:50 -07004023// Turn the expression forming the array size into an id.
4024// This is not quite trivial, because of specialization constants.
4025// Sometimes, a raw constant is turned into an Id, and sometimes
4026// a specialization constant expression is.
4027spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
4028{
4029 // First, see if this is sized with a node, meaning a specialization constant:
4030 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
4031 if (specNode != nullptr) {
4032 builder.clearAccessChain();
4033 specNode->traverse(this);
4034 return accessChainLoad(specNode->getAsTyped()->getType());
4035 }
qining25262b32016-05-06 17:25:16 -04004036
John Kessenich6c292d32016-02-15 20:58:50 -07004037 // Otherwise, need a compile-time (front end) size, get it:
4038 int size = arraySizes.getDimSize(dim);
4039 assert(size > 0);
4040 return builder.makeUintConstant(size);
4041}
4042
John Kessenich103bef92016-02-08 21:38:15 -07004043// Wrap the builder's accessChainLoad to:
4044// - localize handling of RelaxedPrecision
4045// - use the SPIR-V inferred type instead of another conversion of the glslang type
4046// (avoids unnecessary work and possible type punning for structures)
4047// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07004048spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
4049{
John Kessenich103bef92016-02-08 21:38:15 -07004050 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004051
4052 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4053 coherentFlags |= TranslateCoherent(type);
4054
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004055 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004056 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004057
John Kessenich5611c6d2018-04-05 11:25:02 -06004058 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
John Kessenich8985fc92020-03-03 10:25:07 -07004059 TranslateNonUniformDecoration(type.getQualifier()),
4060 nominalTypeId,
4061 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
4062 TranslateMemoryScope(coherentFlags),
4063 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07004064
4065 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08004066 if (type.getBasicType() == glslang::EbtBool) {
4067 if (builder.isScalarType(nominalTypeId)) {
4068 // Conversion for bool
4069 spv::Id boolType = builder.makeBoolType();
4070 if (nominalTypeId != boolType)
4071 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
4072 } else if (builder.isVectorType(nominalTypeId)) {
4073 // Conversion for bvec
4074 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4075 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
4076 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07004077 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
4078 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004079 }
4080 }
John Kessenich103bef92016-02-08 21:38:15 -07004081
4082 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07004083}
4084
Rex Xu27253232016-02-23 17:51:09 +08004085// Wrap the builder's accessChainStore to:
4086// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06004087//
4088// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08004089void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
4090{
4091 // Need to convert to abstract types when necessary
4092 if (type.getBasicType() == glslang::EbtBool) {
4093 spv::Id nominalTypeId = builder.accessChainGetInferredType();
4094
4095 if (builder.isScalarType(nominalTypeId)) {
4096 // Conversion for bool
4097 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06004098 if (nominalTypeId != boolType) {
4099 // keep these outside arguments, for determinant order-of-evaluation
4100 spv::Id one = builder.makeUintConstant(1);
4101 spv::Id zero = builder.makeUintConstant(0);
4102 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
4103 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06004104 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08004105 } else if (builder.isVectorType(nominalTypeId)) {
4106 // Conversion for bvec
4107 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4108 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06004109 if (nominalTypeId != bvecType) {
4110 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06004111 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
4112 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
4113 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06004114 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06004115 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
4116 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004117 }
4118 }
4119
Jeff Bolz36831c92018-09-05 10:11:41 -05004120 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4121 coherentFlags |= TranslateCoherent(type);
4122
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004123 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004124 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004125
Jeff Bolz36831c92018-09-05 10:11:41 -05004126 builder.accessChainStore(rvalue,
John Kessenich8985fc92020-03-03 10:25:07 -07004127 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
4128 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004129 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08004130}
4131
John Kessenich4bf71552016-09-02 11:20:21 -06004132// For storing when types match at the glslang level, but not might match at the
4133// SPIR-V level.
4134//
4135// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004136// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004137// as in a member-decorated way.
4138//
4139// NOTE: This function can handle any store request; if it's not special it
4140// simplifies to a simple OpStore.
4141//
4142// Implicitly uses the existing builder.accessChain as the storage target.
4143void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4144{
John Kessenichb3e24e42016-09-11 12:33:43 -06004145 // we only do the complex path here if it's an aggregate
4146 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004147 accessChainStore(type, rValue);
4148 return;
4149 }
4150
John Kessenichb3e24e42016-09-11 12:33:43 -06004151 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004152 spv::Id rType = builder.getTypeId(rValue);
4153 spv::Id lValue = builder.accessChainGetLValue();
4154 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4155 if (lType == rType) {
4156 accessChainStore(type, rValue);
4157 return;
4158 }
4159
John Kessenichb3e24e42016-09-11 12:33:43 -06004160 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004161 // where the two types were the same type in GLSL. This requires member
4162 // by member copy, recursively.
4163
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004164 // SPIR-V 1.4 added an instruction to do help do this.
4165 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4166 // However, bool in uniform space is changed to int, so
4167 // OpCopyLogical does not work for that.
4168 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4169 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4170 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4171 if (lBool == rBool) {
4172 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4173 accessChainStore(type, logicalCopy);
4174 return;
4175 }
4176 }
4177
John Kessenichb3e24e42016-09-11 12:33:43 -06004178 // If an array, copy element by element.
4179 if (type.isArray()) {
4180 glslang::TType glslangElementType(type, 0);
4181 spv::Id elementRType = builder.getContainedTypeId(rType);
4182 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4183 // get the source member
4184 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004185
John Kessenichb3e24e42016-09-11 12:33:43 -06004186 // set up the target storage
4187 builder.clearAccessChain();
4188 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004189 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4190 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004191
John Kessenichb3e24e42016-09-11 12:33:43 -06004192 // store the member
4193 multiTypeStore(glslangElementType, elementRValue);
4194 }
4195 } else {
4196 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004197
John Kessenichb3e24e42016-09-11 12:33:43 -06004198 // loop over structure members
4199 const glslang::TTypeList& members = *type.getStruct();
4200 for (int m = 0; m < (int)members.size(); ++m) {
4201 const glslang::TType& glslangMemberType = *members[m].type;
4202
4203 // get the source member
4204 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4205 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4206
4207 // set up the target storage
4208 builder.clearAccessChain();
4209 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004210 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4211 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004212
4213 // store the member
4214 multiTypeStore(glslangMemberType, memberRValue);
4215 }
John Kessenich4bf71552016-09-02 11:20:21 -06004216 }
4217}
4218
John Kessenichf85e8062015-12-19 13:57:10 -07004219// Decide whether or not this type should be
4220// decorated with offsets and strides, and if so
4221// whether std140 or std430 rules should be applied.
4222glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004223{
John Kessenichf85e8062015-12-19 13:57:10 -07004224 // has to be a block
4225 if (type.getBasicType() != glslang::EbtBlock)
4226 return glslang::ElpNone;
4227
Chao Chen3c366992018-09-19 11:41:59 -07004228 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004229 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004230 type.getQualifier().storage != glslang::EvqBuffer &&
4231 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004232 return glslang::ElpNone;
4233
4234 // return the layout to use
4235 switch (type.getQualifier().layoutPacking) {
4236 case glslang::ElpStd140:
4237 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004238 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004239 return type.getQualifier().layoutPacking;
4240 default:
4241 return glslang::ElpNone;
4242 }
John Kessenich31ed4832015-09-09 17:51:38 -06004243}
4244
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004245// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004246int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4247 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004248{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004249 int size;
John Kessenich49987892015-12-29 17:11:44 -07004250 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004251 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4252 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004253
4254 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004255}
4256
John Kessenich49987892015-12-29 17:11:44 -07004257// 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 -07004258// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004259int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4260 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004261{
John Kessenich49987892015-12-29 17:11:44 -07004262 glslang::TType elementType;
4263 elementType.shallowCopy(matrixType);
4264 elementType.clearArraySizes();
4265
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004266 int size;
John Kessenich49987892015-12-29 17:11:44 -07004267 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004268 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4269 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004270
4271 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004272}
4273
John Kessenich5e4b1242015-08-06 22:53:06 -06004274// Given a member type of a struct, realign the current offset for it, and compute
4275// the next (not yet aligned) offset for the next member, which will get aligned
4276// on the next call.
4277// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4278// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4279// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004280void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4281 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004282{
4283 // this will get a positive value when deemed necessary
4284 nextOffset = -1;
4285
John Kessenich5e4b1242015-08-06 22:53:06 -06004286 // override anything in currentOffset with user-set offset
4287 if (memberType.getQualifier().hasOffset())
4288 currentOffset = memberType.getQualifier().layoutOffset;
4289
4290 // It could be that current linker usage in glslang updated all the layoutOffset,
4291 // in which case the following code does not matter. But, that's not quite right
4292 // once cross-compilation unit GLSL validation is done, as the original user
4293 // settings are needed in layoutOffset, and then the following will come into play.
4294
John Kessenichf85e8062015-12-19 13:57:10 -07004295 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004296 if (! memberType.getQualifier().hasOffset())
4297 currentOffset = -1;
4298
4299 return;
4300 }
4301
John Kessenichf85e8062015-12-19 13:57:10 -07004302 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004303 if (currentOffset < 0)
4304 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004305
John Kessenich5e4b1242015-08-06 22:53:06 -06004306 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4307 // but possibly not yet correctly aligned.
4308
4309 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004310 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004311 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4312 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004313
4314 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004315 // TODO: make this consistent in early phases of code:
4316 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4317 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4318 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004319 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004320 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004321 int dummySize;
4322 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4323 if (componentAlignment <= 4)
4324 memberAlignment = componentAlignment;
4325 }
4326
4327 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004328 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004329
4330 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004331 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4332 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004333 glslang::RoundToPow2(currentOffset, 16);
4334
John Kessenich5e4b1242015-08-06 22:53:06 -06004335 nextOffset = currentOffset + memberSize;
4336}
4337
David Netoa901ffe2016-06-08 14:11:40 +01004338void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004339{
David Netoa901ffe2016-06-08 14:11:40 +01004340 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4341 switch (glslangBuiltIn)
4342 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004343 case glslang::EbvPointSize:
4344#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004345 case glslang::EbvClipDistance:
4346 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004347 case glslang::EbvViewportMaskNV:
4348 case glslang::EbvSecondaryPositionNV:
4349 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004350 case glslang::EbvPositionPerViewNV:
4351 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004352 case glslang::EbvTaskCountNV:
4353 case glslang::EbvPrimitiveCountNV:
4354 case glslang::EbvPrimitiveIndicesNV:
4355 case glslang::EbvClipDistancePerViewNV:
4356 case glslang::EbvCullDistancePerViewNV:
4357 case glslang::EbvLayerPerViewNV:
4358 case glslang::EbvMeshViewCountNV:
4359 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004360#endif
David Netoa901ffe2016-06-08 14:11:40 +01004361 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4362 // Alternately, we could just call this for any glslang built-in, since the
4363 // capability already guards against duplicates.
4364 TranslateBuiltInDecoration(glslangBuiltIn, false);
4365 break;
4366 default:
4367 // Capabilities were already generated when the struct was declared.
4368 break;
4369 }
John Kessenichebb50532016-05-16 19:22:05 -06004370}
4371
John Kessenich6fccb3c2016-09-19 16:01:41 -06004372bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004373{
John Kessenicheee9d532016-09-19 18:09:30 -06004374 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004375}
4376
John Kessenichd41993d2017-09-10 15:21:05 -06004377// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004378// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4379// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004380bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004381{
John Kessenich6a14f782017-12-04 02:48:10 -07004382 assert(qualifier == glslang::EvqIn ||
4383 qualifier == glslang::EvqOut ||
4384 qualifier == glslang::EvqInOut ||
4385 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004386 return qualifier != glslang::EvqConstReadOnly;
4387}
4388
4389// Is parameter pass-by-original?
4390bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4391 bool implicitThisParam)
4392{
4393 if (implicitThisParam) // implicit this
4394 return true;
4395 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004396 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004397 return paramType.containsOpaque() || // sampler, etc.
4398 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4399}
4400
John Kessenich140f3df2015-06-26 16:58:36 -06004401// Make all the functions, skeletally, without actually visiting their bodies.
4402void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4403{
John Kessenich8985fc92020-03-03 10:25:07 -07004404 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4405 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004406 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4407 if (paramPrecision != spv::NoPrecision)
4408 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004409 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004410 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004411 // Original and non-writable params pass the pointer directly and
4412 // use restrict/aliased, others are stored to a pointer in Function
4413 // memory and use RestrictPointer/AliasedPointer.
4414 if (originalParam(type.getQualifier().storage, type, false) ||
4415 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004416 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4417 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004418 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004419 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4420 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004421 }
4422 }
John Kessenichfad62972017-07-18 02:35:46 -06004423 };
4424
John Kessenich140f3df2015-06-26 16:58:36 -06004425 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4426 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004427 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004428 continue;
4429
4430 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004431 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004432 //
qining25262b32016-05-06 17:25:16 -04004433 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004434 // function. What it is an address of varies:
4435 //
John Kessenich4bf71552016-09-02 11:20:21 -06004436 // - "in" parameters not marked as "const" can be written to without modifying the calling
4437 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004438 //
4439 // - "const in" parameters can just be the r-value, as no writes need occur.
4440 //
John Kessenich4bf71552016-09-02 11:20:21 -06004441 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4442 // 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 -06004443
4444 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004445 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004446 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4447
John Kessenich155d3512019-08-08 23:29:20 -06004448#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004449 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4450 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004451#else
4452 bool implicitThis = false;
4453#endif
John Kessenich37789792017-03-21 23:56:40 -06004454
John Kessenichfad62972017-07-18 02:35:46 -06004455 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004456 for (int p = 0; p < (int)parameters.size(); ++p) {
4457 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4458 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004459 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004460 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004461 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004462 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4463 else
John Kessenich4bf71552016-09-02 11:20:21 -06004464 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004465 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004466 paramTypes.push_back(typeId);
4467 }
4468
4469 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004470 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4471 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004472 glslFunction->getName().c_str(), paramTypes,
4473 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004474 if (implicitThis)
4475 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004476
4477 // Track function to emit/call later
4478 functionMap[glslFunction->getName().c_str()] = function;
4479
4480 // Set the parameter id's
4481 for (int p = 0; p < (int)parameters.size(); ++p) {
4482 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4483 // give a name too
4484 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004485
4486 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004487 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004488 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004489 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004490 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004491 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004492 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004493 }
4494 }
4495}
4496
4497// Process all the initializers, while skipping the functions and link objects
4498void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4499{
4500 builder.setBuildPoint(shaderEntry->getLastBlock());
4501 for (int i = 0; i < (int)initializers.size(); ++i) {
4502 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004503 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4504 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004505
4506 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004507 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004508 initializer->traverse(this);
4509 }
4510 }
4511}
4512
4513// Process all the functions, while skipping initializers.
4514void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4515{
4516 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4517 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004518 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004519 node->traverse(this);
4520 }
4521}
4522
4523void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4524{
qining25262b32016-05-06 17:25:16 -04004525 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004526 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004527 currentFunction = functionMap[node->getName().c_str()];
4528 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004529 builder.setBuildPoint(functionBlock);
4530}
4531
John Kessenich8985fc92020-03-03 10:25:07 -07004532void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4533 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004534{
Rex Xufc618912015-09-09 16:42:49 +08004535 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004536
4537 glslang::TSampler sampler = {};
4538 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004539#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004540 bool f16ShadowCompare = false;
4541#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004542 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004543 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4544 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004545#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004546 f16ShadowCompare = sampler.shadow &&
4547 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004548#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004549 }
4550
John Kessenich140f3df2015-06-26 16:58:36 -06004551 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4552 builder.clearAccessChain();
4553 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004554
John Kessenicha28f7a72019-08-06 07:00:58 -06004555#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004556 // Special case l-value operands
4557 bool lvalue = false;
4558 switch (node.getOp()) {
4559 case glslang::EOpImageAtomicAdd:
4560 case glslang::EOpImageAtomicMin:
4561 case glslang::EOpImageAtomicMax:
4562 case glslang::EOpImageAtomicAnd:
4563 case glslang::EOpImageAtomicOr:
4564 case glslang::EOpImageAtomicXor:
4565 case glslang::EOpImageAtomicExchange:
4566 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004567 case glslang::EOpImageAtomicLoad:
4568 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004569 if (i == 0)
4570 lvalue = true;
4571 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004572 case glslang::EOpSparseImageLoad:
4573 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4574 lvalue = true;
4575 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004576 case glslang::EOpSparseTexture:
4577 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4578 lvalue = true;
4579 break;
4580 case glslang::EOpSparseTextureClamp:
4581 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4582 lvalue = true;
4583 break;
4584 case glslang::EOpSparseTextureLod:
4585 case glslang::EOpSparseTextureOffset:
4586 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4587 lvalue = true;
4588 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004589 case glslang::EOpSparseTextureFetch:
4590 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4591 lvalue = true;
4592 break;
4593 case glslang::EOpSparseTextureFetchOffset:
4594 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4595 lvalue = true;
4596 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004597 case glslang::EOpSparseTextureLodOffset:
4598 case glslang::EOpSparseTextureGrad:
4599 case glslang::EOpSparseTextureOffsetClamp:
4600 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4601 lvalue = true;
4602 break;
4603 case glslang::EOpSparseTextureGradOffset:
4604 case glslang::EOpSparseTextureGradClamp:
4605 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4606 lvalue = true;
4607 break;
4608 case glslang::EOpSparseTextureGradOffsetClamp:
4609 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4610 lvalue = true;
4611 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004612 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004613 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4614 lvalue = true;
4615 break;
4616 case glslang::EOpSparseTextureGatherOffset:
4617 case glslang::EOpSparseTextureGatherOffsets:
4618 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4619 lvalue = true;
4620 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004621 case glslang::EOpSparseTextureGatherLod:
4622 if (i == 3)
4623 lvalue = true;
4624 break;
4625 case glslang::EOpSparseTextureGatherLodOffset:
4626 case glslang::EOpSparseTextureGatherLodOffsets:
4627 if (i == 4)
4628 lvalue = true;
4629 break;
Rex Xu129799a2017-07-05 17:23:28 +08004630 case glslang::EOpSparseImageLoadLod:
4631 if (i == 3)
4632 lvalue = true;
4633 break;
Chao Chen3a137962018-09-19 11:41:27 -07004634 case glslang::EOpImageSampleFootprintNV:
4635 if (i == 4)
4636 lvalue = true;
4637 break;
4638 case glslang::EOpImageSampleFootprintClampNV:
4639 case glslang::EOpImageSampleFootprintLodNV:
4640 if (i == 5)
4641 lvalue = true;
4642 break;
4643 case glslang::EOpImageSampleFootprintGradNV:
4644 if (i == 6)
4645 lvalue = true;
4646 break;
4647 case glslang::EOpImageSampleFootprintGradClampNV:
4648 if (i == 7)
4649 lvalue = true;
4650 break;
Rex Xufc618912015-09-09 16:42:49 +08004651 default:
4652 break;
4653 }
4654
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004655 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004656 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004657 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4658 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4659 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004660#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004661 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004662 }
4663}
4664
John Kessenichfc51d282015-08-19 13:34:18 -06004665void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004666{
John Kessenichfc51d282015-08-19 13:34:18 -06004667 builder.clearAccessChain();
4668 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004669 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004670}
John Kessenich140f3df2015-06-26 16:58:36 -06004671
John Kessenichfc51d282015-08-19 13:34:18 -06004672spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4673{
John Kesseniche485c7a2017-05-31 18:50:53 -06004674 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004675 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004676
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004677 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004678
John Kessenichfc51d282015-08-19 13:34:18 -06004679 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004680
John Kessenichf43c7392019-03-31 10:51:57 -06004681 const glslang::TType &imageType = node->getAsAggregate()
4682 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4683 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004684 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004685#ifdef GLSLANG_WEB
4686 const bool f16ShadowCompare = false;
4687#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004688 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004689 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4690 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004691#endif
4692
John Kessenichf43c7392019-03-31 10:51:57 -06004693 const auto signExtensionMask = [&]() {
4694 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4695 if (sampler.type == glslang::EbtUint)
4696 return spv::ImageOperandsZeroExtendMask;
4697 else if (sampler.type == glslang::EbtInt)
4698 return spv::ImageOperandsSignExtendMask;
4699 }
4700 return spv::ImageOperandsMaskNone;
4701 };
4702
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004703 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4704
John Kessenichfc51d282015-08-19 13:34:18 -06004705 std::vector<spv::Id> arguments;
4706 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004707 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004708 else
4709 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004710 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004711
4712 spv::Builder::TextureParameters params = { };
4713 params.sampler = arguments[0];
4714
Rex Xu04db3f52015-09-16 11:44:02 +08004715 glslang::TCrackedTextureOp cracked;
4716 node->crackTexture(sampler, cracked);
4717
amhagan05506bb2017-06-13 16:53:02 -04004718 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004719
John Kessenichfc51d282015-08-19 13:34:18 -06004720 // Check for queries
4721 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004722 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4723 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004724 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004725
John Kessenichfc51d282015-08-19 13:34:18 -06004726 switch (node->getOp()) {
4727 case glslang::EOpImageQuerySize:
4728 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004729 if (arguments.size() > 1) {
4730 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004731 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004732 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004733 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004734#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004735 case glslang::EOpImageQuerySamples:
4736 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004737 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004738 case glslang::EOpTextureQueryLod:
4739 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004740 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004741 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004742 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004743 case glslang::EOpSparseTexelsResident:
4744 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004745#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004746 default:
4747 assert(0);
4748 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004749 }
John Kessenich140f3df2015-06-26 16:58:36 -06004750 }
4751
LoopDawg4425f242018-02-18 11:40:01 -07004752 int components = node->getType().getVectorSize();
4753
4754 if (node->getOp() == glslang::EOpTextureFetch) {
4755 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4756 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4757 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4758 // here around e.g. which ones return scalars or other types.
4759 components = 4;
4760 }
4761
4762 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4763
4764 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4765
Rex Xufc618912015-09-09 16:42:49 +08004766 // Check for image functions other than queries
4767 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004768 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004769 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004770 spv::IdImmediate image = { true, *(opIt++) };
4771 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004772
4773 // Handle subpass operations
4774 // TODO: GLSL should change to have the "MS" only on the type rather than the
4775 // built-in function.
4776 if (cracked.subpass) {
4777 // add on the (0,0) coordinate
4778 spv::Id zero = builder.makeIntConstant(0);
4779 std::vector<spv::Id> comps;
4780 comps.push_back(zero);
4781 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004782 spv::IdImmediate coord = { true,
4783 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4784 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004785 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4786 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004787 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004788 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4789 }
4790 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004791 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004792 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004793 spv::IdImmediate imageOperand = { true, *(opIt++) };
4794 operands.push_back(imageOperand);
4795 }
John Kessenich6c292d32016-02-15 20:58:50 -07004796 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004797 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4798 builder.setPrecision(result, precision);
4799 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004800 }
4801
John Kessenich149afc32018-08-14 13:31:43 -06004802 spv::IdImmediate coord = { true, *(opIt++) };
4803 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004804 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004805 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004806 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004807 mask = mask | spv::ImageOperandsSampleMask;
4808 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004809 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004810 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4811 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004812 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004813 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004814 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4815 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004816 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004817 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004818 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4819 operands.push_back(imageOperands);
4820 }
4821 if (mask & spv::ImageOperandsSampleMask) {
4822 spv::IdImmediate imageOperand = { true, *opIt++ };
4823 operands.push_back(imageOperand);
4824 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004825 if (mask & spv::ImageOperandsLodMask) {
4826 spv::IdImmediate imageOperand = { true, *opIt++ };
4827 operands.push_back(imageOperand);
4828 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004829 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004830 spv::IdImmediate imageOperand = { true,
4831 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004832 operands.push_back(imageOperand);
4833 }
4834
John Kessenich149afc32018-08-14 13:31:43 -06004835 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004836 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004837
John Kessenich149afc32018-08-14 13:31:43 -06004838 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004839 builder.setPrecision(result[0], precision);
4840
4841 // If needed, add a conversion constructor to the proper size.
4842 if (components != node->getType().getVectorSize())
4843 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4844
4845 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004846 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004847
Jeff Bolz36831c92018-09-05 10:11:41 -05004848 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004849 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004850 spv::IdImmediate texel = { true, *(opIt + 1) };
4851 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004852 } else {
4853 spv::IdImmediate texel = { true, *opIt };
4854 operands.push_back(texel);
4855 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004856
4857 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004858 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004859 mask = mask | spv::ImageOperandsSampleMask;
4860 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004861 if (cracked.lod) {
4862 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4863 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4864 mask = mask | spv::ImageOperandsLodMask;
4865 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004866 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4867 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004868 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004869 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004870 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4871 operands.push_back(imageOperands);
4872 }
4873 if (mask & spv::ImageOperandsSampleMask) {
4874 spv::IdImmediate imageOperand = { true, *opIt++ };
4875 operands.push_back(imageOperand);
4876 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004877 if (mask & spv::ImageOperandsLodMask) {
4878 spv::IdImmediate imageOperand = { true, *opIt++ };
4879 operands.push_back(imageOperand);
4880 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004881 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004882 spv::IdImmediate imageOperand = { true,
4883 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004884 operands.push_back(imageOperand);
4885 }
4886
John Kessenich56bab042015-09-16 10:54:31 -06004887 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004888 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004889 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004890 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004891 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4892 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004893 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004894 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004895 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4896
Jeff Bolz36831c92018-09-05 10:11:41 -05004897 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004898 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004899 mask = mask | spv::ImageOperandsSampleMask;
4900 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004901 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004902 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4903 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4904
Jeff Bolz36831c92018-09-05 10:11:41 -05004905 mask = mask | spv::ImageOperandsLodMask;
4906 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004907 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4908 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004909 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004910 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004911 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004912 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004913 }
4914 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004915 spv::IdImmediate imageOperand = { true, *opIt++ };
4916 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004917 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004918 if (mask & spv::ImageOperandsLodMask) {
4919 spv::IdImmediate imageOperand = { true, *opIt++ };
4920 operands.push_back(imageOperand);
4921 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004922 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07004923 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
4924 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004925 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004926 }
4927
4928 // Create the return type that was a special structure
4929 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004930 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004931 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4932 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4933
4934 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4935
4936 // Decode the return type
4937 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4938 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004939 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004940 // Process image atomic operations
4941
4942 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4943 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004944 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004945 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004946 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004947
Jeff Bolz36831c92018-09-05 10:11:41 -05004948 spv::Id resultTypeId;
4949 // imageAtomicStore has a void return type so base the pointer type on
4950 // the type of the value operand.
4951 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08004952 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05004953 } else {
4954 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4955 }
John Kessenich56bab042015-09-16 10:54:31 -06004956 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Jeff Bolz39ffdaf2020-03-09 10:48:12 -05004957 if (imageType.getQualifier().nonUniform) {
4958 builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
4959 }
Rex Xufc618912015-09-09 16:42:49 +08004960
4961 std::vector<spv::Id> operands;
4962 operands.push_back(pointer);
4963 for (; opIt != arguments.end(); ++opIt)
4964 operands.push_back(*opIt);
4965
John Kessenich8985fc92020-03-03 10:25:07 -07004966 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
4967 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004968 }
4969 }
4970
John Kessenicha28f7a72019-08-06 07:00:58 -06004971#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004972 // Check for fragment mask functions other than queries
4973 if (cracked.fragMask) {
4974 assert(sampler.ms);
4975
4976 auto opIt = arguments.begin();
4977 std::vector<spv::Id> operands;
4978
4979 // Extract the image if necessary
4980 if (builder.isSampledImage(params.sampler))
4981 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4982
4983 operands.push_back(params.sampler);
4984 ++opIt;
4985
4986 if (sampler.isSubpass()) {
4987 // add on the (0,0) coordinate
4988 spv::Id zero = builder.makeIntConstant(0);
4989 std::vector<spv::Id> comps;
4990 comps.push_back(zero);
4991 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07004992 operands.push_back(builder.makeCompositeConstant(
4993 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04004994 }
4995
4996 for (; opIt != arguments.end(); ++opIt)
4997 operands.push_back(*opIt);
4998
4999 spv::Op fragMaskOp = spv::OpNop;
5000 if (node->getOp() == glslang::EOpFragmentMaskFetch)
5001 fragMaskOp = spv::OpFragmentMaskFetchAMD;
5002 else if (node->getOp() == glslang::EOpFragmentFetch)
5003 fragMaskOp = spv::OpFragmentFetchAMD;
5004
5005 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
5006 builder.addCapability(spv::CapabilityFragmentMaskAMD);
5007 return builder.createOp(fragMaskOp, resultType(), operands);
5008 }
5009#endif
5010
Rex Xufc618912015-09-09 16:42:49 +08005011 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08005012 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07005013 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005014 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08005015
John Kessenichfc51d282015-08-19 13:34:18 -06005016 // check for bias argument
5017 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08005018 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005019 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08005020 if (cracked.gather)
5021 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08005022
5023 if (f16ShadowCompare)
5024 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005025 if (cracked.offset)
5026 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08005027 else if (cracked.offsets)
5028 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005029 if (cracked.grad)
5030 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08005031 if (cracked.lodClamp)
5032 ++nonBiasArgCount;
5033 if (sparse)
5034 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07005035 if (imageFootprint)
5036 //Following three extra arguments
5037 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5038 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06005039 if ((int)arguments.size() > nonBiasArgCount)
5040 bias = true;
5041 }
5042
John Kessenicha5c33d62016-06-02 23:45:21 -06005043 // See if the sampler param should really be just the SPV image part
5044 if (cracked.fetch) {
5045 // a fetch needs to have the image extracted first
5046 if (builder.isSampledImage(params.sampler))
5047 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
5048 }
5049
John Kessenicha28f7a72019-08-06 07:00:58 -06005050#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08005051 if (cracked.gather) {
5052 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
5053 if (bias || cracked.lod ||
5054 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
5055 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08005056 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08005057 }
5058 }
5059#endif
5060
John Kessenichfc51d282015-08-19 13:34:18 -06005061 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07005062
John Kessenichfc51d282015-08-19 13:34:18 -06005063 params.coords = arguments[1];
5064 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07005065 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07005066
5067 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08005068 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005069 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08005070 ++extraArgs;
5071 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07005072 params.Dref = arguments[2];
5073 ++extraArgs;
5074 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06005075 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06005076 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06005077 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06005078 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06005079 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005080 dRefComp = builder.getNumComponents(params.coords) - 1;
5081 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07005082 params.Dref = builder.createCompositeExtract(params.coords,
5083 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06005084 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005085
5086 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06005087 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005088 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06005089 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06005090 } else if (glslangIntermediate->getStage() != EShLangFragment &&
5091 !(glslangIntermediate->getStage() == EShLangCompute &&
5092 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07005093 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
5094 noImplicitLod = true;
5095 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005096
5097 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005098 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005099 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08005100 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005101 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005102
5103 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06005104 if (cracked.grad) {
5105 params.gradX = arguments[2 + extraArgs];
5106 params.gradY = arguments[3 + extraArgs];
5107 extraArgs += 2;
5108 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005109
5110 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07005111 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06005112 params.offset = arguments[2 + extraArgs];
5113 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005114 } else if (cracked.offsets) {
5115 params.offsets = arguments[2 + extraArgs];
5116 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005117 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005118
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005119#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005120 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005121 if (cracked.lodClamp) {
5122 params.lodClamp = arguments[2 + extraArgs];
5123 ++extraArgs;
5124 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005125 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005126 if (sparse) {
5127 params.texelOut = arguments[2 + extraArgs];
5128 ++extraArgs;
5129 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005130 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005131 if (cracked.gather && ! sampler.shadow) {
5132 // default component is 0, if missing, otherwise an argument
5133 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005134 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005135 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005136 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005137 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005138 }
Chao Chen3a137962018-09-19 11:41:27 -07005139 spv::Id resultStruct = spv::NoResult;
5140 if (imageFootprint) {
5141 //Following three extra arguments
5142 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5143 params.granularity = arguments[2 + extraArgs];
5144 params.coarse = arguments[3 + extraArgs];
5145 resultStruct = arguments[4 + extraArgs];
5146 extraArgs += 3;
5147 }
5148#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005149 // bias
5150 if (bias) {
5151 params.bias = arguments[2 + extraArgs];
5152 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005153 }
John Kessenichfc51d282015-08-19 13:34:18 -06005154
John Kessenicha28f7a72019-08-06 07:00:58 -06005155#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005156 if (imageFootprint) {
5157 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5158 builder.addCapability(spv::CapabilityImageFootprintNV);
5159
5160
5161 //resultStructType(OpenGL type) contains 5 elements:
5162 //struct gl_TextureFootprint2DNV {
5163 // uvec2 anchor;
5164 // uvec2 offset;
5165 // uvec2 mask;
5166 // uint lod;
5167 // uint granularity;
5168 //};
5169 //or
5170 //struct gl_TextureFootprint3DNV {
5171 // uvec3 anchor;
5172 // uvec3 offset;
5173 // uvec2 mask;
5174 // uint lod;
5175 // uint granularity;
5176 //};
5177 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5178 assert(builder.isStructType(resultStructType));
5179
5180 //resType (SPIR-V type) contains 6 elements:
5181 //Member 0 must be a Boolean type scalar(LOD),
5182 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5183 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5184 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5185 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5186 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5187 std::vector<spv::Id> members;
5188 members.push_back(resultType());
5189 for (int i = 0; i < 5; i++) {
5190 members.push_back(builder.getContainedTypeId(resultStructType, i));
5191 }
5192 spv::Id resType = builder.makeStructType(members, "ResType");
5193
5194 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005195 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5196 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005197
5198 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5199 for (int i = 0; i < 5; i++) {
5200 builder.clearAccessChain();
5201 builder.setAccessChainLValue(resultStruct);
5202
5203 //Accessing to a struct we created, no coherent flag is set
5204 spv::Builder::AccessChain::CoherentFlags flags;
5205 flags.clear();
5206
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005207 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005208 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
5209 i+1));
Chao Chen3a137962018-09-19 11:41:27 -07005210 }
5211 return builder.createCompositeExtract(res, resultType(), 0);
5212 }
5213#endif
5214
John Kessenich65336482016-06-16 14:06:26 -06005215 // projective component (might not to move)
5216 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5217 // are divided by the last component of P."
5218 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5219 // unused components will appear after all used components."
5220 if (cracked.proj) {
5221 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5222 int projTargetComp;
5223 switch (sampler.dim) {
5224 case glslang::Esd1D: projTargetComp = 1; break;
5225 case glslang::Esd2D: projTargetComp = 2; break;
5226 case glslang::EsdRect: projTargetComp = 2; break;
5227 default: projTargetComp = projSourceComp; break;
5228 }
5229 // copy the projective coordinate if we have to
5230 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005231 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005232 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005233 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005234 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005235 }
5236 }
5237
John Kessenichf8d1d742019-10-21 06:55:11 -06005238#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005239 // nonprivate
5240 if (imageType.getQualifier().nonprivate) {
5241 params.nonprivate = true;
5242 }
5243
5244 // volatile
5245 if (imageType.getQualifier().volatil) {
5246 params.volatil = true;
5247 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005248#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005249
St0fFa1184dd2018-04-09 21:08:14 +02005250 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005251 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5252 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005253 );
LoopDawg4425f242018-02-18 11:40:01 -07005254
5255 if (components != node->getType().getVectorSize())
5256 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5257
5258 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005259}
5260
5261spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5262{
5263 // Grab the function's pointer from the previously created function
5264 spv::Function* function = functionMap[node->getName().c_str()];
5265 if (! function)
5266 return 0;
5267
5268 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5269 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5270
5271 // See comments in makeFunctions() for details about the semantics for parameter passing.
5272 //
5273 // These imply we need a four step process:
5274 // 1. Evaluate the arguments
5275 // 2. Allocate and make copies of in, out, and inout arguments
5276 // 3. Make the call
5277 // 4. Copy back the results
5278
John Kessenichd3ed90b2018-05-04 11:43:03 -06005279 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005280 std::vector<spv::Builder::AccessChain> lValues;
5281 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005282 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005283 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005284 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005285 // build l-value
5286 builder.clearAccessChain();
5287 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005288 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005289 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005290 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005291 // save l-value
5292 lValues.push_back(builder.getAccessChain());
5293 } else {
5294 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005295 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005296 }
5297 }
5298
5299 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5300 // copy the original into that space.
5301 //
5302 // Also, build up the list of actual arguments to pass in for the call
5303 int lValueCount = 0;
5304 int rValueCount = 0;
5305 std::vector<spv::Id> spvArgs;
5306 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5307 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005308 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005309 builder.setAccessChain(lValues[lValueCount]);
5310 arg = builder.accessChainGetLValue();
5311 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005312 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005313 // need space to hold the copy
John Kessenich8985fc92020-03-03 10:25:07 -07005314 arg = builder.createVariable(spv::StorageClassFunction,
5315 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005316 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5317 // need to copy the input into output space
5318 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005319 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005320 builder.clearAccessChain();
5321 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005322 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005323 }
5324 ++lValueCount;
5325 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005326 // process r-value, which involves a copy for a type mismatch
5327 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5328 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5329 builder.clearAccessChain();
5330 builder.setAccessChainLValue(argCopy);
5331 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5332 arg = builder.createLoad(argCopy);
5333 } else
5334 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005335 ++rValueCount;
5336 }
5337 spvArgs.push_back(arg);
5338 }
5339
5340 // 3. Make the call.
5341 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005342 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005343
5344 // 4. Copy back out an "out" arguments.
5345 lValueCount = 0;
5346 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005347 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005348 ++lValueCount;
5349 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005350 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5351 spv::Id copy = builder.createLoad(spvArgs[a]);
5352 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005353 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005354 }
5355 ++lValueCount;
5356 }
5357 }
5358
5359 return result;
5360}
5361
5362// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005363spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005364 spv::Id typeId, spv::Id left, spv::Id right,
5365 glslang::TBasicType typeProxy, bool reduceComparison)
5366{
John Kessenich66011cb2018-03-06 16:12:04 -07005367 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5368 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005369 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005370
5371 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005372 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005373 bool comparison = false;
5374
5375 switch (op) {
5376 case glslang::EOpAdd:
5377 case glslang::EOpAddAssign:
5378 if (isFloat)
5379 binOp = spv::OpFAdd;
5380 else
5381 binOp = spv::OpIAdd;
5382 break;
5383 case glslang::EOpSub:
5384 case glslang::EOpSubAssign:
5385 if (isFloat)
5386 binOp = spv::OpFSub;
5387 else
5388 binOp = spv::OpISub;
5389 break;
5390 case glslang::EOpMul:
5391 case glslang::EOpMulAssign:
5392 if (isFloat)
5393 binOp = spv::OpFMul;
5394 else
5395 binOp = spv::OpIMul;
5396 break;
5397 case glslang::EOpVectorTimesScalar:
5398 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005399 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005400 if (builder.isVector(right))
5401 std::swap(left, right);
5402 assert(builder.isScalar(right));
5403 needMatchingVectors = false;
5404 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005405 } else if (isFloat)
5406 binOp = spv::OpFMul;
5407 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005408 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005409 break;
5410 case glslang::EOpVectorTimesMatrix:
5411 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005412 binOp = spv::OpVectorTimesMatrix;
5413 break;
5414 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005415 binOp = spv::OpMatrixTimesVector;
5416 break;
5417 case glslang::EOpMatrixTimesScalar:
5418 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005419 binOp = spv::OpMatrixTimesScalar;
5420 break;
5421 case glslang::EOpMatrixTimesMatrix:
5422 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005423 binOp = spv::OpMatrixTimesMatrix;
5424 break;
5425 case glslang::EOpOuterProduct:
5426 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005427 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005428 break;
5429
5430 case glslang::EOpDiv:
5431 case glslang::EOpDivAssign:
5432 if (isFloat)
5433 binOp = spv::OpFDiv;
5434 else if (isUnsigned)
5435 binOp = spv::OpUDiv;
5436 else
5437 binOp = spv::OpSDiv;
5438 break;
5439 case glslang::EOpMod:
5440 case glslang::EOpModAssign:
5441 if (isFloat)
5442 binOp = spv::OpFMod;
5443 else if (isUnsigned)
5444 binOp = spv::OpUMod;
5445 else
5446 binOp = spv::OpSMod;
5447 break;
5448 case glslang::EOpRightShift:
5449 case glslang::EOpRightShiftAssign:
5450 if (isUnsigned)
5451 binOp = spv::OpShiftRightLogical;
5452 else
5453 binOp = spv::OpShiftRightArithmetic;
5454 break;
5455 case glslang::EOpLeftShift:
5456 case glslang::EOpLeftShiftAssign:
5457 binOp = spv::OpShiftLeftLogical;
5458 break;
5459 case glslang::EOpAnd:
5460 case glslang::EOpAndAssign:
5461 binOp = spv::OpBitwiseAnd;
5462 break;
5463 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005464 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005465 binOp = spv::OpLogicalAnd;
5466 break;
5467 case glslang::EOpInclusiveOr:
5468 case glslang::EOpInclusiveOrAssign:
5469 binOp = spv::OpBitwiseOr;
5470 break;
5471 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005472 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005473 binOp = spv::OpLogicalOr;
5474 break;
5475 case glslang::EOpExclusiveOr:
5476 case glslang::EOpExclusiveOrAssign:
5477 binOp = spv::OpBitwiseXor;
5478 break;
5479 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005480 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005481 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005482 break;
5483
Ian Romanickb3bd4022019-01-21 08:57:25 -08005484 case glslang::EOpAbsDifference:
5485 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5486 break;
5487
5488 case glslang::EOpAddSaturate:
5489 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5490 break;
5491
5492 case glslang::EOpSubSaturate:
5493 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5494 break;
5495
5496 case glslang::EOpAverage:
5497 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5498 break;
5499
5500 case glslang::EOpAverageRounded:
5501 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5502 break;
5503
5504 case glslang::EOpMul32x16:
5505 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5506 break;
5507
John Kessenich140f3df2015-06-26 16:58:36 -06005508 case glslang::EOpLessThan:
5509 case glslang::EOpGreaterThan:
5510 case glslang::EOpLessThanEqual:
5511 case glslang::EOpGreaterThanEqual:
5512 case glslang::EOpEqual:
5513 case glslang::EOpNotEqual:
5514 case glslang::EOpVectorEqual:
5515 case glslang::EOpVectorNotEqual:
5516 comparison = true;
5517 break;
5518 default:
5519 break;
5520 }
5521
John Kessenich7c1aa102015-10-15 13:29:11 -06005522 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005523 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005524 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005525 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5526 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005527 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005528
5529 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005530 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005531 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005532
qining25262b32016-05-06 17:25:16 -04005533 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005534 decorations.addNoContraction(builder, result);
5535 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005536 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005537 }
5538
5539 if (! comparison)
5540 return 0;
5541
John Kessenich7c1aa102015-10-15 13:29:11 -06005542 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005543
John Kessenich4583b612016-08-07 19:14:22 -06005544 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005545 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5546 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005547 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005548 return result;
5549 }
John Kessenich140f3df2015-06-26 16:58:36 -06005550
5551 switch (op) {
5552 case glslang::EOpLessThan:
5553 if (isFloat)
5554 binOp = spv::OpFOrdLessThan;
5555 else if (isUnsigned)
5556 binOp = spv::OpULessThan;
5557 else
5558 binOp = spv::OpSLessThan;
5559 break;
5560 case glslang::EOpGreaterThan:
5561 if (isFloat)
5562 binOp = spv::OpFOrdGreaterThan;
5563 else if (isUnsigned)
5564 binOp = spv::OpUGreaterThan;
5565 else
5566 binOp = spv::OpSGreaterThan;
5567 break;
5568 case glslang::EOpLessThanEqual:
5569 if (isFloat)
5570 binOp = spv::OpFOrdLessThanEqual;
5571 else if (isUnsigned)
5572 binOp = spv::OpULessThanEqual;
5573 else
5574 binOp = spv::OpSLessThanEqual;
5575 break;
5576 case glslang::EOpGreaterThanEqual:
5577 if (isFloat)
5578 binOp = spv::OpFOrdGreaterThanEqual;
5579 else if (isUnsigned)
5580 binOp = spv::OpUGreaterThanEqual;
5581 else
5582 binOp = spv::OpSGreaterThanEqual;
5583 break;
5584 case glslang::EOpEqual:
5585 case glslang::EOpVectorEqual:
5586 if (isFloat)
5587 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005588 else if (isBool)
5589 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005590 else
5591 binOp = spv::OpIEqual;
5592 break;
5593 case glslang::EOpNotEqual:
5594 case glslang::EOpVectorNotEqual:
5595 if (isFloat)
5596 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005597 else if (isBool)
5598 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005599 else
5600 binOp = spv::OpINotEqual;
5601 break;
5602 default:
5603 break;
5604 }
5605
qining25262b32016-05-06 17:25:16 -04005606 if (binOp != spv::OpNop) {
5607 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005608 decorations.addNoContraction(builder, result);
5609 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005610 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005611 }
John Kessenich140f3df2015-06-26 16:58:36 -06005612
5613 return 0;
5614}
5615
John Kessenich04bb8a02015-12-12 12:28:14 -07005616//
5617// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5618// These can be any of:
5619//
5620// matrix * scalar
5621// scalar * matrix
5622// matrix * matrix linear algebraic
5623// matrix * vector
5624// vector * matrix
5625// matrix * matrix componentwise
5626// matrix op matrix op in {+, -, /}
5627// matrix op scalar op in {+, -, /}
5628// scalar op matrix op in {+, -, /}
5629//
John Kessenichead86222018-03-28 18:01:20 -06005630spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5631 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005632{
5633 bool firstClass = true;
5634
5635 // First, handle first-class matrix operations (* and matrix/scalar)
5636 switch (op) {
5637 case spv::OpFDiv:
5638 if (builder.isMatrix(left) && builder.isScalar(right)) {
5639 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005640 spv::Id resultType = builder.getTypeId(right);
5641 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005642 op = spv::OpMatrixTimesScalar;
5643 } else
5644 firstClass = false;
5645 break;
5646 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005647 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005648 std::swap(left, right);
5649 assert(builder.isScalar(right));
5650 break;
5651 case spv::OpVectorTimesMatrix:
5652 assert(builder.isVector(left));
5653 assert(builder.isMatrix(right));
5654 break;
5655 case spv::OpMatrixTimesVector:
5656 assert(builder.isMatrix(left));
5657 assert(builder.isVector(right));
5658 break;
5659 case spv::OpMatrixTimesMatrix:
5660 assert(builder.isMatrix(left));
5661 assert(builder.isMatrix(right));
5662 break;
5663 default:
5664 firstClass = false;
5665 break;
5666 }
5667
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005668 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5669 firstClass = true;
5670
qining25262b32016-05-06 17:25:16 -04005671 if (firstClass) {
5672 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005673 decorations.addNoContraction(builder, result);
5674 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005675 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005676 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005677
LoopDawg592860c2016-06-09 08:57:35 -06005678 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005679 // The result type of all of them is the same type as the (a) matrix operand.
5680 // The algorithm is to:
5681 // - break the matrix(es) into vectors
5682 // - smear any scalar to a vector
5683 // - do vector operations
5684 // - make a matrix out the vector results
5685 switch (op) {
5686 case spv::OpFAdd:
5687 case spv::OpFSub:
5688 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005689 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005690 case spv::OpFMul:
5691 {
5692 // one time set up...
5693 bool leftMat = builder.isMatrix(left);
5694 bool rightMat = builder.isMatrix(right);
5695 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5696 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5697 spv::Id scalarType = builder.getScalarTypeId(typeId);
5698 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5699 std::vector<spv::Id> results;
5700 spv::Id smearVec = spv::NoResult;
5701 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005702 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005703 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005704 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005705
5706 // do each vector op
5707 for (unsigned int c = 0; c < numCols; ++c) {
5708 std::vector<unsigned int> indexes;
5709 indexes.push_back(c);
5710 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5711 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005712 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005713 decorations.addNoContraction(builder, result);
5714 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005715 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005716 }
5717
5718 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005719 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005720 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005721 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005722 }
5723 default:
5724 assert(0);
5725 return spv::NoResult;
5726 }
5727}
5728
John Kessenichead86222018-03-28 18:01:20 -06005729spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005730 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005731{
5732 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005733 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005734 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005735 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5736 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005737
5738 switch (op) {
5739 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005740 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005741 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005742 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005743 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005744 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005745 unaryOp = spv::OpSNegate;
5746 break;
5747
5748 case glslang::EOpLogicalNot:
5749 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005750 unaryOp = spv::OpLogicalNot;
5751 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005752 case glslang::EOpBitwiseNot:
5753 unaryOp = spv::OpNot;
5754 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005755
John Kessenich140f3df2015-06-26 16:58:36 -06005756 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005757 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005758 break;
5759 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005760 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005761 break;
5762 case glslang::EOpTranspose:
5763 unaryOp = spv::OpTranspose;
5764 break;
5765
5766 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005767 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005768 break;
5769 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005770 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005771 break;
5772 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005773 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005774 break;
5775 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005776 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005777 break;
5778 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005779 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005780 break;
5781 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005782 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005783 break;
5784 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005785 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005786 break;
5787 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005788 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005789 break;
5790
5791 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005792 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005793 break;
5794 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005795 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005796 break;
5797 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005798 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005799 break;
5800 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005801 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005802 break;
5803 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005804 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005805 break;
5806 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005807 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005808 break;
5809
5810 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005811 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005812 break;
5813 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005814 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005815 break;
5816
5817 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005818 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005819 break;
5820 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005821 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005822 break;
5823 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005824 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005825 break;
5826 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005827 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005828 break;
5829 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005830 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005831 break;
5832 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005833 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005834 break;
5835
5836 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005837 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005838 break;
5839 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005840 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005841 break;
5842 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005843 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005844 break;
5845 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005846 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005847 break;
5848 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005849 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005850 break;
5851 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005852 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005853 break;
5854
5855 case glslang::EOpIsNan:
5856 unaryOp = spv::OpIsNan;
5857 break;
5858 case glslang::EOpIsInf:
5859 unaryOp = spv::OpIsInf;
5860 break;
LoopDawg592860c2016-06-09 08:57:35 -06005861 case glslang::EOpIsFinite:
5862 unaryOp = spv::OpIsFinite;
5863 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005864
Rex Xucbc426e2015-12-15 16:03:10 +08005865 case glslang::EOpFloatBitsToInt:
5866 case glslang::EOpFloatBitsToUint:
5867 case glslang::EOpIntBitsToFloat:
5868 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005869 case glslang::EOpDoubleBitsToInt64:
5870 case glslang::EOpDoubleBitsToUint64:
5871 case glslang::EOpInt64BitsToDouble:
5872 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005873 case glslang::EOpFloat16BitsToInt16:
5874 case glslang::EOpFloat16BitsToUint16:
5875 case glslang::EOpInt16BitsToFloat16:
5876 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005877 unaryOp = spv::OpBitcast;
5878 break;
5879
John Kessenich140f3df2015-06-26 16:58:36 -06005880 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005881 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005882 break;
5883 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005884 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005885 break;
5886 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005887 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005888 break;
5889 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005890 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005891 break;
5892 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005893 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005894 break;
5895 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005896 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005897 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005898#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005899 case glslang::EOpPackSnorm4x8:
5900 libCall = spv::GLSLstd450PackSnorm4x8;
5901 break;
5902 case glslang::EOpUnpackSnorm4x8:
5903 libCall = spv::GLSLstd450UnpackSnorm4x8;
5904 break;
5905 case glslang::EOpPackUnorm4x8:
5906 libCall = spv::GLSLstd450PackUnorm4x8;
5907 break;
5908 case glslang::EOpUnpackUnorm4x8:
5909 libCall = spv::GLSLstd450UnpackUnorm4x8;
5910 break;
5911 case glslang::EOpPackDouble2x32:
5912 libCall = spv::GLSLstd450PackDouble2x32;
5913 break;
5914 case glslang::EOpUnpackDouble2x32:
5915 libCall = spv::GLSLstd450UnpackDouble2x32;
5916 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005917#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005918
Rex Xu8ff43de2016-04-22 16:51:45 +08005919 case glslang::EOpPackInt2x32:
5920 case glslang::EOpUnpackInt2x32:
5921 case glslang::EOpPackUint2x32:
5922 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005923 case glslang::EOpPack16:
5924 case glslang::EOpPack32:
5925 case glslang::EOpPack64:
5926 case glslang::EOpUnpack32:
5927 case glslang::EOpUnpack16:
5928 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005929 case glslang::EOpPackInt2x16:
5930 case glslang::EOpUnpackInt2x16:
5931 case glslang::EOpPackUint2x16:
5932 case glslang::EOpUnpackUint2x16:
5933 case glslang::EOpPackInt4x16:
5934 case glslang::EOpUnpackInt4x16:
5935 case glslang::EOpPackUint4x16:
5936 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005937 case glslang::EOpPackFloat2x16:
5938 case glslang::EOpUnpackFloat2x16:
5939 unaryOp = spv::OpBitcast;
5940 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005941
John Kessenich140f3df2015-06-26 16:58:36 -06005942 case glslang::EOpDPdx:
5943 unaryOp = spv::OpDPdx;
5944 break;
5945 case glslang::EOpDPdy:
5946 unaryOp = spv::OpDPdy;
5947 break;
5948 case glslang::EOpFwidth:
5949 unaryOp = spv::OpFwidth;
5950 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005951
John Kessenich140f3df2015-06-26 16:58:36 -06005952 case glslang::EOpAny:
5953 unaryOp = spv::OpAny;
5954 break;
5955 case glslang::EOpAll:
5956 unaryOp = spv::OpAll;
5957 break;
5958
5959 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005960 if (isFloat)
5961 libCall = spv::GLSLstd450FAbs;
5962 else
5963 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005964 break;
5965 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005966 if (isFloat)
5967 libCall = spv::GLSLstd450FSign;
5968 else
5969 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005970 break;
5971
John Kessenicha28f7a72019-08-06 07:00:58 -06005972#ifndef GLSLANG_WEB
5973 case glslang::EOpDPdxFine:
5974 unaryOp = spv::OpDPdxFine;
5975 break;
5976 case glslang::EOpDPdyFine:
5977 unaryOp = spv::OpDPdyFine;
5978 break;
5979 case glslang::EOpFwidthFine:
5980 unaryOp = spv::OpFwidthFine;
5981 break;
5982 case glslang::EOpDPdxCoarse:
5983 unaryOp = spv::OpDPdxCoarse;
5984 break;
5985 case glslang::EOpDPdyCoarse:
5986 unaryOp = spv::OpDPdyCoarse;
5987 break;
5988 case glslang::EOpFwidthCoarse:
5989 unaryOp = spv::OpFwidthCoarse;
5990 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04005991 case glslang::EOpRayQueryProceed:
5992 unaryOp = spv::OpRayQueryProceedKHR;
5993 break;
5994 case glslang::EOpRayQueryGetRayTMin:
5995 unaryOp = spv::OpRayQueryGetRayTMinKHR;
5996 break;
5997 case glslang::EOpRayQueryGetRayFlags:
5998 unaryOp = spv::OpRayQueryGetRayFlagsKHR;
5999 break;
6000 case glslang::EOpRayQueryGetWorldRayOrigin:
6001 unaryOp = spv::OpRayQueryGetWorldRayOriginKHR;
6002 break;
6003 case glslang::EOpRayQueryGetWorldRayDirection:
6004 unaryOp = spv::OpRayQueryGetWorldRayDirectionKHR;
6005 break;
6006 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
6007 unaryOp = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
6008 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006009 case glslang::EOpInterpolateAtCentroid:
6010 if (typeProxy == glslang::EbtFloat16)
6011 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6012 libCall = spv::GLSLstd450InterpolateAtCentroid;
6013 break;
John Kessenichfc51d282015-08-19 13:34:18 -06006014 case glslang::EOpAtomicCounterIncrement:
6015 case glslang::EOpAtomicCounterDecrement:
6016 case glslang::EOpAtomicCounter:
6017 {
6018 // Handle all of the atomics in one place, in createAtomicOperation()
6019 std::vector<spv::Id> operands;
6020 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006021 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06006022 }
6023
John Kessenichfc51d282015-08-19 13:34:18 -06006024 case glslang::EOpBitFieldReverse:
6025 unaryOp = spv::OpBitReverse;
6026 break;
6027 case glslang::EOpBitCount:
6028 unaryOp = spv::OpBitCount;
6029 break;
6030 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006031 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006032 break;
6033 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006034 if (isUnsigned)
6035 libCall = spv::GLSLstd450FindUMsb;
6036 else
6037 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006038 break;
6039
Ian Romanickb3bd4022019-01-21 08:57:25 -08006040 case glslang::EOpCountLeadingZeros:
6041 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6042 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6043 unaryOp = spv::OpUCountLeadingZerosINTEL;
6044 break;
6045
6046 case glslang::EOpCountTrailingZeros:
6047 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6048 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6049 unaryOp = spv::OpUCountTrailingZerosINTEL;
6050 break;
6051
Rex Xu574ab042016-04-14 16:53:07 +08006052 case glslang::EOpBallot:
6053 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006054 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006055 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08006056 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08006057 case glslang::EOpMinInvocations:
6058 case glslang::EOpMaxInvocations:
6059 case glslang::EOpAddInvocations:
6060 case glslang::EOpMinInvocationsNonUniform:
6061 case glslang::EOpMaxInvocationsNonUniform:
6062 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006063 case glslang::EOpMinInvocationsInclusiveScan:
6064 case glslang::EOpMaxInvocationsInclusiveScan:
6065 case glslang::EOpAddInvocationsInclusiveScan:
6066 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6067 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6068 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6069 case glslang::EOpMinInvocationsExclusiveScan:
6070 case glslang::EOpMaxInvocationsExclusiveScan:
6071 case glslang::EOpAddInvocationsExclusiveScan:
6072 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6073 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6074 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08006075 {
6076 std::vector<spv::Id> operands;
6077 operands.push_back(operand);
6078 return createInvocationsOperation(op, typeId, operands, typeProxy);
6079 }
John Kessenich66011cb2018-03-06 16:12:04 -07006080 case glslang::EOpSubgroupAll:
6081 case glslang::EOpSubgroupAny:
6082 case glslang::EOpSubgroupAllEqual:
6083 case glslang::EOpSubgroupBroadcastFirst:
6084 case glslang::EOpSubgroupBallot:
6085 case glslang::EOpSubgroupInverseBallot:
6086 case glslang::EOpSubgroupBallotBitCount:
6087 case glslang::EOpSubgroupBallotInclusiveBitCount:
6088 case glslang::EOpSubgroupBallotExclusiveBitCount:
6089 case glslang::EOpSubgroupBallotFindLSB:
6090 case glslang::EOpSubgroupBallotFindMSB:
6091 case glslang::EOpSubgroupAdd:
6092 case glslang::EOpSubgroupMul:
6093 case glslang::EOpSubgroupMin:
6094 case glslang::EOpSubgroupMax:
6095 case glslang::EOpSubgroupAnd:
6096 case glslang::EOpSubgroupOr:
6097 case glslang::EOpSubgroupXor:
6098 case glslang::EOpSubgroupInclusiveAdd:
6099 case glslang::EOpSubgroupInclusiveMul:
6100 case glslang::EOpSubgroupInclusiveMin:
6101 case glslang::EOpSubgroupInclusiveMax:
6102 case glslang::EOpSubgroupInclusiveAnd:
6103 case glslang::EOpSubgroupInclusiveOr:
6104 case glslang::EOpSubgroupInclusiveXor:
6105 case glslang::EOpSubgroupExclusiveAdd:
6106 case glslang::EOpSubgroupExclusiveMul:
6107 case glslang::EOpSubgroupExclusiveMin:
6108 case glslang::EOpSubgroupExclusiveMax:
6109 case glslang::EOpSubgroupExclusiveAnd:
6110 case glslang::EOpSubgroupExclusiveOr:
6111 case glslang::EOpSubgroupExclusiveXor:
6112 case glslang::EOpSubgroupQuadSwapHorizontal:
6113 case glslang::EOpSubgroupQuadSwapVertical:
6114 case glslang::EOpSubgroupQuadSwapDiagonal: {
6115 std::vector<spv::Id> operands;
6116 operands.push_back(operand);
6117 return createSubgroupOperation(op, typeId, operands, typeProxy);
6118 }
Rex Xu9d93a232016-05-05 12:30:44 +08006119 case glslang::EOpMbcnt:
6120 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6121 libCall = spv::MbcntAMD;
6122 break;
6123
6124 case glslang::EOpCubeFaceIndex:
6125 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6126 libCall = spv::CubeFaceIndexAMD;
6127 break;
6128
6129 case glslang::EOpCubeFaceCoord:
6130 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6131 libCall = spv::CubeFaceCoordAMD;
6132 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006133 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006134 unaryOp = spv::OpGroupNonUniformPartitionNV;
6135 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006136 case glslang::EOpConstructReference:
6137 unaryOp = spv::OpBitcast;
6138 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006139#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006140
6141 case glslang::EOpCopyObject:
6142 unaryOp = spv::OpCopyObject;
6143 break;
6144
John Kessenich140f3df2015-06-26 16:58:36 -06006145 default:
6146 return 0;
6147 }
6148
6149 spv::Id id;
6150 if (libCall >= 0) {
6151 std::vector<spv::Id> args;
6152 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006153 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006154 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006155 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006156 }
John Kessenich140f3df2015-06-26 16:58:36 -06006157
John Kessenichb9197c82019-08-11 07:41:45 -06006158 decorations.addNoContraction(builder, id);
6159 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006160 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006161}
6162
John Kessenich7a53f762016-01-20 11:19:27 -07006163// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006164spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6165 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006166{
6167 // Handle unary operations vector by vector.
6168 // The result type is the same type as the original type.
6169 // The algorithm is to:
6170 // - break the matrix into vectors
6171 // - apply the operation to each vector
6172 // - make a matrix out the vector results
6173
6174 // get the types sorted out
6175 int numCols = builder.getNumColumns(operand);
6176 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006177 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6178 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006179 std::vector<spv::Id> results;
6180
6181 // do each vector op
6182 for (int c = 0; c < numCols; ++c) {
6183 std::vector<unsigned int> indexes;
6184 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006185 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6186 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006187 decorations.addNoContraction(builder, destVec);
6188 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006189 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006190 }
6191
6192 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006193 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006194 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006195 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006196}
6197
John Kessenichad7645f2018-06-04 19:11:25 -06006198// For converting integers where both the bitwidth and the signedness could
6199// change, but only do the width change here. The caller is still responsible
6200// for the signedness conversion.
6201spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006202{
John Kessenichad7645f2018-06-04 19:11:25 -06006203 // Get the result type width, based on the type to convert to.
6204 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006205 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006206 case glslang::EOpConvInt16ToUint8:
6207 case glslang::EOpConvIntToUint8:
6208 case glslang::EOpConvInt64ToUint8:
6209 case glslang::EOpConvUint16ToInt8:
6210 case glslang::EOpConvUintToInt8:
6211 case glslang::EOpConvUint64ToInt8:
6212 width = 8;
6213 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006214 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006215 case glslang::EOpConvIntToUint16:
6216 case glslang::EOpConvInt64ToUint16:
6217 case glslang::EOpConvUint8ToInt16:
6218 case glslang::EOpConvUintToInt16:
6219 case glslang::EOpConvUint64ToInt16:
6220 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006221 break;
6222 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006223 case glslang::EOpConvInt16ToUint:
6224 case glslang::EOpConvInt64ToUint:
6225 case glslang::EOpConvUint8ToInt:
6226 case glslang::EOpConvUint16ToInt:
6227 case glslang::EOpConvUint64ToInt:
6228 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006229 break;
6230 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006231 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006232 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006233 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006234 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006235 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006236 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006237 break;
6238
6239 default:
6240 assert(false && "Default missing");
6241 break;
6242 }
6243
John Kessenichad7645f2018-06-04 19:11:25 -06006244 // Get the conversion operation and result type,
6245 // based on the target width, but the source type.
6246 spv::Id type = spv::NoType;
6247 spv::Op convOp = spv::OpNop;
6248 switch(op) {
6249 case glslang::EOpConvInt8ToUint16:
6250 case glslang::EOpConvInt8ToUint:
6251 case glslang::EOpConvInt8ToUint64:
6252 case glslang::EOpConvInt16ToUint8:
6253 case glslang::EOpConvInt16ToUint:
6254 case glslang::EOpConvInt16ToUint64:
6255 case glslang::EOpConvIntToUint8:
6256 case glslang::EOpConvIntToUint16:
6257 case glslang::EOpConvIntToUint64:
6258 case glslang::EOpConvInt64ToUint8:
6259 case glslang::EOpConvInt64ToUint16:
6260 case glslang::EOpConvInt64ToUint:
6261 convOp = spv::OpSConvert;
6262 type = builder.makeIntType(width);
6263 break;
6264 default:
6265 convOp = spv::OpUConvert;
6266 type = builder.makeUintType(width);
6267 break;
6268 }
6269
John Kessenich66011cb2018-03-06 16:12:04 -07006270 if (vectorSize > 0)
6271 type = builder.makeVectorType(type, vectorSize);
6272
John Kessenichad7645f2018-06-04 19:11:25 -06006273 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006274}
6275
John Kessenichead86222018-03-28 18:01:20 -06006276spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6277 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006278{
6279 spv::Op convOp = spv::OpNop;
6280 spv::Id zero = 0;
6281 spv::Id one = 0;
6282
6283 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6284
6285 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006286 case glslang::EOpConvIntToBool:
6287 case glslang::EOpConvUintToBool:
6288 zero = builder.makeUintConstant(0);
6289 zero = makeSmearedConstant(zero, vectorSize);
6290 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006291 case glslang::EOpConvFloatToBool:
6292 zero = builder.makeFloatConstant(0.0F);
6293 zero = makeSmearedConstant(zero, vectorSize);
6294 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006295 case glslang::EOpConvBoolToFloat:
6296 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006297 zero = builder.makeFloatConstant(0.0F);
6298 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006299 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006300
John Kessenich140f3df2015-06-26 16:58:36 -06006301 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006302 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006303#ifndef GLSLANG_WEB
6304 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006305 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006306 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006307 } else
6308#endif
6309 {
6310 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006311 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006312 }
Rex Xucabbb782017-03-24 13:41:14 +08006313
John Kessenich140f3df2015-06-26 16:58:36 -06006314 convOp = spv::OpSelect;
6315 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006316
John Kessenich140f3df2015-06-26 16:58:36 -06006317 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006318 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006319#ifndef GLSLANG_WEB
6320 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006321 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006322 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006323 } else
6324#endif
6325 {
6326 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006327 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006328 }
Rex Xucabbb782017-03-24 13:41:14 +08006329
John Kessenich140f3df2015-06-26 16:58:36 -06006330 convOp = spv::OpSelect;
6331 break;
6332
John Kessenich66011cb2018-03-06 16:12:04 -07006333 case glslang::EOpConvInt8ToFloat16:
6334 case glslang::EOpConvInt8ToFloat:
6335 case glslang::EOpConvInt8ToDouble:
6336 case glslang::EOpConvInt16ToFloat16:
6337 case glslang::EOpConvInt16ToFloat:
6338 case glslang::EOpConvInt16ToDouble:
6339 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006340 case glslang::EOpConvIntToFloat:
6341 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006342 case glslang::EOpConvInt64ToFloat:
6343 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006344 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006345 convOp = spv::OpConvertSToF;
6346 break;
6347
John Kessenich66011cb2018-03-06 16:12:04 -07006348 case glslang::EOpConvUint8ToFloat16:
6349 case glslang::EOpConvUint8ToFloat:
6350 case glslang::EOpConvUint8ToDouble:
6351 case glslang::EOpConvUint16ToFloat16:
6352 case glslang::EOpConvUint16ToFloat:
6353 case glslang::EOpConvUint16ToDouble:
6354 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006355 case glslang::EOpConvUintToFloat:
6356 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006357 case glslang::EOpConvUint64ToFloat:
6358 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006359 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006360 convOp = spv::OpConvertUToF;
6361 break;
6362
John Kessenich66011cb2018-03-06 16:12:04 -07006363 case glslang::EOpConvFloat16ToInt8:
6364 case glslang::EOpConvFloatToInt8:
6365 case glslang::EOpConvDoubleToInt8:
6366 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006367 case glslang::EOpConvFloatToInt16:
6368 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006369 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006370 case glslang::EOpConvFloatToInt:
6371 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006372 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006373 case glslang::EOpConvFloatToInt64:
6374 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006375 convOp = spv::OpConvertFToS;
6376 break;
6377
John Kessenich66011cb2018-03-06 16:12:04 -07006378 case glslang::EOpConvUint8ToInt8:
6379 case glslang::EOpConvInt8ToUint8:
6380 case glslang::EOpConvUint16ToInt16:
6381 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006382 case glslang::EOpConvUintToInt:
6383 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006384 case glslang::EOpConvUint64ToInt64:
6385 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006386 if (builder.isInSpecConstCodeGenMode()) {
6387 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006388#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006389 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6390 zero = builder.makeUint8Constant(0);
6391 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006392 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006393 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6394 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006395 } else
6396#endif
6397 {
Rex Xucabbb782017-03-24 13:41:14 +08006398 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006399 }
qining189b2032016-04-12 23:16:20 -04006400 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006401 // Use OpIAdd, instead of OpBitcast to do the conversion when
6402 // generating for OpSpecConstantOp instruction.
6403 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6404 }
6405 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006406 convOp = spv::OpBitcast;
6407 break;
6408
John Kessenich66011cb2018-03-06 16:12:04 -07006409 case glslang::EOpConvFloat16ToUint8:
6410 case glslang::EOpConvFloatToUint8:
6411 case glslang::EOpConvDoubleToUint8:
6412 case glslang::EOpConvFloat16ToUint16:
6413 case glslang::EOpConvFloatToUint16:
6414 case glslang::EOpConvDoubleToUint16:
6415 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006416 case glslang::EOpConvFloatToUint:
6417 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006418 case glslang::EOpConvFloatToUint64:
6419 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006420 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006421 convOp = spv::OpConvertFToU;
6422 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006423
John Kessenich39697cd2019-08-08 10:35:51 -06006424#ifndef GLSLANG_WEB
6425 case glslang::EOpConvInt8ToBool:
6426 case glslang::EOpConvUint8ToBool:
6427 zero = builder.makeUint8Constant(0);
6428 zero = makeSmearedConstant(zero, vectorSize);
6429 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6430 case glslang::EOpConvInt16ToBool:
6431 case glslang::EOpConvUint16ToBool:
6432 zero = builder.makeUint16Constant(0);
6433 zero = makeSmearedConstant(zero, vectorSize);
6434 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6435 case glslang::EOpConvInt64ToBool:
6436 case glslang::EOpConvUint64ToBool:
6437 zero = builder.makeUint64Constant(0);
6438 zero = makeSmearedConstant(zero, vectorSize);
6439 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6440 case glslang::EOpConvDoubleToBool:
6441 zero = builder.makeDoubleConstant(0.0);
6442 zero = makeSmearedConstant(zero, vectorSize);
6443 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6444 case glslang::EOpConvFloat16ToBool:
6445 zero = builder.makeFloat16Constant(0.0F);
6446 zero = makeSmearedConstant(zero, vectorSize);
6447 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6448 case glslang::EOpConvBoolToDouble:
6449 convOp = spv::OpSelect;
6450 zero = builder.makeDoubleConstant(0.0);
6451 one = builder.makeDoubleConstant(1.0);
6452 break;
6453 case glslang::EOpConvBoolToFloat16:
6454 convOp = spv::OpSelect;
6455 zero = builder.makeFloat16Constant(0.0F);
6456 one = builder.makeFloat16Constant(1.0F);
6457 break;
6458 case glslang::EOpConvBoolToInt8:
6459 zero = builder.makeInt8Constant(0);
6460 one = builder.makeInt8Constant(1);
6461 convOp = spv::OpSelect;
6462 break;
6463 case glslang::EOpConvBoolToUint8:
6464 zero = builder.makeUint8Constant(0);
6465 one = builder.makeUint8Constant(1);
6466 convOp = spv::OpSelect;
6467 break;
6468 case glslang::EOpConvBoolToInt16:
6469 zero = builder.makeInt16Constant(0);
6470 one = builder.makeInt16Constant(1);
6471 convOp = spv::OpSelect;
6472 break;
6473 case glslang::EOpConvBoolToUint16:
6474 zero = builder.makeUint16Constant(0);
6475 one = builder.makeUint16Constant(1);
6476 convOp = spv::OpSelect;
6477 break;
6478 case glslang::EOpConvDoubleToFloat:
6479 case glslang::EOpConvFloatToDouble:
6480 case glslang::EOpConvDoubleToFloat16:
6481 case glslang::EOpConvFloat16ToDouble:
6482 case glslang::EOpConvFloatToFloat16:
6483 case glslang::EOpConvFloat16ToFloat:
6484 convOp = spv::OpFConvert;
6485 if (builder.isMatrixType(destType))
6486 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6487 break;
6488
John Kessenich66011cb2018-03-06 16:12:04 -07006489 case glslang::EOpConvInt8ToInt16:
6490 case glslang::EOpConvInt8ToInt:
6491 case glslang::EOpConvInt8ToInt64:
6492 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006493 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006494 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006495 case glslang::EOpConvIntToInt8:
6496 case glslang::EOpConvIntToInt16:
6497 case glslang::EOpConvIntToInt64:
6498 case glslang::EOpConvInt64ToInt8:
6499 case glslang::EOpConvInt64ToInt16:
6500 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006501 convOp = spv::OpSConvert;
6502 break;
6503
John Kessenich66011cb2018-03-06 16:12:04 -07006504 case glslang::EOpConvUint8ToUint16:
6505 case glslang::EOpConvUint8ToUint:
6506 case glslang::EOpConvUint8ToUint64:
6507 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006508 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006509 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006510 case glslang::EOpConvUintToUint8:
6511 case glslang::EOpConvUintToUint16:
6512 case glslang::EOpConvUintToUint64:
6513 case glslang::EOpConvUint64ToUint8:
6514 case glslang::EOpConvUint64ToUint16:
6515 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006516 convOp = spv::OpUConvert;
6517 break;
6518
John Kessenich66011cb2018-03-06 16:12:04 -07006519 case glslang::EOpConvInt8ToUint16:
6520 case glslang::EOpConvInt8ToUint:
6521 case glslang::EOpConvInt8ToUint64:
6522 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006523 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006524 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006525 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006526 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006527 case glslang::EOpConvIntToUint64:
6528 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006529 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006530 case glslang::EOpConvInt64ToUint:
6531 case glslang::EOpConvUint8ToInt16:
6532 case glslang::EOpConvUint8ToInt:
6533 case glslang::EOpConvUint8ToInt64:
6534 case glslang::EOpConvUint16ToInt8:
6535 case glslang::EOpConvUint16ToInt:
6536 case glslang::EOpConvUint16ToInt64:
6537 case glslang::EOpConvUintToInt8:
6538 case glslang::EOpConvUintToInt16:
6539 case glslang::EOpConvUintToInt64:
6540 case glslang::EOpConvUint64ToInt8:
6541 case glslang::EOpConvUint64ToInt16:
6542 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006543 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006544 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006545
6546 if (builder.isInSpecConstCodeGenMode()) {
6547 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006548 switch(op) {
6549 case glslang::EOpConvInt16ToUint8:
6550 case glslang::EOpConvIntToUint8:
6551 case glslang::EOpConvInt64ToUint8:
6552 case glslang::EOpConvUint16ToInt8:
6553 case glslang::EOpConvUintToInt8:
6554 case glslang::EOpConvUint64ToInt8:
6555 zero = builder.makeUint8Constant(0);
6556 break;
6557 case glslang::EOpConvInt8ToUint16:
6558 case glslang::EOpConvIntToUint16:
6559 case glslang::EOpConvInt64ToUint16:
6560 case glslang::EOpConvUint8ToInt16:
6561 case glslang::EOpConvUintToInt16:
6562 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006563 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006564 break;
6565 case glslang::EOpConvInt8ToUint:
6566 case glslang::EOpConvInt16ToUint:
6567 case glslang::EOpConvInt64ToUint:
6568 case glslang::EOpConvUint8ToInt:
6569 case glslang::EOpConvUint16ToInt:
6570 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006571 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006572 break;
6573 case glslang::EOpConvInt8ToUint64:
6574 case glslang::EOpConvInt16ToUint64:
6575 case glslang::EOpConvIntToUint64:
6576 case glslang::EOpConvUint8ToInt64:
6577 case glslang::EOpConvUint16ToInt64:
6578 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006579 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006580 break;
6581 default:
6582 assert(false && "Default missing");
6583 break;
6584 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006585 zero = makeSmearedConstant(zero, vectorSize);
6586 // Use OpIAdd, instead of OpBitcast to do the conversion when
6587 // generating for OpSpecConstantOp instruction.
6588 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6589 }
6590 // For normal run-time conversion instruction, use OpBitcast.
6591 convOp = spv::OpBitcast;
6592 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006593 case glslang::EOpConvUint64ToPtr:
6594 convOp = spv::OpConvertUToPtr;
6595 break;
6596 case glslang::EOpConvPtrToUint64:
6597 convOp = spv::OpConvertPtrToU;
6598 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006599 case glslang::EOpConvPtrToUvec2:
6600 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006601 if (builder.isVector(operand))
6602 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6603 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006604 convOp = spv::OpBitcast;
6605 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006606#endif
6607
John Kessenich140f3df2015-06-26 16:58:36 -06006608 default:
6609 break;
6610 }
6611
6612 spv::Id result = 0;
6613 if (convOp == spv::OpNop)
6614 return result;
6615
6616 if (convOp == spv::OpSelect) {
6617 zero = makeSmearedConstant(zero, vectorSize);
6618 one = makeSmearedConstant(one, vectorSize);
6619 result = builder.createTriOp(convOp, destType, operand, one, zero);
6620 } else
6621 result = builder.createUnaryOp(convOp, destType, operand);
6622
John Kessenichead86222018-03-28 18:01:20 -06006623 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006624 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006625 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006626}
6627
6628spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6629{
6630 if (vectorSize == 0)
6631 return constant;
6632
6633 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6634 std::vector<spv::Id> components;
6635 for (int c = 0; c < vectorSize; ++c)
6636 components.push_back(constant);
6637 return builder.makeCompositeConstant(vectorTypeId, components);
6638}
6639
John Kessenich426394d2015-07-23 10:22:48 -06006640// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006641spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6642 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6643 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006644{
6645 spv::Op opCode = spv::OpNop;
6646
6647 switch (op) {
6648 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006649 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006650 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006651 opCode = spv::OpAtomicIAdd;
6652 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006653 case glslang::EOpAtomicCounterSubtract:
6654 opCode = spv::OpAtomicISub;
6655 break;
John Kessenich426394d2015-07-23 10:22:48 -06006656 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006657 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006658 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006659 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6660 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006661 break;
6662 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006663 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006664 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006665 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6666 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006667 break;
6668 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006669 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006670 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006671 opCode = spv::OpAtomicAnd;
6672 break;
6673 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006674 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006675 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006676 opCode = spv::OpAtomicOr;
6677 break;
6678 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006679 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006680 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006681 opCode = spv::OpAtomicXor;
6682 break;
6683 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006684 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006685 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006686 opCode = spv::OpAtomicExchange;
6687 break;
6688 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006689 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006690 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006691 opCode = spv::OpAtomicCompareExchange;
6692 break;
6693 case glslang::EOpAtomicCounterIncrement:
6694 opCode = spv::OpAtomicIIncrement;
6695 break;
6696 case glslang::EOpAtomicCounterDecrement:
6697 opCode = spv::OpAtomicIDecrement;
6698 break;
6699 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006700 case glslang::EOpImageAtomicLoad:
6701 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006702 opCode = spv::OpAtomicLoad;
6703 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006704 case glslang::EOpAtomicStore:
6705 case glslang::EOpImageAtomicStore:
6706 opCode = spv::OpAtomicStore;
6707 break;
John Kessenich426394d2015-07-23 10:22:48 -06006708 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006709 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006710 break;
6711 }
6712
Rex Xue8fe8b02017-09-26 15:42:56 +08006713 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6714 builder.addCapability(spv::CapabilityInt64Atomics);
6715
John Kessenich426394d2015-07-23 10:22:48 -06006716 // Sort out the operands
6717 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006718 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006719 // - compare-exchange swaps the value and comparator
6720 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006721 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006722 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6723 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6724 spv::Id scopeId;
6725 if (glslangIntermediate->usingVulkanMemoryModel()) {
6726 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6727 } else {
6728 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6729 }
6730 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006731 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6732 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006733 spv::MemorySemanticsVolatileMask :
6734 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006735 spv::Id semanticsId2 = semanticsId;
6736
6737 pointerId = operands[0];
6738 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6739 // no additional operands
6740 } else if (opCode == spv::OpAtomicCompareExchange) {
6741 compareId = operands[1];
6742 valueId = operands[2];
6743 if (operands.size() > 3) {
6744 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006745 semanticsId = builder.makeUintConstant(
6746 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6747 semanticsId2 = builder.makeUintConstant(
6748 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006749 }
6750 } else if (opCode == spv::OpAtomicLoad) {
6751 if (operands.size() > 1) {
6752 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006753 semanticsId = builder.makeUintConstant(
6754 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006755 }
6756 } else {
6757 // atomic store or RMW
6758 valueId = operands[1];
6759 if (operands.size() > 2) {
6760 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006761 semanticsId = builder.makeUintConstant
6762 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006763 }
Rex Xu04db3f52015-09-16 11:44:02 +08006764 }
John Kessenich426394d2015-07-23 10:22:48 -06006765
Jeff Bolz36831c92018-09-05 10:11:41 -05006766 // Check for capabilities
6767 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006768 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6769 spv::MemorySemanticsMakeVisibleKHRMask |
6770 spv::MemorySemanticsOutputMemoryKHRMask |
6771 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006772 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6773 }
John Kessenich426394d2015-07-23 10:22:48 -06006774
Jeff Bolz36831c92018-09-05 10:11:41 -05006775 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6776 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6777 }
John Kessenich48d6e792017-10-06 21:21:48 -06006778
Jeff Bolz36831c92018-09-05 10:11:41 -05006779 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6780 spvAtomicOperands.push_back(pointerId);
6781 spvAtomicOperands.push_back(scopeId);
6782 spvAtomicOperands.push_back(semanticsId);
6783 if (opCode == spv::OpAtomicCompareExchange) {
6784 spvAtomicOperands.push_back(semanticsId2);
6785 spvAtomicOperands.push_back(valueId);
6786 spvAtomicOperands.push_back(compareId);
6787 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6788 spvAtomicOperands.push_back(valueId);
6789 }
John Kessenich48d6e792017-10-06 21:21:48 -06006790
Jeff Bolz36831c92018-09-05 10:11:41 -05006791 if (opCode == spv::OpAtomicStore) {
6792 builder.createNoResultOp(opCode, spvAtomicOperands);
6793 return 0;
6794 } else {
6795 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6796
6797 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6798 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6799 if (op == glslang::EOpAtomicCounterDecrement)
6800 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6801
6802 return resultId;
6803 }
John Kessenich426394d2015-07-23 10:22:48 -06006804}
6805
John Kessenich91cef522016-05-05 16:45:40 -06006806// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07006807spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
6808 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006809{
John Kessenich66011cb2018-03-06 16:12:04 -07006810 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6811 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006812
Rex Xu51596642016-09-21 18:56:12 +08006813 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006814 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006815 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6816
chaocf200da82016-12-20 12:44:35 -08006817 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6818 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006819 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6820 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006821 } else if (op == glslang::EOpAnyInvocation ||
6822 op == glslang::EOpAllInvocations ||
6823 op == glslang::EOpAllInvocationsEqual) {
6824 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6825 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006826 } else {
6827 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006828 if (op == glslang::EOpMinInvocationsNonUniform ||
6829 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006830 op == glslang::EOpAddInvocationsNonUniform ||
6831 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6832 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6833 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6834 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6835 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6836 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006837 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006838
Rex Xu430ef402016-10-14 17:22:23 +08006839 switch (op) {
6840 case glslang::EOpMinInvocations:
6841 case glslang::EOpMaxInvocations:
6842 case glslang::EOpAddInvocations:
6843 case glslang::EOpMinInvocationsNonUniform:
6844 case glslang::EOpMaxInvocationsNonUniform:
6845 case glslang::EOpAddInvocationsNonUniform:
6846 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006847 break;
6848 case glslang::EOpMinInvocationsInclusiveScan:
6849 case glslang::EOpMaxInvocationsInclusiveScan:
6850 case glslang::EOpAddInvocationsInclusiveScan:
6851 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6852 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6853 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6854 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006855 break;
6856 case glslang::EOpMinInvocationsExclusiveScan:
6857 case glslang::EOpMaxInvocationsExclusiveScan:
6858 case glslang::EOpAddInvocationsExclusiveScan:
6859 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6860 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6861 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6862 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006863 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006864 default:
6865 break;
Rex Xu430ef402016-10-14 17:22:23 +08006866 }
John Kessenich149afc32018-08-14 13:31:43 -06006867 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6868 spvGroupOperands.push_back(scope);
6869 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006870 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006871 spvGroupOperands.push_back(groupOp);
6872 }
Rex Xu51596642016-09-21 18:56:12 +08006873 }
6874
John Kessenich149afc32018-08-14 13:31:43 -06006875 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6876 spv::IdImmediate op = { true, *opIt };
6877 spvGroupOperands.push_back(op);
6878 }
John Kessenich91cef522016-05-05 16:45:40 -06006879
6880 switch (op) {
6881 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006882 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006883 break;
John Kessenich91cef522016-05-05 16:45:40 -06006884 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006885 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006886 break;
John Kessenich91cef522016-05-05 16:45:40 -06006887 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006888 opCode = spv::OpSubgroupAllEqualKHR;
6889 break;
Rex Xu51596642016-09-21 18:56:12 +08006890 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006891 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006892 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006893 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006894 break;
6895 case glslang::EOpReadFirstInvocation:
6896 opCode = spv::OpSubgroupFirstInvocationKHR;
6897 break;
6898 case glslang::EOpBallot:
6899 {
6900 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6901 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6902 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6903 //
6904 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6905 //
6906 spv::Id uintType = builder.makeUintType(32);
6907 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6908 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6909
6910 std::vector<spv::Id> components;
6911 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6912 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6913
6914 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6915 return builder.createUnaryOp(spv::OpBitcast, typeId,
6916 builder.createCompositeConstruct(uvec2Type, components));
6917 }
6918
Rex Xu9d93a232016-05-05 12:30:44 +08006919 case glslang::EOpMinInvocations:
6920 case glslang::EOpMaxInvocations:
6921 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006922 case glslang::EOpMinInvocationsInclusiveScan:
6923 case glslang::EOpMaxInvocationsInclusiveScan:
6924 case glslang::EOpAddInvocationsInclusiveScan:
6925 case glslang::EOpMinInvocationsExclusiveScan:
6926 case glslang::EOpMaxInvocationsExclusiveScan:
6927 case glslang::EOpAddInvocationsExclusiveScan:
6928 if (op == glslang::EOpMinInvocations ||
6929 op == glslang::EOpMinInvocationsInclusiveScan ||
6930 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006931 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006932 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006933 else {
6934 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006935 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006936 else
Rex Xu51596642016-09-21 18:56:12 +08006937 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006938 }
Rex Xu430ef402016-10-14 17:22:23 +08006939 } else if (op == glslang::EOpMaxInvocations ||
6940 op == glslang::EOpMaxInvocationsInclusiveScan ||
6941 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006942 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006943 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006944 else {
6945 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006946 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006947 else
Rex Xu51596642016-09-21 18:56:12 +08006948 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006949 }
6950 } else {
6951 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006952 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006953 else
Rex Xu51596642016-09-21 18:56:12 +08006954 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006955 }
6956
Rex Xu2bbbe062016-08-23 15:41:05 +08006957 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006958 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006959
6960 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006961 case glslang::EOpMinInvocationsNonUniform:
6962 case glslang::EOpMaxInvocationsNonUniform:
6963 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006964 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6965 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6966 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6967 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6968 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6969 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6970 if (op == glslang::EOpMinInvocationsNonUniform ||
6971 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6972 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006973 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006974 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006975 else {
6976 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006977 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006978 else
Rex Xu51596642016-09-21 18:56:12 +08006979 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006980 }
6981 }
Rex Xu430ef402016-10-14 17:22:23 +08006982 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6983 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6984 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006985 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006986 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006987 else {
6988 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006989 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006990 else
Rex Xu51596642016-09-21 18:56:12 +08006991 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006992 }
6993 }
6994 else {
6995 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006996 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006997 else
Rex Xu51596642016-09-21 18:56:12 +08006998 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006999 }
7000
Rex Xu2bbbe062016-08-23 15:41:05 +08007001 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007002 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007003
7004 break;
John Kessenich91cef522016-05-05 16:45:40 -06007005 default:
7006 logger->missingFunctionality("invocation operation");
7007 return spv::NoResult;
7008 }
Rex Xu51596642016-09-21 18:56:12 +08007009
7010 assert(opCode != spv::OpNop);
7011 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06007012}
7013
Rex Xu2bbbe062016-08-23 15:41:05 +08007014// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06007015spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
7016 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08007017{
7018 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
7019 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08007020 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08007021 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07007022 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
7023 op == spv::OpGroupSMinNonUniformAMD ||
7024 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
7025 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08007026 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
7027
7028 // Handle group invocation operations scalar by scalar.
7029 // The result type is the same type as the original type.
7030 // The algorithm is to:
7031 // - break the vector into scalars
7032 // - apply the operation to each scalar
7033 // - make a vector out the scalar results
7034
7035 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08007036 int numComponents = builder.getNumComponents(operands[0]);
7037 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08007038 std::vector<spv::Id> results;
7039
7040 // do each scalar op
7041 for (int comp = 0; comp < numComponents; ++comp) {
7042 std::vector<unsigned int> indexes;
7043 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06007044 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
7045 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08007046 if (op == spv::OpSubgroupReadInvocationKHR) {
7047 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007048 spv::IdImmediate operand = { true, operands[1] };
7049 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08007050 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06007051 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7052 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08007053 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007054 spv::IdImmediate operand = { true, operands[1] };
7055 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08007056 } else {
John Kessenich149afc32018-08-14 13:31:43 -06007057 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7058 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06007059 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007060 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08007061 spvGroupOperands.push_back(scalar);
7062 }
Rex Xu2bbbe062016-08-23 15:41:05 +08007063
Rex Xub7072052016-09-26 15:53:40 +08007064 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08007065 }
7066
7067 // put the pieces together
7068 return builder.createCompositeConstruct(typeId, results);
7069}
Rex Xu2bbbe062016-08-23 15:41:05 +08007070
John Kessenich66011cb2018-03-06 16:12:04 -07007071// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06007072spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
7073 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07007074{
7075 // Add the required capabilities.
7076 switch (op) {
7077 case glslang::EOpSubgroupElect:
7078 builder.addCapability(spv::CapabilityGroupNonUniform);
7079 break;
7080 case glslang::EOpSubgroupAll:
7081 case glslang::EOpSubgroupAny:
7082 case glslang::EOpSubgroupAllEqual:
7083 builder.addCapability(spv::CapabilityGroupNonUniform);
7084 builder.addCapability(spv::CapabilityGroupNonUniformVote);
7085 break;
7086 case glslang::EOpSubgroupBroadcast:
7087 case glslang::EOpSubgroupBroadcastFirst:
7088 case glslang::EOpSubgroupBallot:
7089 case glslang::EOpSubgroupInverseBallot:
7090 case glslang::EOpSubgroupBallotBitExtract:
7091 case glslang::EOpSubgroupBallotBitCount:
7092 case glslang::EOpSubgroupBallotInclusiveBitCount:
7093 case glslang::EOpSubgroupBallotExclusiveBitCount:
7094 case glslang::EOpSubgroupBallotFindLSB:
7095 case glslang::EOpSubgroupBallotFindMSB:
7096 builder.addCapability(spv::CapabilityGroupNonUniform);
7097 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
7098 break;
7099 case glslang::EOpSubgroupShuffle:
7100 case glslang::EOpSubgroupShuffleXor:
7101 builder.addCapability(spv::CapabilityGroupNonUniform);
7102 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
7103 break;
7104 case glslang::EOpSubgroupShuffleUp:
7105 case glslang::EOpSubgroupShuffleDown:
7106 builder.addCapability(spv::CapabilityGroupNonUniform);
7107 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
7108 break;
7109 case glslang::EOpSubgroupAdd:
7110 case glslang::EOpSubgroupMul:
7111 case glslang::EOpSubgroupMin:
7112 case glslang::EOpSubgroupMax:
7113 case glslang::EOpSubgroupAnd:
7114 case glslang::EOpSubgroupOr:
7115 case glslang::EOpSubgroupXor:
7116 case glslang::EOpSubgroupInclusiveAdd:
7117 case glslang::EOpSubgroupInclusiveMul:
7118 case glslang::EOpSubgroupInclusiveMin:
7119 case glslang::EOpSubgroupInclusiveMax:
7120 case glslang::EOpSubgroupInclusiveAnd:
7121 case glslang::EOpSubgroupInclusiveOr:
7122 case glslang::EOpSubgroupInclusiveXor:
7123 case glslang::EOpSubgroupExclusiveAdd:
7124 case glslang::EOpSubgroupExclusiveMul:
7125 case glslang::EOpSubgroupExclusiveMin:
7126 case glslang::EOpSubgroupExclusiveMax:
7127 case glslang::EOpSubgroupExclusiveAnd:
7128 case glslang::EOpSubgroupExclusiveOr:
7129 case glslang::EOpSubgroupExclusiveXor:
7130 builder.addCapability(spv::CapabilityGroupNonUniform);
7131 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
7132 break;
7133 case glslang::EOpSubgroupClusteredAdd:
7134 case glslang::EOpSubgroupClusteredMul:
7135 case glslang::EOpSubgroupClusteredMin:
7136 case glslang::EOpSubgroupClusteredMax:
7137 case glslang::EOpSubgroupClusteredAnd:
7138 case glslang::EOpSubgroupClusteredOr:
7139 case glslang::EOpSubgroupClusteredXor:
7140 builder.addCapability(spv::CapabilityGroupNonUniform);
7141 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7142 break;
7143 case glslang::EOpSubgroupQuadBroadcast:
7144 case glslang::EOpSubgroupQuadSwapHorizontal:
7145 case glslang::EOpSubgroupQuadSwapVertical:
7146 case glslang::EOpSubgroupQuadSwapDiagonal:
7147 builder.addCapability(spv::CapabilityGroupNonUniform);
7148 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7149 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007150 case glslang::EOpSubgroupPartitionedAdd:
7151 case glslang::EOpSubgroupPartitionedMul:
7152 case glslang::EOpSubgroupPartitionedMin:
7153 case glslang::EOpSubgroupPartitionedMax:
7154 case glslang::EOpSubgroupPartitionedAnd:
7155 case glslang::EOpSubgroupPartitionedOr:
7156 case glslang::EOpSubgroupPartitionedXor:
7157 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7158 case glslang::EOpSubgroupPartitionedInclusiveMul:
7159 case glslang::EOpSubgroupPartitionedInclusiveMin:
7160 case glslang::EOpSubgroupPartitionedInclusiveMax:
7161 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7162 case glslang::EOpSubgroupPartitionedInclusiveOr:
7163 case glslang::EOpSubgroupPartitionedInclusiveXor:
7164 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7165 case glslang::EOpSubgroupPartitionedExclusiveMul:
7166 case glslang::EOpSubgroupPartitionedExclusiveMin:
7167 case glslang::EOpSubgroupPartitionedExclusiveMax:
7168 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7169 case glslang::EOpSubgroupPartitionedExclusiveOr:
7170 case glslang::EOpSubgroupPartitionedExclusiveXor:
7171 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7172 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7173 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007174 default: assert(0 && "Unhandled subgroup operation!");
7175 }
7176
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007177
7178 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7179 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007180 const bool isBool = typeProxy == glslang::EbtBool;
7181
7182 spv::Op opCode = spv::OpNop;
7183
7184 // Figure out which opcode to use.
7185 switch (op) {
7186 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7187 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7188 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7189 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7190 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7191 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7192 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7193 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7194 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7195 case glslang::EOpSubgroupBallotBitCount:
7196 case glslang::EOpSubgroupBallotInclusiveBitCount:
7197 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7198 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7199 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7200 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7201 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7202 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7203 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7204 case glslang::EOpSubgroupAdd:
7205 case glslang::EOpSubgroupInclusiveAdd:
7206 case glslang::EOpSubgroupExclusiveAdd:
7207 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007208 case glslang::EOpSubgroupPartitionedAdd:
7209 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7210 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007211 if (isFloat) {
7212 opCode = spv::OpGroupNonUniformFAdd;
7213 } else {
7214 opCode = spv::OpGroupNonUniformIAdd;
7215 }
7216 break;
7217 case glslang::EOpSubgroupMul:
7218 case glslang::EOpSubgroupInclusiveMul:
7219 case glslang::EOpSubgroupExclusiveMul:
7220 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007221 case glslang::EOpSubgroupPartitionedMul:
7222 case glslang::EOpSubgroupPartitionedInclusiveMul:
7223 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007224 if (isFloat) {
7225 opCode = spv::OpGroupNonUniformFMul;
7226 } else {
7227 opCode = spv::OpGroupNonUniformIMul;
7228 }
7229 break;
7230 case glslang::EOpSubgroupMin:
7231 case glslang::EOpSubgroupInclusiveMin:
7232 case glslang::EOpSubgroupExclusiveMin:
7233 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007234 case glslang::EOpSubgroupPartitionedMin:
7235 case glslang::EOpSubgroupPartitionedInclusiveMin:
7236 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007237 if (isFloat) {
7238 opCode = spv::OpGroupNonUniformFMin;
7239 } else if (isUnsigned) {
7240 opCode = spv::OpGroupNonUniformUMin;
7241 } else {
7242 opCode = spv::OpGroupNonUniformSMin;
7243 }
7244 break;
7245 case glslang::EOpSubgroupMax:
7246 case glslang::EOpSubgroupInclusiveMax:
7247 case glslang::EOpSubgroupExclusiveMax:
7248 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007249 case glslang::EOpSubgroupPartitionedMax:
7250 case glslang::EOpSubgroupPartitionedInclusiveMax:
7251 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007252 if (isFloat) {
7253 opCode = spv::OpGroupNonUniformFMax;
7254 } else if (isUnsigned) {
7255 opCode = spv::OpGroupNonUniformUMax;
7256 } else {
7257 opCode = spv::OpGroupNonUniformSMax;
7258 }
7259 break;
7260 case glslang::EOpSubgroupAnd:
7261 case glslang::EOpSubgroupInclusiveAnd:
7262 case glslang::EOpSubgroupExclusiveAnd:
7263 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007264 case glslang::EOpSubgroupPartitionedAnd:
7265 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7266 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007267 if (isBool) {
7268 opCode = spv::OpGroupNonUniformLogicalAnd;
7269 } else {
7270 opCode = spv::OpGroupNonUniformBitwiseAnd;
7271 }
7272 break;
7273 case glslang::EOpSubgroupOr:
7274 case glslang::EOpSubgroupInclusiveOr:
7275 case glslang::EOpSubgroupExclusiveOr:
7276 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007277 case glslang::EOpSubgroupPartitionedOr:
7278 case glslang::EOpSubgroupPartitionedInclusiveOr:
7279 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007280 if (isBool) {
7281 opCode = spv::OpGroupNonUniformLogicalOr;
7282 } else {
7283 opCode = spv::OpGroupNonUniformBitwiseOr;
7284 }
7285 break;
7286 case glslang::EOpSubgroupXor:
7287 case glslang::EOpSubgroupInclusiveXor:
7288 case glslang::EOpSubgroupExclusiveXor:
7289 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007290 case glslang::EOpSubgroupPartitionedXor:
7291 case glslang::EOpSubgroupPartitionedInclusiveXor:
7292 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007293 if (isBool) {
7294 opCode = spv::OpGroupNonUniformLogicalXor;
7295 } else {
7296 opCode = spv::OpGroupNonUniformBitwiseXor;
7297 }
7298 break;
7299 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7300 case glslang::EOpSubgroupQuadSwapHorizontal:
7301 case glslang::EOpSubgroupQuadSwapVertical:
7302 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7303 default: assert(0 && "Unhandled subgroup operation!");
7304 }
7305
John Kessenich149afc32018-08-14 13:31:43 -06007306 // get the right Group Operation
7307 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007308 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007309 default:
7310 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007311 case glslang::EOpSubgroupBallotBitCount:
7312 case glslang::EOpSubgroupAdd:
7313 case glslang::EOpSubgroupMul:
7314 case glslang::EOpSubgroupMin:
7315 case glslang::EOpSubgroupMax:
7316 case glslang::EOpSubgroupAnd:
7317 case glslang::EOpSubgroupOr:
7318 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007319 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007320 break;
7321 case glslang::EOpSubgroupBallotInclusiveBitCount:
7322 case glslang::EOpSubgroupInclusiveAdd:
7323 case glslang::EOpSubgroupInclusiveMul:
7324 case glslang::EOpSubgroupInclusiveMin:
7325 case glslang::EOpSubgroupInclusiveMax:
7326 case glslang::EOpSubgroupInclusiveAnd:
7327 case glslang::EOpSubgroupInclusiveOr:
7328 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007329 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007330 break;
7331 case glslang::EOpSubgroupBallotExclusiveBitCount:
7332 case glslang::EOpSubgroupExclusiveAdd:
7333 case glslang::EOpSubgroupExclusiveMul:
7334 case glslang::EOpSubgroupExclusiveMin:
7335 case glslang::EOpSubgroupExclusiveMax:
7336 case glslang::EOpSubgroupExclusiveAnd:
7337 case glslang::EOpSubgroupExclusiveOr:
7338 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007339 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007340 break;
7341 case glslang::EOpSubgroupClusteredAdd:
7342 case glslang::EOpSubgroupClusteredMul:
7343 case glslang::EOpSubgroupClusteredMin:
7344 case glslang::EOpSubgroupClusteredMax:
7345 case glslang::EOpSubgroupClusteredAnd:
7346 case glslang::EOpSubgroupClusteredOr:
7347 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007348 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007349 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007350 case glslang::EOpSubgroupPartitionedAdd:
7351 case glslang::EOpSubgroupPartitionedMul:
7352 case glslang::EOpSubgroupPartitionedMin:
7353 case glslang::EOpSubgroupPartitionedMax:
7354 case glslang::EOpSubgroupPartitionedAnd:
7355 case glslang::EOpSubgroupPartitionedOr:
7356 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007357 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007358 break;
7359 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7360 case glslang::EOpSubgroupPartitionedInclusiveMul:
7361 case glslang::EOpSubgroupPartitionedInclusiveMin:
7362 case glslang::EOpSubgroupPartitionedInclusiveMax:
7363 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7364 case glslang::EOpSubgroupPartitionedInclusiveOr:
7365 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007366 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007367 break;
7368 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7369 case glslang::EOpSubgroupPartitionedExclusiveMul:
7370 case glslang::EOpSubgroupPartitionedExclusiveMin:
7371 case glslang::EOpSubgroupPartitionedExclusiveMax:
7372 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7373 case glslang::EOpSubgroupPartitionedExclusiveOr:
7374 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007375 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007376 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007377 }
7378
John Kessenich149afc32018-08-14 13:31:43 -06007379 // build the instruction
7380 std::vector<spv::IdImmediate> spvGroupOperands;
7381
7382 // Every operation begins with the Execution Scope operand.
7383 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7384 spvGroupOperands.push_back(executionScope);
7385
7386 // Next, for all operations that use a Group Operation, push that as an operand.
7387 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007388 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007389 spvGroupOperands.push_back(groupOperand);
7390 }
7391
John Kessenich66011cb2018-03-06 16:12:04 -07007392 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007393 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7394 spv::IdImmediate operand = { true, *opIt };
7395 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007396 }
7397
7398 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007399 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007400 switch (op) {
7401 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007402 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7403 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7404 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7405 }
7406 if (directionId != spv::NoResult) {
7407 spv::IdImmediate direction = { true, directionId };
7408 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007409 }
7410
7411 return builder.createOp(opCode, typeId, spvGroupOperands);
7412}
7413
John Kessenich8985fc92020-03-03 10:25:07 -07007414spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7415 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007416{
John Kessenich66011cb2018-03-06 16:12:04 -07007417 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7418 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007419
John Kessenich140f3df2015-06-26 16:58:36 -06007420 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007421 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007422 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007423 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007424 spv::Id typeId0 = 0;
7425 if (consumedOperands > 0)
7426 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007427 spv::Id typeId1 = 0;
7428 if (consumedOperands > 1)
7429 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007430 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007431
7432 switch (op) {
7433 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007434 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007435 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007436 else if (isUnsigned)
7437 libCall = spv::GLSLstd450UMin;
7438 else
7439 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007440 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007441 break;
7442 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007443 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007444 break;
7445 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007446 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007447 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007448 else if (isUnsigned)
7449 libCall = spv::GLSLstd450UMax;
7450 else
7451 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007452 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007453 break;
7454 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007455 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007456 break;
7457 case glslang::EOpDot:
7458 opCode = spv::OpDot;
7459 break;
7460 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007461 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007462 break;
7463
7464 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007465 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007466 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007467 else if (isUnsigned)
7468 libCall = spv::GLSLstd450UClamp;
7469 else
7470 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007471 builder.promoteScalar(precision, operands.front(), operands[1]);
7472 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007473 break;
7474 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007475 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7476 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007477 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007478 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007479 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007480 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007481 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007482 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007483 break;
7484 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007485 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007486 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007487 break;
7488 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007489 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007490 builder.promoteScalar(precision, operands[0], operands[2]);
7491 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007492 break;
7493
7494 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007495 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007496 break;
7497 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007498 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007499 break;
7500 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007501 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007502 break;
7503 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007504 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007505 break;
7506 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007507 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007508 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007509 case glslang::EOpBarrier:
7510 {
7511 // This is for the extended controlBarrier function, with four operands.
7512 // The unextended barrier() goes through createNoArgOperation.
7513 assert(operands.size() == 4);
7514 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7515 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7516 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007517 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7518 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007519 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7520 spv::MemorySemanticsMakeVisibleKHRMask |
7521 spv::MemorySemanticsOutputMemoryKHRMask |
7522 spv::MemorySemanticsVolatileMask)) {
7523 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7524 }
John Kessenich8985fc92020-03-03 10:25:07 -07007525 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7526 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007527 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7528 }
7529 return 0;
7530 }
7531 break;
7532 case glslang::EOpMemoryBarrier:
7533 {
7534 // This is for the extended memoryBarrier function, with three operands.
7535 // The unextended memoryBarrier() goes through createNoArgOperation.
7536 assert(operands.size() == 3);
7537 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7538 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7539 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7540 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7541 spv::MemorySemanticsMakeVisibleKHRMask |
7542 spv::MemorySemanticsOutputMemoryKHRMask |
7543 spv::MemorySemanticsVolatileMask)) {
7544 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7545 }
7546 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7547 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7548 }
7549 return 0;
7550 }
7551 break;
7552
John Kessenicha28f7a72019-08-06 07:00:58 -06007553#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007554 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007555 if (typeProxy == glslang::EbtFloat16)
7556 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007557 libCall = spv::GLSLstd450InterpolateAtSample;
7558 break;
7559 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007560 if (typeProxy == glslang::EbtFloat16)
7561 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007562 libCall = spv::GLSLstd450InterpolateAtOffset;
7563 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007564 case glslang::EOpAddCarry:
7565 opCode = spv::OpIAddCarry;
7566 typeId = builder.makeStructResultType(typeId0, typeId0);
7567 consumedOperands = 2;
7568 break;
7569 case glslang::EOpSubBorrow:
7570 opCode = spv::OpISubBorrow;
7571 typeId = builder.makeStructResultType(typeId0, typeId0);
7572 consumedOperands = 2;
7573 break;
7574 case glslang::EOpUMulExtended:
7575 opCode = spv::OpUMulExtended;
7576 typeId = builder.makeStructResultType(typeId0, typeId0);
7577 consumedOperands = 2;
7578 break;
7579 case glslang::EOpIMulExtended:
7580 opCode = spv::OpSMulExtended;
7581 typeId = builder.makeStructResultType(typeId0, typeId0);
7582 consumedOperands = 2;
7583 break;
7584 case glslang::EOpBitfieldExtract:
7585 if (isUnsigned)
7586 opCode = spv::OpBitFieldUExtract;
7587 else
7588 opCode = spv::OpBitFieldSExtract;
7589 break;
7590 case glslang::EOpBitfieldInsert:
7591 opCode = spv::OpBitFieldInsert;
7592 break;
7593
7594 case glslang::EOpFma:
7595 libCall = spv::GLSLstd450Fma;
7596 break;
7597 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007598 {
7599 libCall = spv::GLSLstd450FrexpStruct;
7600 assert(builder.isPointerType(typeId1));
7601 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007602 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007603 if (width == 16)
7604 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7605 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007606 if (builder.getNumComponents(operands[0]) == 1)
7607 frexpIntType = builder.makeIntegerType(width, true);
7608 else
John Kessenich8985fc92020-03-03 10:25:07 -07007609 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7610 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007611 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7612 consumedOperands = 1;
7613 }
John Kessenich55e7d112015-11-15 21:33:39 -07007614 break;
7615 case glslang::EOpLdexp:
7616 libCall = spv::GLSLstd450Ldexp;
7617 break;
7618
Rex Xu574ab042016-04-14 16:53:07 +08007619 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007620 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007621
John Kessenich66011cb2018-03-06 16:12:04 -07007622 case glslang::EOpSubgroupBroadcast:
7623 case glslang::EOpSubgroupBallotBitExtract:
7624 case glslang::EOpSubgroupShuffle:
7625 case glslang::EOpSubgroupShuffleXor:
7626 case glslang::EOpSubgroupShuffleUp:
7627 case glslang::EOpSubgroupShuffleDown:
7628 case glslang::EOpSubgroupClusteredAdd:
7629 case glslang::EOpSubgroupClusteredMul:
7630 case glslang::EOpSubgroupClusteredMin:
7631 case glslang::EOpSubgroupClusteredMax:
7632 case glslang::EOpSubgroupClusteredAnd:
7633 case glslang::EOpSubgroupClusteredOr:
7634 case glslang::EOpSubgroupClusteredXor:
7635 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007636 case glslang::EOpSubgroupPartitionedAdd:
7637 case glslang::EOpSubgroupPartitionedMul:
7638 case glslang::EOpSubgroupPartitionedMin:
7639 case glslang::EOpSubgroupPartitionedMax:
7640 case glslang::EOpSubgroupPartitionedAnd:
7641 case glslang::EOpSubgroupPartitionedOr:
7642 case glslang::EOpSubgroupPartitionedXor:
7643 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7644 case glslang::EOpSubgroupPartitionedInclusiveMul:
7645 case glslang::EOpSubgroupPartitionedInclusiveMin:
7646 case glslang::EOpSubgroupPartitionedInclusiveMax:
7647 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7648 case glslang::EOpSubgroupPartitionedInclusiveOr:
7649 case glslang::EOpSubgroupPartitionedInclusiveXor:
7650 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7651 case glslang::EOpSubgroupPartitionedExclusiveMul:
7652 case glslang::EOpSubgroupPartitionedExclusiveMin:
7653 case glslang::EOpSubgroupPartitionedExclusiveMax:
7654 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7655 case glslang::EOpSubgroupPartitionedExclusiveOr:
7656 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007657 return createSubgroupOperation(op, typeId, operands, typeProxy);
7658
Rex Xu9d93a232016-05-05 12:30:44 +08007659 case glslang::EOpSwizzleInvocations:
7660 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7661 libCall = spv::SwizzleInvocationsAMD;
7662 break;
7663 case glslang::EOpSwizzleInvocationsMasked:
7664 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7665 libCall = spv::SwizzleInvocationsMaskedAMD;
7666 break;
7667 case glslang::EOpWriteInvocation:
7668 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7669 libCall = spv::WriteInvocationAMD;
7670 break;
7671
7672 case glslang::EOpMin3:
7673 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7674 if (isFloat)
7675 libCall = spv::FMin3AMD;
7676 else {
7677 if (isUnsigned)
7678 libCall = spv::UMin3AMD;
7679 else
7680 libCall = spv::SMin3AMD;
7681 }
7682 break;
7683 case glslang::EOpMax3:
7684 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7685 if (isFloat)
7686 libCall = spv::FMax3AMD;
7687 else {
7688 if (isUnsigned)
7689 libCall = spv::UMax3AMD;
7690 else
7691 libCall = spv::SMax3AMD;
7692 }
7693 break;
7694 case glslang::EOpMid3:
7695 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7696 if (isFloat)
7697 libCall = spv::FMid3AMD;
7698 else {
7699 if (isUnsigned)
7700 libCall = spv::UMid3AMD;
7701 else
7702 libCall = spv::SMid3AMD;
7703 }
7704 break;
7705
7706 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007707 if (typeProxy == glslang::EbtFloat16)
7708 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007709 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7710 libCall = spv::InterpolateAtVertexAMD;
7711 break;
Chao Chen3c366992018-09-19 11:41:59 -07007712
Daniel Kochdb32b242020-03-17 20:42:47 -04007713 case glslang::EOpReportIntersection:
Chao Chenb50c02e2018-09-19 11:42:24 -07007714 typeId = builder.makeBoolType();
Daniel Kochdb32b242020-03-17 20:42:47 -04007715 opCode = spv::OpReportIntersectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007716 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04007717 case glslang::EOpTrace:
Daniel Kochdb32b242020-03-17 20:42:47 -04007718 builder.createNoResultOp(spv::OpTraceRayKHR, operands);
Ashwin Leleff1783d2018-10-22 16:41:44 -07007719 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04007720 case glslang::EOpExecuteCallable:
Daniel Kochdb32b242020-03-17 20:42:47 -04007721 builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007722 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007723
7724 case glslang::EOpRayQueryInitialize:
Torosdagli06c2eee2020-03-19 11:09:57 -04007725 builder.createNoResultOp(spv::OpRayQueryInitializeKHR, operands);
7726 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007727 case glslang::EOpRayQueryTerminate:
Torosdagli06c2eee2020-03-19 11:09:57 -04007728 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operands);
7729 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007730 case glslang::EOpRayQueryGenerateIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007731 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR, operands);
7732 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007733 case glslang::EOpRayQueryConfirmIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007734 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operands);
7735 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007736 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04007737 typeId = builder.makeBoolType();
7738 opCode = spv::OpRayQueryProceedKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007739 break;
7740 case glslang::EOpRayQueryGetIntersectionType:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007741 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007742 opCode = spv::OpRayQueryGetIntersectionTypeKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007743 break;
7744 case glslang::EOpRayQueryGetRayTMin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007745 typeId = builder.makeFloatType(32);
7746 opCode = spv::OpRayQueryGetRayTMinKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007747 break;
7748 case glslang::EOpRayQueryGetRayFlags:
Torosdagli06c2eee2020-03-19 11:09:57 -04007749 typeId = builder.makeIntType(32);
7750 opCode = spv::OpRayQueryGetRayFlagsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007751 break;
7752 case glslang::EOpRayQueryGetIntersectionT:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007753 typeId = builder.makeFloatType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007754 opCode = spv::OpRayQueryGetIntersectionTKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007755 break;
7756 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007757 typeId = builder.makeIntType(32);
7758 opCode = spv::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007759 break;
7760 case glslang::EOpRayQueryGetIntersectionInstanceId:
Torosdagli06c2eee2020-03-19 11:09:57 -04007761 typeId = builder.makeIntType(32);
7762 opCode = spv::OpRayQueryGetIntersectionInstanceIdKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007763 break;
7764 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
Torosdagli06c2eee2020-03-19 11:09:57 -04007765 typeId = builder.makeIntType(32);
7766 opCode = spv::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007767 break;
7768 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007769 typeId = builder.makeIntType(32);
7770 opCode = spv::OpRayQueryGetIntersectionGeometryIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007771 break;
7772 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007773 typeId = builder.makeIntType(32);
7774 opCode = spv::OpRayQueryGetIntersectionPrimitiveIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007775 break;
7776 case glslang::EOpRayQueryGetIntersectionBarycentrics:
Torosdagli06c2eee2020-03-19 11:09:57 -04007777 typeId = builder.makeVectorType(builder.makeFloatType(32), 2);
7778 opCode = spv::OpRayQueryGetIntersectionBarycentricsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007779 break;
7780 case glslang::EOpRayQueryGetIntersectionFrontFace:
Torosdagli06c2eee2020-03-19 11:09:57 -04007781 typeId = builder.makeBoolType();
7782 opCode = spv::OpRayQueryGetIntersectionFrontFaceKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007783 break;
7784 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
Torosdagli06c2eee2020-03-19 11:09:57 -04007785 typeId = builder.makeBoolType();
7786 opCode = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007787 break;
7788 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007789 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7790 opCode = spv::OpRayQueryGetIntersectionObjectRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007791 break;
7792 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007793 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7794 opCode = spv::OpRayQueryGetIntersectionObjectRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007795 break;
7796 case glslang::EOpRayQueryGetWorldRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007797 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7798 opCode = spv::OpRayQueryGetWorldRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007799 break;
7800 case glslang::EOpRayQueryGetWorldRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007801 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7802 opCode = spv::OpRayQueryGetWorldRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007803 break;
7804 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
Torosdagli06c2eee2020-03-19 11:09:57 -04007805 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007806 opCode = spv::OpRayQueryGetIntersectionObjectToWorldKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007807 break;
7808 case glslang::EOpRayQueryGetIntersectionWorldToObject:
Torosdagli06c2eee2020-03-19 11:09:57 -04007809 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007810 opCode = spv::OpRayQueryGetIntersectionWorldToObjectKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007811 break;
Chao Chen3c366992018-09-19 11:41:59 -07007812 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7813 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7814 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007815 case glslang::EOpCooperativeMatrixMulAdd:
7816 opCode = spv::OpCooperativeMatrixMulAddNV;
7817 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007818#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007819 default:
7820 return 0;
7821 }
7822
7823 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007824 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007825 // Use an extended instruction from the standard library.
7826 // Construct the call arguments, without modifying the original operands vector.
7827 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7828 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007829 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007830 } else if (opCode == spv::OpDot && !isFloat) {
7831 // int dot(int, int)
7832 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7833 const int componentCount = builder.getNumComponents(operands[0]);
7834 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7835 builder.setPrecision(mulOp, precision);
7836 id = builder.createCompositeExtract(mulOp, typeId, 0);
7837 for (int i = 1; i < componentCount; ++i) {
7838 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07007839 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01007840 }
John Kessenich2359bd02015-12-06 19:29:11 -07007841 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007842 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007843 case 0:
7844 // should all be handled by visitAggregate and createNoArgOperation
7845 assert(0);
7846 return 0;
7847 case 1:
7848 // should all be handled by createUnaryOperation
7849 assert(0);
7850 return 0;
7851 case 2:
7852 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7853 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007854 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007855 // anything 3 or over doesn't have l-value operands, so all should be consumed
7856 assert(consumedOperands == operands.size());
7857 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007858 break;
7859 }
7860 }
7861
John Kessenichb9197c82019-08-11 07:41:45 -06007862#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007863 // Decode the return types that were structures
7864 switch (op) {
7865 case glslang::EOpAddCarry:
7866 case glslang::EOpSubBorrow:
7867 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7868 id = builder.createCompositeExtract(id, typeId0, 0);
7869 break;
7870 case glslang::EOpUMulExtended:
7871 case glslang::EOpIMulExtended:
7872 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7873 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7874 break;
7875 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007876 {
7877 assert(operands.size() == 2);
7878 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7879 // "exp" is floating-point type (from HLSL intrinsic)
7880 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7881 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7882 builder.createStore(member1, operands[1]);
7883 } else
7884 // "exp" is integer type (from GLSL built-in function)
7885 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7886 id = builder.createCompositeExtract(id, typeId0, 0);
7887 }
John Kessenich55e7d112015-11-15 21:33:39 -07007888 break;
7889 default:
7890 break;
7891 }
John Kessenichb9197c82019-08-11 07:41:45 -06007892#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007893
John Kessenich32cfd492016-02-02 12:37:46 -07007894 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007895}
7896
Rex Xu9d93a232016-05-05 12:30:44 +08007897// Intrinsics with no arguments (or no return value, and no precision).
7898spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007899{
Jeff Bolz36831c92018-09-05 10:11:41 -05007900 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07007901 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
7902 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007903
7904 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007905 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007906 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007907 if (glslangIntermediate->usingVulkanMemoryModel()) {
7908 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7909 spv::MemorySemanticsOutputMemoryKHRMask |
7910 spv::MemorySemanticsAcquireReleaseMask);
7911 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7912 } else {
7913 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7914 }
John Kessenich82979362017-12-11 04:02:24 -07007915 } else {
7916 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7917 spv::MemorySemanticsWorkgroupMemoryMask |
7918 spv::MemorySemanticsAcquireReleaseMask);
7919 }
John Kessenich140f3df2015-06-26 16:58:36 -06007920 return 0;
7921 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007922 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7923 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007924 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007925 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007926 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7927 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007928 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007929 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007930 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7931 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007932 return 0;
7933 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007934 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7935 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007936 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007937#ifndef GLSLANG_WEB
7938 case glslang::EOpMemoryBarrierAtomicCounter:
7939 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7940 spv::MemorySemanticsAcquireReleaseMask);
7941 return 0;
7942 case glslang::EOpMemoryBarrierImage:
7943 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7944 spv::MemorySemanticsAcquireReleaseMask);
7945 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007946 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007947 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007948 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007949 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007950 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007951 case glslang::EOpDeviceMemoryBarrier:
7952 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7953 spv::MemorySemanticsImageMemoryMask |
7954 spv::MemorySemanticsAcquireReleaseMask);
7955 return 0;
7956 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7957 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7958 spv::MemorySemanticsImageMemoryMask |
7959 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007960 return 0;
7961 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007962 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7963 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007964 return 0;
7965 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007966 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7967 spv::MemorySemanticsWorkgroupMemoryMask |
7968 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007969 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007970 case glslang::EOpSubgroupBarrier:
7971 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7972 spv::MemorySemanticsAcquireReleaseMask);
7973 return spv::NoResult;
7974 case glslang::EOpSubgroupMemoryBarrier:
7975 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7976 spv::MemorySemanticsAcquireReleaseMask);
7977 return spv::NoResult;
7978 case glslang::EOpSubgroupMemoryBarrierBuffer:
7979 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7980 spv::MemorySemanticsAcquireReleaseMask);
7981 return spv::NoResult;
7982 case glslang::EOpSubgroupMemoryBarrierImage:
7983 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7984 spv::MemorySemanticsAcquireReleaseMask);
7985 return spv::NoResult;
7986 case glslang::EOpSubgroupMemoryBarrierShared:
7987 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7988 spv::MemorySemanticsAcquireReleaseMask);
7989 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06007990
7991 case glslang::EOpEmitVertex:
7992 builder.createNoResultOp(spv::OpEmitVertex);
7993 return 0;
7994 case glslang::EOpEndPrimitive:
7995 builder.createNoResultOp(spv::OpEndPrimitive);
7996 return 0;
7997
John Kessenich66011cb2018-03-06 16:12:04 -07007998 case glslang::EOpSubgroupElect: {
7999 std::vector<spv::Id> operands;
8000 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
8001 }
Rex Xu9d93a232016-05-05 12:30:44 +08008002 case glslang::EOpTime:
8003 {
8004 std::vector<spv::Id> args; // Dummy arguments
8005 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
8006 return builder.setPrecision(id, precision);
8007 }
Daniel Kochdb32b242020-03-17 20:42:47 -04008008 case glslang::EOpIgnoreIntersection:
8009 builder.createNoResultOp(spv::OpIgnoreIntersectionKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008010 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04008011 case glslang::EOpTerminateRay:
8012 builder.createNoResultOp(spv::OpTerminateRayKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008013 return 0;
Torosdagli06c2eee2020-03-19 11:09:57 -04008014 case glslang::EOpRayQueryInitialize:
8015 builder.createNoResultOp(spv::OpRayQueryInitializeKHR);
8016 return 0;
8017 case glslang::EOpRayQueryTerminate:
8018 builder.createNoResultOp(spv::OpRayQueryTerminateKHR);
8019 return 0;
8020 case glslang::EOpRayQueryGenerateIntersection:
8021 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR);
8022 return 0;
8023 case glslang::EOpRayQueryConfirmIntersection:
8024 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR);
8025 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05008026 case glslang::EOpBeginInvocationInterlock:
8027 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
8028 return 0;
8029 case glslang::EOpEndInvocationInterlock:
8030 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
8031 return 0;
8032
Jeff Bolzba6170b2019-07-01 09:23:23 -05008033 case glslang::EOpIsHelperInvocation:
8034 {
8035 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08008036 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
8037 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
8038 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05008039 }
8040
amhagan91fb0092019-07-10 21:14:38 -04008041 case glslang::EOpReadClockSubgroupKHR: {
8042 std::vector<spv::Id> args;
8043 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
8044 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8045 builder.addCapability(spv::CapabilityShaderClockKHR);
8046 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8047 }
8048
8049 case glslang::EOpReadClockDeviceKHR: {
8050 std::vector<spv::Id> args;
8051 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
8052 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8053 builder.addCapability(spv::CapabilityShaderClockKHR);
8054 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8055 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06008056#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008057 default:
John Kessenich155d3512019-08-08 23:29:20 -06008058 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008059 }
John Kessenich155d3512019-08-08 23:29:20 -06008060
8061 logger->missingFunctionality("unknown operation with no arguments");
8062
8063 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008064}
8065
8066spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
8067{
John Kessenich2f273362015-07-18 22:34:27 -06008068 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06008069 spv::Id id;
8070 if (symbolValues.end() != iter) {
8071 id = iter->second;
8072 return id;
8073 }
8074
8075 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06008076 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
Daniel Kochdb32b242020-03-17 20:42:47 -04008077 auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06008078 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06008079 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06008080 if (forcedType.second != spv::NoType)
8081 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06008082
Rex Xuc884b4a2016-06-29 15:03:44 +08008083 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008084 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
8085 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
8086 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06008087#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008088 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06008089 if (symbol->getQualifier().hasComponent())
8090 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
8091 if (symbol->getQualifier().hasIndex())
8092 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07008093#endif
John Kessenich6c292d32016-02-15 20:58:50 -07008094 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07008095 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06008096 // atomic counters use this:
8097 if (symbol->getQualifier().hasOffset())
8098 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008099 }
8100
scygan2c864272016-05-18 18:09:17 +02008101 if (symbol->getQualifier().hasLocation())
8102 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07008103 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07008104 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07008105 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06008106 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07008107 }
John Kessenich140f3df2015-06-26 16:58:36 -06008108 if (symbol->getQualifier().hasSet())
8109 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07008110 else if (IsDescriptorResource(symbol->getType())) {
8111 // default to 0
8112 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
8113 }
John Kessenich140f3df2015-06-26 16:58:36 -06008114 if (symbol->getQualifier().hasBinding())
8115 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06008116 else if (IsDescriptorResource(symbol->getType())) {
8117 // default to 0
8118 builder.addDecoration(id, spv::DecorationBinding, 0);
8119 }
John Kessenich6c292d32016-02-15 20:58:50 -07008120 if (symbol->getQualifier().hasAttachment())
8121 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06008122 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07008123 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07008124 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008125 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07008126 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
8127 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
8128 builder.addDecoration(id, spv::DecorationXfbStride, stride);
8129 }
8130 if (symbol->getQualifier().hasXfbOffset())
8131 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008132 }
8133
John Kessenichb9197c82019-08-11 07:41:45 -06008134 // add built-in variable decoration
8135 if (builtIn != spv::BuiltInMax) {
8136 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
8137 }
8138
8139#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08008140 if (symbol->getType().isImage()) {
8141 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07008142 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
8143 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08008144 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07008145 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08008146 }
8147
John Kessenich5611c6d2018-04-05 11:25:02 -06008148 // nonuniform
8149 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
8150
chaoc0ad6a4e2016-12-19 16:29:34 -08008151 if (builtIn == spv::BuiltInSampleMask) {
8152 spv::Decoration decoration;
8153 // GL_NV_sample_mask_override_coverage extension
8154 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08008155 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08008156 else
8157 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07008158 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08008159 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07008160 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08008161 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
8162 }
8163 }
chaoc771d89f2017-01-13 01:10:53 -08008164 else if (builtIn == spv::BuiltInLayer) {
8165 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06008166 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008167 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08008168 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
8169 builder.addExtension(spv::E_SPV_NV_viewport_array2);
8170 }
John Kessenichb41bff62017-08-11 13:07:17 -06008171 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008172 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
8173 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08008174 builder.addCapability(spv::CapabilityShaderStereoViewNV);
8175 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
8176 }
8177 }
8178
chaoc6e5acae2016-12-20 13:28:52 -08008179 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008180 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08008181 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08008182 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
8183 }
Chao Chen9eada4b2018-09-19 11:39:56 -07008184 if (symbol->getQualifier().pervertexNV) {
8185 builder.addDecoration(id, spv::DecorationPerVertexNV);
8186 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
8187 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
8188 }
chaoc0ad6a4e2016-12-19 16:29:34 -08008189
John Kessenich5d610ee2018-03-07 18:05:55 -07008190 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
8191 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
8192 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
8193 symbol->getType().getQualifier().semanticName);
8194 }
8195
John Kessenich7015bd62019-08-01 03:28:08 -06008196 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07008197 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
8198 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008199 }
John Kessenichb9197c82019-08-11 07:41:45 -06008200#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008201
John Kessenich140f3df2015-06-26 16:58:36 -06008202 return id;
8203}
8204
John Kessenicha28f7a72019-08-06 07:00:58 -06008205#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008206// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
8207void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
8208{
8209 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07008210 if (qualifier.perPrimitiveNV) {
8211 // Need to add capability/extension for fragment shader.
8212 // Mesh shader already adds this by default.
8213 if (glslangIntermediate->getStage() == EShLangFragment) {
8214 builder.addCapability(spv::CapabilityMeshShadingNV);
8215 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8216 }
Chao Chen3c366992018-09-19 11:41:59 -07008217 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008218 }
Chao Chen3c366992018-09-19 11:41:59 -07008219 if (qualifier.perViewNV)
8220 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
8221 if (qualifier.perTaskNV)
8222 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
8223 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07008224 if (qualifier.perPrimitiveNV) {
8225 // Need to add capability/extension for fragment shader.
8226 // Mesh shader already adds this by default.
8227 if (glslangIntermediate->getStage() == EShLangFragment) {
8228 builder.addCapability(spv::CapabilityMeshShadingNV);
8229 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8230 }
Chao Chen3c366992018-09-19 11:41:59 -07008231 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008232 }
Chao Chen3c366992018-09-19 11:41:59 -07008233 if (qualifier.perViewNV)
8234 builder.addDecoration(id, spv::DecorationPerViewNV);
8235 if (qualifier.perTaskNV)
8236 builder.addDecoration(id, spv::DecorationPerTaskNV);
8237 }
8238}
8239#endif
8240
John Kessenich55e7d112015-11-15 21:33:39 -07008241// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008242// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008243//
8244// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8245//
8246// Recursively walk the nodes. The nodes form a tree whose leaves are
8247// regular constants, which themselves are trees that createSpvConstant()
8248// recursively walks. So, this function walks the "top" of the tree:
8249// - emit specialization constant-building instructions for specConstant
8250// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008251spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008252{
John Kessenich7cc0e282016-03-20 00:46:02 -06008253 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008254
qining4f4bb812016-04-03 23:55:17 -04008255 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008256 if (! node.getQualifier().specConstant) {
8257 // hand off to the non-spec-constant path
8258 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8259 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008260 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8261 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8262 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008263 }
8264
8265 // We now know we have a specialization constant to build
8266
John Kessenichd94c0032016-05-30 19:29:40 -06008267 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008268 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8269 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8270 std::vector<spv::Id> dimConstId;
8271 for (int dim = 0; dim < 3; ++dim) {
8272 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8273 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008274 if (specConst) {
8275 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8276 glslangIntermediate->getLocalSizeSpecId(dim));
8277 }
qining4f4bb812016-04-03 23:55:17 -04008278 }
8279 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8280 }
8281
8282 // An AST node labelled as specialization constant should be a symbol node.
8283 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8284 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008285 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008286 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008287 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8288 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8289 // will set the builder into spec constant op instruction generating mode.
8290 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008291 result = accessChainLoad(sub_tree->getType());
8292 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008293 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008294 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008295 } else {
8296 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008297 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008298 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008299 builder.addName(result, sn->getName().c_str());
8300 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008301 }
qining4f4bb812016-04-03 23:55:17 -04008302
8303 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8304 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008305 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008306 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008307}
8308
John Kessenich140f3df2015-06-26 16:58:36 -06008309// Use 'consts' as the flattened glslang source of scalar constants to recursively
8310// build the aggregate SPIR-V constant.
8311//
8312// If there are not enough elements present in 'consts', 0 will be substituted;
8313// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8314//
John Kessenich8985fc92020-03-03 10:25:07 -07008315spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8316 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008317{
8318 // vector of constants for SPIR-V
8319 std::vector<spv::Id> spvConsts;
8320
8321 // Type is used for struct and array constants
8322 spv::Id typeId = convertGlslangToSpvType(glslangType);
8323
8324 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008325 glslang::TType elementType(glslangType, 0);
8326 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008327 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008328 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008329 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008330 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008331 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008332 } else if (glslangType.isCoopMat()) {
8333 glslang::TType componentType(glslangType.getBasicType());
8334 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008335 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008336 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8337 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008338 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008339 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008340 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8341 bool zero = nextConst >= consts.size();
8342 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008343 case glslang::EbtInt:
8344 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8345 break;
8346 case glslang::EbtUint:
8347 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8348 break;
8349 case glslang::EbtFloat:
8350 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8351 break;
8352 case glslang::EbtBool:
8353 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8354 break;
8355#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008356 case glslang::EbtInt8:
8357 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8358 break;
8359 case glslang::EbtUint8:
8360 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8361 break;
8362 case glslang::EbtInt16:
8363 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8364 break;
8365 case glslang::EbtUint16:
8366 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8367 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008368 case glslang::EbtInt64:
8369 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8370 break;
8371 case glslang::EbtUint64:
8372 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8373 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008374 case glslang::EbtDouble:
8375 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8376 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008377 case glslang::EbtFloat16:
8378 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8379 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008380#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008381 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008382 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008383 break;
8384 }
8385 ++nextConst;
8386 }
8387 } else {
8388 // we have a non-aggregate (scalar) constant
8389 bool zero = nextConst >= consts.size();
8390 spv::Id scalar = 0;
8391 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008392 case glslang::EbtInt:
8393 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8394 break;
8395 case glslang::EbtUint:
8396 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8397 break;
8398 case glslang::EbtFloat:
8399 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8400 break;
8401 case glslang::EbtBool:
8402 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8403 break;
8404#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008405 case glslang::EbtInt8:
8406 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8407 break;
8408 case glslang::EbtUint8:
8409 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8410 break;
8411 case glslang::EbtInt16:
8412 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8413 break;
8414 case glslang::EbtUint16:
8415 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8416 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008417 case glslang::EbtInt64:
8418 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8419 break;
8420 case glslang::EbtUint64:
8421 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8422 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008423 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008424 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008425 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008426 case glslang::EbtFloat16:
8427 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8428 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008429 case glslang::EbtReference:
8430 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8431 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8432 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008433#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008434 case glslang::EbtString:
8435 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8436 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008437 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008438 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008439 break;
8440 }
8441 ++nextConst;
8442 return scalar;
8443 }
8444
8445 return builder.makeCompositeConstant(typeId, spvConsts);
8446}
8447
John Kessenich7c1aa102015-10-15 13:29:11 -06008448// Return true if the node is a constant or symbol whose reading has no
8449// non-trivial observable cost or effect.
8450bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8451{
8452 // don't know what this is
8453 if (node == nullptr)
8454 return false;
8455
8456 // a constant is safe
8457 if (node->getAsConstantUnion() != nullptr)
8458 return true;
8459
8460 // not a symbol means non-trivial
8461 if (node->getAsSymbolNode() == nullptr)
8462 return false;
8463
8464 // a symbol, depends on what's being read
8465 switch (node->getType().getQualifier().storage) {
8466 case glslang::EvqTemporary:
8467 case glslang::EvqGlobal:
8468 case glslang::EvqIn:
8469 case glslang::EvqInOut:
8470 case glslang::EvqConst:
8471 case glslang::EvqConstReadOnly:
8472 case glslang::EvqUniform:
8473 return true;
8474 default:
8475 return false;
8476 }
qining25262b32016-05-06 17:25:16 -04008477}
John Kessenich7c1aa102015-10-15 13:29:11 -06008478
8479// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008480// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008481// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008482// Return true if trivial.
8483bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8484{
8485 if (node == nullptr)
8486 return false;
8487
John Kessenich84cc15f2017-05-24 16:44:47 -06008488 // count non scalars as trivial, as well as anything coming from HLSL
8489 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008490 return true;
8491
John Kessenich7c1aa102015-10-15 13:29:11 -06008492 // symbols and constants are trivial
8493 if (isTrivialLeaf(node))
8494 return true;
8495
8496 // otherwise, it needs to be a simple operation or one or two leaf nodes
8497
8498 // not a simple operation
8499 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8500 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8501 if (binaryNode == nullptr && unaryNode == nullptr)
8502 return false;
8503
8504 // not on leaf nodes
8505 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8506 return false;
8507
8508 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8509 return false;
8510 }
8511
8512 switch (node->getAsOperator()->getOp()) {
8513 case glslang::EOpLogicalNot:
8514 case glslang::EOpConvIntToBool:
8515 case glslang::EOpConvUintToBool:
8516 case glslang::EOpConvFloatToBool:
8517 case glslang::EOpConvDoubleToBool:
8518 case glslang::EOpEqual:
8519 case glslang::EOpNotEqual:
8520 case glslang::EOpLessThan:
8521 case glslang::EOpGreaterThan:
8522 case glslang::EOpLessThanEqual:
8523 case glslang::EOpGreaterThanEqual:
8524 case glslang::EOpIndexDirect:
8525 case glslang::EOpIndexDirectStruct:
8526 case glslang::EOpLogicalXor:
8527 case glslang::EOpAny:
8528 case glslang::EOpAll:
8529 return true;
8530 default:
8531 return false;
8532 }
8533}
8534
8535// Emit short-circuiting code, where 'right' is never evaluated unless
8536// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008537spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8538 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008539{
8540 spv::Id boolTypeId = builder.makeBoolType();
8541
8542 // emit left operand
8543 builder.clearAccessChain();
8544 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008545 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008546
8547 // Operands to accumulate OpPhi operands
8548 std::vector<spv::Id> phiOperands;
8549 // accumulate left operand's phi information
8550 phiOperands.push_back(leftId);
8551 phiOperands.push_back(builder.getBuildPoint()->getId());
8552
8553 // Make the two kinds of operation symmetric with a "!"
8554 // || => emit "if (! left) result = right"
8555 // && => emit "if ( left) result = right"
8556 //
8557 // TODO: this runtime "not" for || could be avoided by adding functionality
8558 // to 'builder' to have an "else" without an "then"
8559 if (op == glslang::EOpLogicalOr)
8560 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8561
8562 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008563 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008564
8565 // emit right operand as the "then" part of the "if"
8566 builder.clearAccessChain();
8567 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008568 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008569
8570 // accumulate left operand's phi information
8571 phiOperands.push_back(rightId);
8572 phiOperands.push_back(builder.getBuildPoint()->getId());
8573
8574 // finish the "if"
8575 ifBuilder.makeEndIf();
8576
8577 // phi together the two results
8578 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8579}
8580
John Kessenicha28f7a72019-08-06 07:00:58 -06008581#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008582// Return type Id of the imported set of extended instructions corresponds to the name.
8583// Import this set if it has not been imported yet.
8584spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8585{
8586 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8587 return extBuiltinMap[name];
8588 else {
Rex Xu51596642016-09-21 18:56:12 +08008589 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008590 spv::Id extBuiltins = builder.import(name);
8591 extBuiltinMap[name] = extBuiltins;
8592 return extBuiltins;
8593 }
8594}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008595#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008596
John Kessenich140f3df2015-06-26 16:58:36 -06008597}; // end anonymous namespace
8598
8599namespace glslang {
8600
John Kessenich68d78fd2015-07-12 19:28:10 -06008601void GetSpirvVersion(std::string& version)
8602{
John Kessenich9e55f632015-07-15 10:03:39 -06008603 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008604 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008605 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008606 version = buf;
8607}
8608
John Kessenicha372a3e2017-11-02 22:32:14 -06008609// For low-order part of the generator's magic number. Bump up
8610// when there is a change in the style (e.g., if SSA form changes,
8611// or a different instruction sequence to do something gets used).
8612int GetSpirvGeneratorVersion()
8613{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008614 // return 1; // start
8615 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008616 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008617 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008618 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008619 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8620 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008621 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
8622 return 8; // switch to new dead block eliminator; use OpUnreachable
John Kessenicha372a3e2017-11-02 22:32:14 -06008623}
8624
John Kessenich140f3df2015-06-26 16:58:36 -06008625// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008626void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008627{
8628 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008629 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008630 if (out.fail())
8631 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008632 for (int i = 0; i < (int)spirv.size(); ++i) {
8633 unsigned int word = spirv[i];
8634 out.write((const char*)&word, 4);
8635 }
8636 out.close();
8637}
8638
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008639// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008640void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008641{
John Kessenich155d3512019-08-08 23:29:20 -06008642#ifndef GLSLANG_WEB
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008643 std::ofstream out;
8644 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008645 if (out.fail())
8646 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008647 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008648 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008649 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008650 if (varName != nullptr) {
8651 out << "\t #pragma once" << std::endl;
8652 out << "const uint32_t " << varName << "[] = {" << std::endl;
8653 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008654 const int WORDS_PER_LINE = 8;
8655 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8656 out << "\t";
8657 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8658 const unsigned int word = spirv[i + j];
8659 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8660 if (i + j + 1 < (int)spirv.size()) {
8661 out << ",";
8662 }
8663 }
8664 out << std::endl;
8665 }
Flavio15017db2017-02-15 14:29:33 -08008666 if (varName != nullptr) {
8667 out << "};";
8668 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008669 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008670#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008671}
8672
John Kessenich140f3df2015-06-26 16:58:36 -06008673//
8674// Set up the glslang traversal
8675//
John Kessenich4e11b612018-08-30 16:56:59 -06008676void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008677{
Lei Zhang17535f72016-05-04 15:55:59 -04008678 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008679 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008680}
8681
John Kessenich4e11b612018-08-30 16:56:59 -06008682void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008683 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008684{
John Kessenich140f3df2015-06-26 16:58:36 -06008685 TIntermNode* root = intermediate.getTreeRoot();
8686
8687 if (root == 0)
8688 return;
8689
John Kessenich4e11b612018-08-30 16:56:59 -06008690 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008691 if (options == nullptr)
8692 options = &defaultOptions;
8693
John Kessenich4e11b612018-08-30 16:56:59 -06008694 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008695
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008696 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008697 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008698 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008699 it.dumpSpv(spirv);
8700
GregFfb03a552018-03-29 11:49:14 -06008701#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008702 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8703 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008704 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8705 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008706 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008707 prelegalization = false;
8708 }
John Kessenich717c80a2018-08-23 15:17:10 -06008709
John Kessenich4e11b612018-08-30 16:56:59 -06008710 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008711 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008712
John Kessenich717c80a2018-08-23 15:17:10 -06008713 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008714 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008715
GregFcd1f1692017-09-21 18:40:22 -06008716#endif
8717
John Kessenich4e11b612018-08-30 16:56:59 -06008718 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008719}
8720
8721}; // end namespace glslang