blob: dd19e77dfef60004fb351fbc2a380409fd1458fe [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"
Ben Claytonfbe9a232020-06-17 11:17:19 +010059
60// Build-time generated includes
61#include "glslang/build_info.h"
John Kessenich140f3df2015-06-26 16:58:36 -060062
John Kessenich140f3df2015-06-26 16:58:36 -060063#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050064#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040065#include <list>
66#include <map>
67#include <stack>
68#include <string>
69#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060070
71namespace {
72
qining4c912612016-04-01 10:35:16 -040073namespace {
74class SpecConstantOpModeGuard {
75public:
76 SpecConstantOpModeGuard(spv::Builder* builder)
77 : builder_(builder) {
78 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040079 }
80 ~SpecConstantOpModeGuard() {
81 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
82 : builder_->setToNormalCodeGenMode();
83 }
qining40887662016-04-03 22:20:42 -040084 void turnOnSpecConstantOpMode() {
85 builder_->setToSpecConstCodeGenMode();
86 }
qining4c912612016-04-01 10:35:16 -040087
88private:
89 spv::Builder* builder_;
90 bool previous_flag_;
91};
John Kessenichead86222018-03-28 18:01:20 -060092
93struct OpDecorations {
John Kessenichb9197c82019-08-11 07:41:45 -060094 public:
95 OpDecorations(spv::Decoration precision, spv::Decoration noContraction, spv::Decoration nonUniform) :
96 precision(precision)
97#ifndef GLSLANG_WEB
98 ,
99 noContraction(noContraction),
100 nonUniform(nonUniform)
101#endif
102 { }
103
John Kessenichead86222018-03-28 18:01:20 -0600104 spv::Decoration precision;
John Kessenichb9197c82019-08-11 07:41:45 -0600105
106#ifdef GLSLANG_WEB
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400107 void addNoContraction(spv::Builder&, spv::Id) const { }
108 void addNonUniform(spv::Builder&, spv::Id) const { }
John Kessenichb9197c82019-08-11 07:41:45 -0600109#else
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400110 void addNoContraction(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, noContraction); }
111 void addNonUniform(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, nonUniform); }
John Kessenichb9197c82019-08-11 07:41:45 -0600112 protected:
113 spv::Decoration noContraction;
114 spv::Decoration nonUniform;
115#endif
116
John Kessenichead86222018-03-28 18:01:20 -0600117};
118
119} // namespace
qining4c912612016-04-01 10:35:16 -0400120
John Kessenich140f3df2015-06-26 16:58:36 -0600121//
122// The main holder of information for translating glslang to SPIR-V.
123//
124// Derives from the AST walking base class.
125//
126class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
127public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700128 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
129 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700130 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600131
132 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
133 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
134 void visitConstantUnion(glslang::TIntermConstantUnion*);
135 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
136 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
137 void visitSymbol(glslang::TIntermSymbol* symbol);
138 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
139 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
140 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
141
John Kessenichfca82622016-11-26 13:23:20 -0700142 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700143 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600144
145protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700146 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
147 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
148
Rex Xu17ff3432016-10-14 17:41:45 +0800149 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800150 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600151 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500152 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
153 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
154 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
155 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100156 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700157 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700158 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
159 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700160 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600161 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600162 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich9c14f772019-06-17 08:38:35 -0600163 spv::Id createSpvVariable(const glslang::TIntermSymbol*, spv::Id forcedType);
John Kessenich140f3df2015-06-26 16:58:36 -0600164 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600165 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
166 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
167 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600168 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600169 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600170 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600171 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600172 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
173 glslang::TLayoutPacking, const glslang::TQualifier&);
174 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
175 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700176 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700177 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800178 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600179 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700180 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700181 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
182 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700183 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
184 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100185 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600186
John Kessenich6fccb3c2016-09-19 16:01:41 -0600187 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600188 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600189 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600190 void makeFunctions(const glslang::TIntermSequence&);
191 void makeGlobalInitializers(const glslang::TIntermSequence&);
192 void visitFunctions(const glslang::TIntermSequence&);
193 void handleFunctionEntry(const glslang::TIntermAggregate* node);
John Kessenich8985fc92020-03-03 10:25:07 -0700194 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
195 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -0600196 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
197 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600198 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
199
John Kessenichead86222018-03-28 18:01:20 -0600200 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
201 glslang::TBasicType typeProxy, bool reduceComparison = true);
202 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
203 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
John Kessenich8985fc92020-03-03 10:25:07 -0700204 glslang::TBasicType typeProxy,
205 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -0600206 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
207 glslang::TBasicType typeProxy);
208 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
209 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600210 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600211 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
John Kessenich8985fc92020-03-03 10:25:07 -0700212 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId,
213 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
214 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
215 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands,
216 glslang::TBasicType typeProxy);
217 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
218 spv::Id typeId, std::vector<spv::Id>& operands);
219 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands,
220 glslang::TBasicType typeProxy);
221 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId,
222 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800223 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600224 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700225 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
qining08408382016-03-21 09:51:37 -0400226 spv::Id createSpvConstant(const glslang::TIntermTyped&);
John Kessenich8985fc92020-03-03 10:25:07 -0700227 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&,
228 int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600229 bool isTrivialLeaf(const glslang::TIntermTyped* node);
230 bool isTrivial(const glslang::TIntermTyped* node);
231 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800232 spv::Id getExtBuiltins(const char* name);
Daniel Kochdb32b242020-03-17 20:42:47 -0400233 std::pair<spv::Id, spv::Id> getForcedType(glslang::TBuiltInVariable builtIn, const glslang::TType&);
John Kessenich9c14f772019-06-17 08:38:35 -0600234 spv::Id translateForcedType(spv::Id object);
Jeff Bolz53134492019-06-25 13:31:10 -0500235 spv::Id createCompositeConstruct(spv::Id typeId, std::vector<spv::Id> constituents);
John Kessenich140f3df2015-06-26 16:58:36 -0600236
John Kessenich121853f2017-05-31 17:11:16 -0600237 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600238 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600239 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700240 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600241 int sequenceDepth;
242
Lei Zhang17535f72016-05-04 15:55:59 -0400243 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400244
John Kessenich140f3df2015-06-26 16:58:36 -0600245 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
246 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700247 bool inEntryPoint;
248 bool entryPointTerminated;
John Kessenich8985fc92020-03-03 10:25:07 -0700249 bool linkageOnly; // true when visiting the set of objects in the AST present only for
250 // establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700251 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600252 const glslang::TIntermediate* glslangIntermediate;
John Kessenich605afc72019-06-17 23:33:09 -0600253 bool nanMinMaxClamp; // true if use NMin/NMax/NClamp instead of FMin/FMax/FClamp
John Kessenich140f3df2015-06-26 16:58:36 -0600254 spv::Id stdBuiltins;
Jeff Bolz04d73732019-05-31 13:06:01 -0500255 spv::Id nonSemanticDebugPrintf;
Rex Xu9d93a232016-05-05 12:30:44 +0800256 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600257
John Kessenich2f273362015-07-18 22:34:27 -0600258 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich8985fc92020-03-03 10:25:07 -0700259 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues,
260 // rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600261 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700262 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700263 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
Roy05a5b532020-01-03 16:21:34 +0800264 std::unordered_map<int, std::vector<int>> memberRemapper;
265 // for mapping glslang symbol struct to symbol Id
266 std::unordered_map<const glslang::TTypeList*, int> glslangTypeToIdMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600267 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700268 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600269 // Map pointee types for EbtReference to their forward pointers
270 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich9c14f772019-06-17 08:38:35 -0600271 // Type forcing, for when SPIR-V wants a different type than the AST,
272 // requiring local translation to and from SPIR-V type on every access.
273 // Maps <builtin-variable-id -> AST-required-type-id>
274 std::unordered_map<spv::Id, spv::Id> forceType;
John Kessenich140f3df2015-06-26 16:58:36 -0600275};
276
277//
278// Helper functions for translating glslang representations to SPIR-V enumerants.
279//
280
281// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700282spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600283{
John Kessenich155d3512019-08-08 23:29:20 -0600284#ifdef GLSLANG_WEB
285 return spv::SourceLanguageESSL;
Shahbaz Youssefi1ef2e252020-07-03 15:42:53 -0400286#elif defined(GLSLANG_ANGLE)
287 return spv::SourceLanguageGLSL;
John Kessenich155d3512019-08-08 23:29:20 -0600288#endif
289
John Kessenich66e2faf2016-03-12 18:34:36 -0700290 switch (source) {
291 case glslang::EShSourceGlsl:
292 switch (profile) {
293 case ENoProfile:
294 case ECoreProfile:
295 case ECompatibilityProfile:
296 return spv::SourceLanguageGLSL;
297 case EEsProfile:
298 return spv::SourceLanguageESSL;
299 default:
300 return spv::SourceLanguageUnknown;
301 }
302 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600303 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600304 default:
305 return spv::SourceLanguageUnknown;
306 }
307}
308
309// Translate glslang language (stage) to SPIR-V execution model.
310spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
311{
312 switch (stage) {
313 case EShLangVertex: return spv::ExecutionModelVertex;
John Kessenicha28f7a72019-08-06 07:00:58 -0600314 case EShLangFragment: return spv::ExecutionModelFragment;
John Kessenicha28f7a72019-08-06 07:00:58 -0600315 case EShLangCompute: return spv::ExecutionModelGLCompute;
John Kessenich51ed01c2019-10-10 11:40:11 -0600316#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -0600317 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
318 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
319 case EShLangGeometry: return spv::ExecutionModelGeometry;
Daniel Kochdb32b242020-03-17 20:42:47 -0400320 case EShLangRayGen: return spv::ExecutionModelRayGenerationKHR;
321 case EShLangIntersect: return spv::ExecutionModelIntersectionKHR;
322 case EShLangAnyHit: return spv::ExecutionModelAnyHitKHR;
323 case EShLangClosestHit: return spv::ExecutionModelClosestHitKHR;
324 case EShLangMiss: return spv::ExecutionModelMissKHR;
325 case EShLangCallable: return spv::ExecutionModelCallableKHR;
Chao Chen3c366992018-09-19 11:41:59 -0700326 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
327 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
328#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600329 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700330 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600331 return spv::ExecutionModelFragment;
332 }
333}
334
John Kessenich140f3df2015-06-26 16:58:36 -0600335// Translate glslang sampler type to SPIR-V dimensionality.
336spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
337{
338 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700339 case glslang::Esd1D: return spv::Dim1D;
340 case glslang::Esd2D: return spv::Dim2D;
341 case glslang::Esd3D: return spv::Dim3D;
342 case glslang::EsdCube: return spv::DimCube;
343 case glslang::EsdRect: return spv::DimRect;
344 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700345 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600346 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700347 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600348 return spv::Dim2D;
349 }
350}
351
John Kessenichf6640762016-08-01 19:44:00 -0600352// Translate glslang precision to SPIR-V precision decorations.
353spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600354{
John Kessenichf6640762016-08-01 19:44:00 -0600355 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700356 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600357 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600358 default:
359 return spv::NoPrecision;
360 }
361}
362
John Kessenichf6640762016-08-01 19:44:00 -0600363// Translate glslang type to SPIR-V precision decorations.
364spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
365{
366 return TranslatePrecisionDecoration(type.getQualifier().precision);
367}
368
John Kessenich140f3df2015-06-26 16:58:36 -0600369// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600370spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600371{
372 if (type.getBasicType() == glslang::EbtBlock) {
373 switch (type.getQualifier().storage) {
374 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600375 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600376 case glslang::EvqVaryingIn: return spv::DecorationBlock;
377 case glslang::EvqVaryingOut: return spv::DecorationBlock;
John Kessenicha28f7a72019-08-06 07:00:58 -0600378#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -0400379 case glslang::EvqPayload: return spv::DecorationBlock;
380 case glslang::EvqPayloadIn: return spv::DecorationBlock;
381 case glslang::EvqHitAttr: return spv::DecorationBlock;
382 case glslang::EvqCallableData: return spv::DecorationBlock;
383 case glslang::EvqCallableDataIn: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700384#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600385 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700386 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600387 break;
388 }
389 }
390
John Kessenich4016e382016-07-15 11:53:56 -0600391 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600392}
393
Rex Xu1da878f2016-02-21 20:59:01 +0800394// Translate glslang type to SPIR-V memory decorations.
John Kessenich8985fc92020-03-03 10:25:07 -0700395void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory,
396 bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800397{
Jeff Bolz36831c92018-09-05 10:11:41 -0500398 if (!useVulkanMemoryModel) {
John Kessenichf8d1d742019-10-21 06:55:11 -0600399 if (qualifier.isCoherent())
Jeff Bolz36831c92018-09-05 10:11:41 -0500400 memory.push_back(spv::DecorationCoherent);
John Kessenichf8d1d742019-10-21 06:55:11 -0600401 if (qualifier.isVolatile()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500402 memory.push_back(spv::DecorationVolatile);
403 memory.push_back(spv::DecorationCoherent);
404 }
John Kessenich14b85d32018-06-04 15:36:03 -0600405 }
John Kessenichf8d1d742019-10-21 06:55:11 -0600406 if (qualifier.isRestrict())
Rex Xu1da878f2016-02-21 20:59:01 +0800407 memory.push_back(spv::DecorationRestrict);
John Kessenichdeec1932019-08-13 08:00:30 -0600408 if (qualifier.isReadOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800409 memory.push_back(spv::DecorationNonWritable);
John Kessenichdeec1932019-08-13 08:00:30 -0600410 if (qualifier.isWriteOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800411 memory.push_back(spv::DecorationNonReadable);
412}
413
John Kessenich140f3df2015-06-26 16:58:36 -0600414// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700415spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600416{
417 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700418 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600419 case glslang::ElmRowMajor:
420 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700421 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600422 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700423 default:
424 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600425 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600426 }
427 } else {
428 switch (type.getBasicType()) {
429 default:
John Kessenich4016e382016-07-15 11:53:56 -0600430 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600431 break;
432 case glslang::EbtBlock:
433 switch (type.getQualifier().storage) {
434 case glslang::EvqUniform:
435 case glslang::EvqBuffer:
436 switch (type.getQualifier().layoutPacking) {
437 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600438 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
439 default:
John Kessenich4016e382016-07-15 11:53:56 -0600440 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600441 }
442 case glslang::EvqVaryingIn:
443 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700444 if (type.getQualifier().isTaskMemory()) {
445 switch (type.getQualifier().layoutPacking) {
446 case glslang::ElpShared: return spv::DecorationGLSLShared;
447 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
448 default: break;
449 }
450 } else {
451 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
452 }
John Kessenich4016e382016-07-15 11:53:56 -0600453 return spv::DecorationMax;
John Kessenicha28f7a72019-08-06 07:00:58 -0600454#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -0400455 case glslang::EvqPayload:
456 case glslang::EvqPayloadIn:
457 case glslang::EvqHitAttr:
458 case glslang::EvqCallableData:
459 case glslang::EvqCallableDataIn:
Chao Chenb50c02e2018-09-19 11:42:24 -0700460 return spv::DecorationMax;
461#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600462 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700463 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600464 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600465 }
466 }
467 }
468}
469
470// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600471// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700472// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800473spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600474{
Rex Xubbceed72016-05-21 09:40:44 +0800475 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700476 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600477 return spv::DecorationMax;
John Kessenich7015bd62019-08-01 03:28:08 -0600478 else if (qualifier.isNonPerspective())
John Kessenich55e7d112015-11-15 21:33:39 -0700479 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700480 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600481 return spv::DecorationFlat;
John Kessenicha28f7a72019-08-06 07:00:58 -0600482 else if (qualifier.isExplicitInterpolation()) {
Rex Xu17ff3432016-10-14 17:41:45 +0800483 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800484 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800485 }
Rex Xubbceed72016-05-21 09:40:44 +0800486 else
John Kessenich4016e382016-07-15 11:53:56 -0600487 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800488}
489
490// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600491// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800492// should be applied.
493spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
494{
John Kessenichb9197c82019-08-11 07:41:45 -0600495 if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600496 return spv::DecorationCentroid;
John Kessenichb9197c82019-08-11 07:41:45 -0600497#ifndef GLSLANG_WEB
498 else if (qualifier.patch)
499 return spv::DecorationPatch;
John Kessenich5e801132016-02-15 11:09:46 -0700500 else if (qualifier.sample) {
501 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600502 return spv::DecorationSample;
John Kessenichb9197c82019-08-11 07:41:45 -0600503 }
504#endif
505
506 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600507}
508
John Kessenich92187592016-02-01 13:45:25 -0700509// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700510spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600511{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700512 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600513 return spv::DecorationInvariant;
514 else
John Kessenich4016e382016-07-15 11:53:56 -0600515 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600516}
517
qining9220dbb2016-05-04 17:34:38 -0400518// If glslang type is noContraction, return SPIR-V NoContraction decoration.
519spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
520{
John Kessenichb9197c82019-08-11 07:41:45 -0600521#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -0600522 if (qualifier.isNoContraction())
qining9220dbb2016-05-04 17:34:38 -0400523 return spv::DecorationNoContraction;
524 else
John Kessenichb9197c82019-08-11 07:41:45 -0600525#endif
John Kessenich4016e382016-07-15 11:53:56 -0600526 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400527}
528
John Kessenich5611c6d2018-04-05 11:25:02 -0600529// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
530spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
531{
John Kessenichb9197c82019-08-11 07:41:45 -0600532#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -0600533 if (qualifier.isNonUniform()) {
John Kessenich8317e6c2019-08-18 23:58:08 -0600534 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -0600535 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
536 return spv::DecorationNonUniformEXT;
537 } else
John Kessenichb9197c82019-08-11 07:41:45 -0600538#endif
John Kessenich5611c6d2018-04-05 11:25:02 -0600539 return spv::DecorationMax;
540}
541
John Kessenichb9197c82019-08-11 07:41:45 -0600542spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(
543 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500544{
Jeff Bolz36831c92018-09-05 10:11:41 -0500545 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600546
547#ifndef GLSLANG_WEB
548 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage)
549 return mask;
550
Daniel Kochdb32b242020-03-17 20:42:47 -0400551 if (coherentFlags.isVolatile() || coherentFlags.anyCoherent()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500552 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
553 spv::MemoryAccessMakePointerVisibleKHRMask;
554 }
Daniel Kochdb32b242020-03-17 20:42:47 -0400555
Jeff Bolz36831c92018-09-05 10:11:41 -0500556 if (coherentFlags.nonprivate) {
557 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
558 }
559 if (coherentFlags.volatil) {
560 mask = mask | spv::MemoryAccessVolatileMask;
561 }
562 if (mask != spv::MemoryAccessMaskNone) {
563 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
564 }
John Kessenichb9197c82019-08-11 07:41:45 -0600565#endif
566
Jeff Bolz36831c92018-09-05 10:11:41 -0500567 return mask;
568}
569
John Kessenichb9197c82019-08-11 07:41:45 -0600570spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(
571 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500572{
Jeff Bolz36831c92018-09-05 10:11:41 -0500573 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600574
575#ifndef GLSLANG_WEB
576 if (!glslangIntermediate->usingVulkanMemoryModel())
577 return mask;
578
Jeff Bolz36831c92018-09-05 10:11:41 -0500579 if (coherentFlags.volatil ||
Daniel Kochdb32b242020-03-17 20:42:47 -0400580 coherentFlags.anyCoherent()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500581 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
582 spv::ImageOperandsMakeTexelVisibleKHRMask;
583 }
584 if (coherentFlags.nonprivate) {
585 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
586 }
587 if (coherentFlags.volatil) {
588 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
589 }
590 if (mask != spv::ImageOperandsMaskNone) {
591 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
592 }
John Kessenichb9197c82019-08-11 07:41:45 -0600593#endif
594
Jeff Bolz36831c92018-09-05 10:11:41 -0500595 return mask;
596}
597
598spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
599{
John Kessenichb9197c82019-08-11 07:41:45 -0600600 spv::Builder::AccessChain::CoherentFlags flags = {};
601#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -0500602 flags.coherent = type.getQualifier().coherent;
603 flags.devicecoherent = type.getQualifier().devicecoherent;
604 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
605 // shared variables are implicitly workgroupcoherent in GLSL.
606 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
607 type.getQualifier().storage == glslang::EvqShared;
608 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Daniel Kochdb32b242020-03-17 20:42:47 -0400609 flags.shadercallcoherent = type.getQualifier().shadercallcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600610 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500611 // *coherent variables are implicitly nonprivate in GLSL
612 flags.nonprivate = type.getQualifier().nonprivate ||
Daniel Kochdb32b242020-03-17 20:42:47 -0400613 flags.anyCoherent() ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600614 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500615 flags.isImage = type.getBasicType() == glslang::EbtSampler;
John Kessenichb9197c82019-08-11 07:41:45 -0600616#endif
Jeff Bolz36831c92018-09-05 10:11:41 -0500617 return flags;
618}
619
John Kessenichb9197c82019-08-11 07:41:45 -0600620spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(
621 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500622{
John Kessenichb9197c82019-08-11 07:41:45 -0600623 spv::Scope scope = spv::ScopeMax;
624
625#ifndef GLSLANG_WEB
Jeff Bolz38cbad12019-03-05 14:40:07 -0600626 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500627 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
628 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
629 } else if (coherentFlags.devicecoherent) {
630 scope = spv::ScopeDevice;
631 } else if (coherentFlags.queuefamilycoherent) {
632 scope = spv::ScopeQueueFamilyKHR;
633 } else if (coherentFlags.workgroupcoherent) {
634 scope = spv::ScopeWorkgroup;
635 } else if (coherentFlags.subgroupcoherent) {
636 scope = spv::ScopeSubgroup;
Daniel Kochdb32b242020-03-17 20:42:47 -0400637 } else if (coherentFlags.shadercallcoherent) {
638 scope = spv::ScopeShaderCallKHR;
Jeff Bolz36831c92018-09-05 10:11:41 -0500639 }
640 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
641 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
642 }
John Kessenichb9197c82019-08-11 07:41:45 -0600643#endif
644
Jeff Bolz36831c92018-09-05 10:11:41 -0500645 return scope;
646}
647
David Netoa901ffe2016-06-08 14:11:40 +0100648// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
649// associated capabilities when required. For some built-in variables, a capability
650// is generated only when using the variable in an executable instruction, but not when
651// just declaring a struct member variable with it. This is true for PointSize,
652// ClipDistance, and CullDistance.
John Kessenich8985fc92020-03-03 10:25:07 -0700653spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn,
654 bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600655{
656 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700657 case glslang::EbvPointSize:
John Kessenich155d3512019-08-08 23:29:20 -0600658#ifndef GLSLANG_WEB
John Kessenich78a45572016-07-08 14:05:15 -0600659 // Defer adding the capability until the built-in is actually used.
660 if (! memberDeclaration) {
661 switch (glslangIntermediate->getStage()) {
662 case EShLangGeometry:
663 builder.addCapability(spv::CapabilityGeometryPointSize);
664 break;
665 case EShLangTessControl:
666 case EShLangTessEvaluation:
667 builder.addCapability(spv::CapabilityTessellationPointSize);
668 break;
669 default:
670 break;
671 }
John Kessenich92187592016-02-01 13:45:25 -0700672 }
John Kessenich155d3512019-08-08 23:29:20 -0600673#endif
John Kessenich92187592016-02-01 13:45:25 -0700674 return spv::BuiltInPointSize;
675
John Kessenicha28f7a72019-08-06 07:00:58 -0600676 case glslang::EbvPosition: return spv::BuiltInPosition;
677 case glslang::EbvVertexId: return spv::BuiltInVertexId;
678 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
679 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
680 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
681
682 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
683 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
684 case glslang::EbvFace: return spv::BuiltInFrontFacing;
685 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
686
John Kessenich3dd1ce52019-10-17 07:08:40 -0600687 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
688 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
689 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
690 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
691 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
692 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
693
John Kessenicha28f7a72019-08-06 07:00:58 -0600694#ifndef GLSLANG_WEB
John Kessenichebb50532016-05-16 19:22:05 -0600695 // These *Distance capabilities logically belong here, but if the member is declared and
696 // then never used, consumers of SPIR-V prefer the capability not be declared.
697 // They are now generated when used, rather than here when declared.
698 // Potentially, the specification should be more clear what the minimum
699 // use needed is to trigger the capability.
700 //
John Kessenich92187592016-02-01 13:45:25 -0700701 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100702 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800703 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700704 return spv::BuiltInClipDistance;
705
706 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100707 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800708 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700709 return spv::BuiltInCullDistance;
710
711 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600712 builder.addCapability(spv::CapabilityMultiViewport);
713 if (glslangIntermediate->getStage() == EShLangVertex ||
714 glslangIntermediate->getStage() == EShLangTessControl ||
715 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800716
John Kessenich8317e6c2019-08-18 23:58:08 -0600717 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600718 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800719 }
John Kessenich92187592016-02-01 13:45:25 -0700720 return spv::BuiltInViewportIndex;
721
John Kessenich5e801132016-02-15 11:09:46 -0700722 case glslang::EbvSampleId:
723 builder.addCapability(spv::CapabilitySampleRateShading);
724 return spv::BuiltInSampleId;
725
726 case glslang::EbvSamplePosition:
727 builder.addCapability(spv::CapabilitySampleRateShading);
728 return spv::BuiltInSamplePosition;
729
730 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700731 return spv::BuiltInSampleMask;
732
John Kessenich78a45572016-07-08 14:05:15 -0600733 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700734 if (glslangIntermediate->getStage() == EShLangMeshNV) {
735 return spv::BuiltInLayer;
736 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600737 builder.addCapability(spv::CapabilityGeometry);
738 if (glslangIntermediate->getStage() == EShLangVertex ||
739 glslangIntermediate->getStage() == EShLangTessControl ||
740 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800741
John Kessenich8317e6c2019-08-18 23:58:08 -0600742 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600743 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800744 }
John Kessenich78a45572016-07-08 14:05:15 -0600745 return spv::BuiltInLayer;
746
John Kessenichda581a22015-10-14 14:10:30 -0600747 case glslang::EbvBaseVertex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600748 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800749 builder.addCapability(spv::CapabilityDrawParameters);
750 return spv::BuiltInBaseVertex;
751
John Kessenichda581a22015-10-14 14:10:30 -0600752 case glslang::EbvBaseInstance:
John Kessenich8317e6c2019-08-18 23:58:08 -0600753 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800754 builder.addCapability(spv::CapabilityDrawParameters);
755 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200756
John Kessenichda581a22015-10-14 14:10:30 -0600757 case glslang::EbvDrawId:
John Kessenich8317e6c2019-08-18 23:58:08 -0600758 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800759 builder.addCapability(spv::CapabilityDrawParameters);
760 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200761
762 case glslang::EbvPrimitiveId:
763 if (glslangIntermediate->getStage() == EShLangFragment)
764 builder.addCapability(spv::CapabilityGeometry);
765 return spv::BuiltInPrimitiveId;
766
Rex Xu37cdcee2017-06-29 17:46:34 +0800767 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800768 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
769 builder.addCapability(spv::CapabilityStencilExportEXT);
770 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800771
John Kessenich140f3df2015-06-26 16:58:36 -0600772 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600773 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
774 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
775 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
776 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
John Kessenich140f3df2015-06-26 16:58:36 -0600777 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
Rex Xu51596642016-09-21 18:56:12 +0800778
Rex Xu574ab042016-04-14 16:53:07 +0800779 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800780 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800781 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
782 return spv::BuiltInSubgroupSize;
783
Rex Xu574ab042016-04-14 16:53:07 +0800784 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800785 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800786 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
787 return spv::BuiltInSubgroupLocalInvocationId;
788
Rex Xu574ab042016-04-14 16:53:07 +0800789 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800790 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
791 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600792 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800793
Rex Xu574ab042016-04-14 16:53:07 +0800794 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800795 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
796 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600797 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800798
Rex Xu574ab042016-04-14 16:53:07 +0800799 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800800 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
801 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600802 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800803
Rex Xu574ab042016-04-14 16:53:07 +0800804 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800805 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
806 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600807 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800808
Rex Xu574ab042016-04-14 16:53:07 +0800809 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800810 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
811 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600812 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800813
John Kessenich66011cb2018-03-06 16:12:04 -0700814 case glslang::EbvNumSubgroups:
815 builder.addCapability(spv::CapabilityGroupNonUniform);
816 return spv::BuiltInNumSubgroups;
817
818 case glslang::EbvSubgroupID:
819 builder.addCapability(spv::CapabilityGroupNonUniform);
820 return spv::BuiltInSubgroupId;
821
822 case glslang::EbvSubgroupSize2:
823 builder.addCapability(spv::CapabilityGroupNonUniform);
824 return spv::BuiltInSubgroupSize;
825
826 case glslang::EbvSubgroupInvocation2:
827 builder.addCapability(spv::CapabilityGroupNonUniform);
828 return spv::BuiltInSubgroupLocalInvocationId;
829
830 case glslang::EbvSubgroupEqMask2:
831 builder.addCapability(spv::CapabilityGroupNonUniform);
832 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
833 return spv::BuiltInSubgroupEqMask;
834
835 case glslang::EbvSubgroupGeMask2:
836 builder.addCapability(spv::CapabilityGroupNonUniform);
837 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
838 return spv::BuiltInSubgroupGeMask;
839
840 case glslang::EbvSubgroupGtMask2:
841 builder.addCapability(spv::CapabilityGroupNonUniform);
842 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
843 return spv::BuiltInSubgroupGtMask;
844
845 case glslang::EbvSubgroupLeMask2:
846 builder.addCapability(spv::CapabilityGroupNonUniform);
847 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
848 return spv::BuiltInSubgroupLeMask;
849
850 case glslang::EbvSubgroupLtMask2:
851 builder.addCapability(spv::CapabilityGroupNonUniform);
852 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
853 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600854
Rex Xu17ff3432016-10-14 17:41:45 +0800855 case glslang::EbvBaryCoordNoPersp:
856 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
857 return spv::BuiltInBaryCoordNoPerspAMD;
858
859 case glslang::EbvBaryCoordNoPerspCentroid:
860 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
861 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
862
863 case glslang::EbvBaryCoordNoPerspSample:
864 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
865 return spv::BuiltInBaryCoordNoPerspSampleAMD;
866
867 case glslang::EbvBaryCoordSmooth:
868 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
869 return spv::BuiltInBaryCoordSmoothAMD;
870
871 case glslang::EbvBaryCoordSmoothCentroid:
872 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
873 return spv::BuiltInBaryCoordSmoothCentroidAMD;
874
875 case glslang::EbvBaryCoordSmoothSample:
876 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
877 return spv::BuiltInBaryCoordSmoothSampleAMD;
878
879 case glslang::EbvBaryCoordPullModel:
880 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
881 return spv::BuiltInBaryCoordPullModelAMD;
chaoc771d89f2017-01-13 01:10:53 -0800882
John Kessenich6c8aaac2017-02-27 01:20:51 -0700883 case glslang::EbvDeviceIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600884 builder.addIncorporatedExtension(spv::E_SPV_KHR_device_group, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700885 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700886 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700887
888 case glslang::EbvViewIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600889 builder.addIncorporatedExtension(spv::E_SPV_KHR_multiview, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700890 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700891 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700892
Daniel Koch5154db52018-11-26 10:01:58 -0500893 case glslang::EbvFragSizeEXT:
894 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
895 builder.addCapability(spv::CapabilityFragmentDensityEXT);
896 return spv::BuiltInFragSizeEXT;
897
898 case glslang::EbvFragInvocationCountEXT:
899 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
900 builder.addCapability(spv::CapabilityFragmentDensityEXT);
901 return spv::BuiltInFragInvocationCountEXT;
902
chaoc771d89f2017-01-13 01:10:53 -0800903 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800904 if (!memberDeclaration) {
905 builder.addExtension(spv::E_SPV_NV_viewport_array2);
906 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
907 }
chaoc771d89f2017-01-13 01:10:53 -0800908 return spv::BuiltInViewportMaskNV;
909 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800910 if (!memberDeclaration) {
911 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
912 builder.addCapability(spv::CapabilityShaderStereoViewNV);
913 }
chaoc771d89f2017-01-13 01:10:53 -0800914 return spv::BuiltInSecondaryPositionNV;
915 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800916 if (!memberDeclaration) {
917 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
918 builder.addCapability(spv::CapabilityShaderStereoViewNV);
919 }
chaoc771d89f2017-01-13 01:10:53 -0800920 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800921 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800922 if (!memberDeclaration) {
923 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
924 builder.addCapability(spv::CapabilityPerViewAttributesNV);
925 }
chaocdf3956c2017-02-14 14:52:34 -0800926 return spv::BuiltInPositionPerViewNV;
927 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800928 if (!memberDeclaration) {
929 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
930 builder.addCapability(spv::CapabilityPerViewAttributesNV);
931 }
chaocdf3956c2017-02-14 14:52:34 -0800932 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700933 case glslang::EbvFragFullyCoveredNV:
934 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
935 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
936 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700937 case glslang::EbvFragmentSizeNV:
938 builder.addExtension(spv::E_SPV_NV_shading_rate);
939 builder.addCapability(spv::CapabilityShadingRateNV);
940 return spv::BuiltInFragmentSizeNV;
941 case glslang::EbvInvocationsPerPixelNV:
942 builder.addExtension(spv::E_SPV_NV_shading_rate);
943 builder.addCapability(spv::CapabilityShadingRateNV);
944 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700945
Daniel Koch593a4e02019-05-27 16:46:31 -0400946 // ray tracing
Daniel Kochdb32b242020-03-17 20:42:47 -0400947 case glslang::EbvLaunchId:
948 return spv::BuiltInLaunchIdKHR;
949 case glslang::EbvLaunchSize:
950 return spv::BuiltInLaunchSizeKHR;
951 case glslang::EbvWorldRayOrigin:
952 return spv::BuiltInWorldRayOriginKHR;
953 case glslang::EbvWorldRayDirection:
954 return spv::BuiltInWorldRayDirectionKHR;
955 case glslang::EbvObjectRayOrigin:
956 return spv::BuiltInObjectRayOriginKHR;
957 case glslang::EbvObjectRayDirection:
958 return spv::BuiltInObjectRayDirectionKHR;
959 case glslang::EbvRayTmin:
960 return spv::BuiltInRayTminKHR;
961 case glslang::EbvRayTmax:
962 return spv::BuiltInRayTmaxKHR;
963 case glslang::EbvInstanceCustomIndex:
964 return spv::BuiltInInstanceCustomIndexKHR;
965 case glslang::EbvHitT:
966 return spv::BuiltInHitTKHR;
967 case glslang::EbvHitKind:
968 return spv::BuiltInHitKindKHR;
969 case glslang::EbvObjectToWorld:
970 case glslang::EbvObjectToWorld3x4:
971 return spv::BuiltInObjectToWorldKHR;
972 case glslang::EbvWorldToObject:
973 case glslang::EbvWorldToObject3x4:
974 return spv::BuiltInWorldToObjectKHR;
975 case glslang::EbvIncomingRayFlags:
976 return spv::BuiltInIncomingRayFlagsKHR;
977 case glslang::EbvGeometryIndex:
978 return spv::BuiltInRayGeometryIndexKHR;
Daniel Koch593a4e02019-05-27 16:46:31 -0400979
980 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700981 case glslang::EbvBaryCoordNV:
982 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
983 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
984 return spv::BuiltInBaryCoordNV;
985 case glslang::EbvBaryCoordNoPerspNV:
986 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
987 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
988 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400989
990 // mesh shaders
991 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700992 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400993 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700994 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400995 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700996 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400997 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700998 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400999 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001000 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001001 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001002 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001003 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001004 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001005 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -07001006 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch2cb2f192019-06-04 08:43:32 -04001007
1008 // sm builtins
1009 case glslang::EbvWarpsPerSM:
1010 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1011 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1012 return spv::BuiltInWarpsPerSMNV;
1013 case glslang::EbvSMCount:
1014 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1015 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1016 return spv::BuiltInSMCountNV;
1017 case glslang::EbvWarpID:
1018 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1019 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1020 return spv::BuiltInWarpIDNV;
1021 case glslang::EbvSMID:
1022 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1023 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1024 return spv::BuiltInSMIDNV;
John Kessenicha28f7a72019-08-06 07:00:58 -06001025#endif
1026
Rex Xu3e783f92017-02-22 16:44:48 +08001027 default:
1028 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -06001029 }
1030}
1031
Rex Xufc618912015-09-09 16:42:49 +08001032// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -07001033spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +08001034{
1035 assert(type.getBasicType() == glslang::EbtSampler);
1036
John Kessenichb9197c82019-08-11 07:41:45 -06001037#ifdef GLSLANG_WEB
1038 return spv::ImageFormatUnknown;
1039#endif
1040
John Kessenich5d0fa972016-02-15 11:57:00 -07001041 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -06001042 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -07001043 case glslang::ElfRg32f:
1044 case glslang::ElfRg16f:
1045 case glslang::ElfR11fG11fB10f:
1046 case glslang::ElfR16f:
1047 case glslang::ElfRgba16:
1048 case glslang::ElfRgb10A2:
1049 case glslang::ElfRg16:
1050 case glslang::ElfRg8:
1051 case glslang::ElfR16:
1052 case glslang::ElfR8:
1053 case glslang::ElfRgba16Snorm:
1054 case glslang::ElfRg16Snorm:
1055 case glslang::ElfRg8Snorm:
1056 case glslang::ElfR16Snorm:
1057 case glslang::ElfR8Snorm:
1058
1059 case glslang::ElfRg32i:
1060 case glslang::ElfRg16i:
1061 case glslang::ElfRg8i:
1062 case glslang::ElfR16i:
1063 case glslang::ElfR8i:
1064
1065 case glslang::ElfRgb10a2ui:
1066 case glslang::ElfRg32ui:
1067 case glslang::ElfRg16ui:
1068 case glslang::ElfRg8ui:
1069 case glslang::ElfR16ui:
1070 case glslang::ElfR8ui:
1071 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1072 break;
1073
1074 default:
1075 break;
1076 }
1077
1078 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001079 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001080 case glslang::ElfNone: return spv::ImageFormatUnknown;
1081 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1082 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1083 case glslang::ElfR32f: return spv::ImageFormatR32f;
1084 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1085 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1086 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1087 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1088 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1089 case glslang::ElfR16f: return spv::ImageFormatR16f;
1090 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1091 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1092 case glslang::ElfRg16: return spv::ImageFormatRg16;
1093 case glslang::ElfRg8: return spv::ImageFormatRg8;
1094 case glslang::ElfR16: return spv::ImageFormatR16;
1095 case glslang::ElfR8: return spv::ImageFormatR8;
1096 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1097 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1098 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1099 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1100 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1101 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1102 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1103 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1104 case glslang::ElfR32i: return spv::ImageFormatR32i;
1105 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1106 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1107 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1108 case glslang::ElfR16i: return spv::ImageFormatR16i;
1109 case glslang::ElfR8i: return spv::ImageFormatR8i;
1110 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1111 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1112 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1113 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1114 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1115 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1116 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1117 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1118 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1119 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001120 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001121 }
1122}
1123
John Kessenich8985fc92020-03-03 10:25:07 -07001124spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(
1125 const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001126{
John Kesseniche18fd202018-01-30 11:01:39 -07001127 if (selectionNode.getFlatten())
1128 return spv::SelectionControlFlattenMask;
1129 if (selectionNode.getDontFlatten())
1130 return spv::SelectionControlDontFlattenMask;
1131 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001132}
1133
John Kessenich8985fc92020-03-03 10:25:07 -07001134spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode)
1135 const
steve-lunargf1709e72017-05-02 20:14:50 -06001136{
John Kesseniche18fd202018-01-30 11:01:39 -07001137 if (switchNode.getFlatten())
1138 return spv::SelectionControlFlattenMask;
1139 if (switchNode.getDontFlatten())
1140 return spv::SelectionControlDontFlattenMask;
1141 return spv::SelectionControlMaskNone;
1142}
1143
John Kessenicha2858d92018-01-31 08:11:18 -07001144// return a non-0 dependency if the dependency argument must be set
1145spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001146 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001147{
1148 spv::LoopControlMask control = spv::LoopControlMaskNone;
1149
1150 if (loopNode.getDontUnroll())
1151 control = control | spv::LoopControlDontUnrollMask;
1152 if (loopNode.getUnroll())
1153 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001154 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001155 control = control | spv::LoopControlDependencyInfiniteMask;
1156 else if (loopNode.getLoopDependency() > 0) {
1157 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001158 operands.push_back((unsigned int)loopNode.getLoopDependency());
1159 }
1160 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1161 if (loopNode.getMinIterations() > 0) {
1162 control = control | spv::LoopControlMinIterationsMask;
1163 operands.push_back(loopNode.getMinIterations());
1164 }
1165 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1166 control = control | spv::LoopControlMaxIterationsMask;
1167 operands.push_back(loopNode.getMaxIterations());
1168 }
1169 if (loopNode.getIterationMultiple() > 1) {
1170 control = control | spv::LoopControlIterationMultipleMask;
1171 operands.push_back(loopNode.getIterationMultiple());
1172 }
1173 if (loopNode.getPeelCount() > 0) {
1174 control = control | spv::LoopControlPeelCountMask;
1175 operands.push_back(loopNode.getPeelCount());
1176 }
1177 if (loopNode.getPartialCount() > 0) {
1178 control = control | spv::LoopControlPartialCountMask;
1179 operands.push_back(loopNode.getPartialCount());
1180 }
John Kessenicha2858d92018-01-31 08:11:18 -07001181 }
John Kesseniche18fd202018-01-30 11:01:39 -07001182
1183 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001184}
1185
John Kessenicha5c5fb62017-05-05 05:09:58 -06001186// Translate glslang type to SPIR-V storage class.
1187spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1188{
Torosdagli06c2eee2020-03-19 11:09:57 -04001189 if (type.getBasicType() == glslang::EbtRayQuery)
Neslisah Torosdagli054b5e32020-03-26 12:24:31 -04001190 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001191 if (type.getQualifier().isPipeInput())
1192 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001193 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001194 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001195
1196 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001197 type.getQualifier().storage == glslang::EvqUniform) {
John Kessenichdeec1932019-08-13 08:00:30 -06001198 if (type.isAtomic())
John Kessenichbed4e4f2017-09-08 02:38:07 -06001199 return spv::StorageClassAtomicCounter;
1200 if (type.containsOpaque())
1201 return spv::StorageClassUniformConstant;
1202 }
1203
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001204 if (type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001205 type.getQualifier().isShaderRecord()) {
1206 return spv::StorageClassShaderRecordBufferKHR;
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001207 }
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001208
John Kessenichbed4e4f2017-09-08 02:38:07 -06001209 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001210 builder.addIncorporatedExtension(spv::E_SPV_KHR_storage_buffer_storage_class, spv::Spv_1_3);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001211 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001212 }
1213
1214 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich7015bd62019-08-01 03:28:08 -06001215 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001216 return spv::StorageClassPushConstant;
1217 if (type.getBasicType() == glslang::EbtBlock)
1218 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001219 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001220 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001221
1222 switch (type.getQualifier().storage) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001223 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1224 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1225 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenichdeec1932019-08-13 08:00:30 -06001226 case glslang::EvqShared: return spv::StorageClassWorkgroup;
John Kessenich3dd1ce52019-10-17 07:08:40 -06001227#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -04001228 case glslang::EvqPayload: return spv::StorageClassRayPayloadKHR;
1229 case glslang::EvqPayloadIn: return spv::StorageClassIncomingRayPayloadKHR;
1230 case glslang::EvqHitAttr: return spv::StorageClassHitAttributeKHR;
1231 case glslang::EvqCallableData: return spv::StorageClassCallableDataKHR;
1232 case glslang::EvqCallableDataIn: return spv::StorageClassIncomingCallableDataKHR;
Chao Chenb50c02e2018-09-19 11:42:24 -07001233#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001234 default:
1235 assert(0);
1236 break;
1237 }
1238
1239 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001240}
1241
John Kessenich5611c6d2018-04-05 11:25:02 -06001242// Add capabilities pertaining to how an array is indexed.
1243void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1244 const glslang::TType& indexType)
1245{
John Kessenichb9197c82019-08-11 07:41:45 -06001246#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06001247 if (indexType.getQualifier().isNonUniform()) {
1248 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001249 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001250 if (baseType.getBasicType() == glslang::EbtSampler) {
1251 if (baseType.getQualifier().hasAttachment())
1252 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001253 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001254 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001255 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001256 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1257 else if (baseType.isImage())
1258 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1259 else if (baseType.isTexture())
1260 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1261 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1262 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1263 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1264 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1265 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1266 }
1267 } else {
1268 // assume a dynamically uniform index
1269 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001270 if (baseType.getQualifier().hasAttachment()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001271 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001272 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001273 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001274 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001275 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001276 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001277 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001278 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001279 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001280 }
1281 }
John Kessenichb9197c82019-08-11 07:41:45 -06001282#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06001283}
1284
qining25262b32016-05-06 17:25:16 -04001285// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001286// descriptor set.
1287bool IsDescriptorResource(const glslang::TType& type)
1288{
John Kessenichf7497e22016-03-08 21:36:22 -07001289 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001290 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001291 return type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001292 ! type.getQualifier().isShaderRecord() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001293 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001294
1295 // non block...
1296 // basically samplerXXX/subpass/sampler/texture are all included
1297 // if they are the global-scope-class, not the function parameter
1298 // (or local, if they ever exist) class.
alelenv999d4fd2020-06-01 23:24:41 -07001299 if (type.getBasicType() == glslang::EbtSampler ||
1300 type.getBasicType() == glslang::EbtAccStruct)
John Kessenich6c292d32016-02-15 20:58:50 -07001301 return type.getQualifier().isUniformOrBuffer();
1302
1303 // None of the above.
1304 return false;
1305}
1306
John Kesseniche0b6cad2015-12-24 10:30:13 -07001307void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1308{
1309 if (child.layoutMatrix == glslang::ElmNone)
1310 child.layoutMatrix = parent.layoutMatrix;
1311
1312 if (parent.invariant)
1313 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001314 if (parent.flat)
1315 child.flat = true;
1316 if (parent.centroid)
1317 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001318#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001319 if (parent.nopersp)
1320 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001321 if (parent.explicitInterp)
1322 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001323 if (parent.perPrimitiveNV)
1324 child.perPrimitiveNV = true;
1325 if (parent.perViewNV)
1326 child.perViewNV = true;
1327 if (parent.perTaskNV)
1328 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001329 if (parent.patch)
1330 child.patch = true;
1331 if (parent.sample)
1332 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001333 if (parent.coherent)
1334 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001335 if (parent.devicecoherent)
1336 child.devicecoherent = true;
1337 if (parent.queuefamilycoherent)
1338 child.queuefamilycoherent = true;
1339 if (parent.workgroupcoherent)
1340 child.workgroupcoherent = true;
1341 if (parent.subgroupcoherent)
1342 child.subgroupcoherent = true;
Daniel Kochdb32b242020-03-17 20:42:47 -04001343 if (parent.shadercallcoherent)
1344 child.shadercallcoherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001345 if (parent.nonprivate)
1346 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001347 if (parent.volatil)
1348 child.volatil = true;
1349 if (parent.restrict)
1350 child.restrict = true;
1351 if (parent.readonly)
1352 child.readonly = true;
1353 if (parent.writeonly)
1354 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001355#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001356}
1357
John Kessenichf2b7f332016-09-01 17:05:23 -06001358bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001359{
John Kessenich7b9fa252016-01-21 18:56:57 -07001360 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001361 // - struct members might inherit from a struct declaration
1362 // (note that non-block structs don't explicitly inherit,
1363 // only implicitly, meaning no decoration involved)
1364 // - affect decorations on the struct members
1365 // (note smooth does not, and expecting something like volatile
1366 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001367 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001368 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001369}
1370
John Kessenich140f3df2015-06-26 16:58:36 -06001371//
1372// Implement the TGlslangToSpvTraverser class.
1373//
1374
John Kessenich8985fc92020-03-03 10:25:07 -07001375TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion,
1376 const glslang::TIntermediate* glslangIntermediate,
1377 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options) :
1378 TIntermTraverser(true, false, true),
1379 options(options),
1380 shaderEntry(nullptr), currentFunction(nullptr),
1381 sequenceDepth(0), logger(buildLogger),
1382 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
1383 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
1384 glslangIntermediate(glslangIntermediate),
Jeff Bolz04d73732019-05-31 13:06:01 -05001385 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp()),
1386 nonSemanticDebugPrintf(0)
John Kessenich140f3df2015-06-26 16:58:36 -06001387{
1388 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1389
1390 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001391 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1392 glslangIntermediate->getVersion());
1393
John Kessenich121853f2017-05-31 17:11:16 -06001394 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001395 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001396 builder.setSourceFile(glslangIntermediate->getSourceFile());
1397
1398 // Set the source shader's text. If for SPV version 1.0, include
1399 // a preamble in comments stating the OpModuleProcessed instructions.
1400 // Otherwise, emit those as actual instructions.
1401 std::string text;
1402 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1403 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001404 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001405 text.append("// OpModuleProcessed ");
1406 text.append(processes[p]);
1407 text.append("\n");
1408 } else
1409 builder.addModuleProcessed(processes[p]);
1410 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001411 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001412 text.append("#line 1\n");
1413 text.append(glslangIntermediate->getSourceText());
1414 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001415 // Pass name and text for all included files
1416 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1417 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1418 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001419 }
John Kessenich140f3df2015-06-26 16:58:36 -06001420 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001421
1422 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1423 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1424
1425 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1426 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
John Kessenich1ff0c182019-10-10 12:01:13 -06001427 builder.addIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001428 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
John Kessenich8985fc92020-03-03 10:25:07 -07001429 }
Jeff Bolz36831c92018-09-05 10:11:41 -05001430 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001431 memoryModel = spv::MemoryModelVulkanKHR;
1432 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001433 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001434 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001435 builder.setMemoryModel(addressingModel, memoryModel);
1436
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001437 if (glslangIntermediate->usingVariablePointers()) {
1438 builder.addCapability(spv::CapabilityVariablePointers);
1439 }
1440
John Kessenicheee9d532016-09-19 18:09:30 -06001441 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1442 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001443
1444 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001445 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1446 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
johnkslang01384722020-08-14 08:40:06 -06001447 builder.addSourceExtension(it->c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001448
1449 // Add the top-level modes for this shader.
1450
John Kessenich92187592016-02-01 13:45:25 -07001451 if (glslangIntermediate->getXfbMode()) {
1452 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001453 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001454 }
John Kessenich140f3df2015-06-26 16:58:36 -06001455
alelenv59216d52020-05-21 04:38:41 -07001456 if (glslangIntermediate->getLayoutPrimitiveCulling()) {
alelenv75de1962020-04-08 21:09:20 -07001457 builder.addCapability(spv::CapabilityRayTraversalPrimitiveCullingProvisionalKHR);
1458 }
1459
John Kessenich140f3df2015-06-26 16:58:36 -06001460 unsigned int mode;
1461 switch (glslangIntermediate->getStage()) {
1462 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001463 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001464 break;
1465
John Kessenicha28f7a72019-08-06 07:00:58 -06001466 case EShLangFragment:
1467 builder.addCapability(spv::CapabilityShader);
1468 if (glslangIntermediate->getPixelCenterInteger())
1469 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1470
1471 if (glslangIntermediate->getOriginUpperLeft())
1472 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1473 else
1474 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1475
1476 if (glslangIntermediate->getEarlyFragmentTests())
1477 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1478
1479 if (glslangIntermediate->getPostDepthCoverage()) {
1480 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1481 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1482 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1483 }
1484
John Kessenichb9197c82019-08-11 07:41:45 -06001485 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1486 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1487
1488#ifndef GLSLANG_WEB
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001489
John Kessenicha28f7a72019-08-06 07:00:58 -06001490 switch(glslangIntermediate->getDepth()) {
1491 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1492 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1493 default: mode = spv::ExecutionModeMax; break;
1494 }
1495 if (mode != spv::ExecutionModeMax)
1496 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001497 switch (glslangIntermediate->getInterlockOrdering()) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001498 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT;
1499 break;
1500 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT;
1501 break;
1502 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT;
1503 break;
1504 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT;
1505 break;
1506 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT;
1507 break;
1508 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT;
1509 break;
1510 default: mode = spv::ExecutionModeMax;
1511 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001512 }
1513 if (mode != spv::ExecutionModeMax) {
1514 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1515 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1516 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1517 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1518 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1519 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1520 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1521 } else {
1522 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1523 }
1524 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1525 }
John Kessenichb9197c82019-08-11 07:41:45 -06001526#endif
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001527 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001528
John Kessenicha28f7a72019-08-06 07:00:58 -06001529 case EShLangCompute:
1530 builder.addCapability(spv::CapabilityShader);
1531 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1532 glslangIntermediate->getLocalSize(1),
1533 glslangIntermediate->getLocalSize(2));
1534 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1535 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1536 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1537 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1538 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1539 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1540 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1541 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1542 }
1543 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001544#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001545 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001546 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001547 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001548
steve-lunarge7412492017-03-23 11:56:07 -06001549 glslang::TLayoutGeometry primitive;
1550
1551 if (glslangIntermediate->getStage() == EShLangTessControl) {
John Kessenich8985fc92020-03-03 10:25:07 -07001552 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1553 glslangIntermediate->getVertices());
steve-lunarge7412492017-03-23 11:56:07 -06001554 primitive = glslangIntermediate->getOutputPrimitive();
1555 } else {
1556 primitive = glslangIntermediate->getInputPrimitive();
1557 }
1558
1559 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001560 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1561 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1562 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001563 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001564 }
John Kessenich4016e382016-07-15 11:53:56 -06001565 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001566 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1567
John Kesseniche6903322015-10-13 16:29:02 -06001568 switch (glslangIntermediate->getVertexSpacing()) {
1569 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1570 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1571 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001572 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001573 }
John Kessenich4016e382016-07-15 11:53:56 -06001574 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001575 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1576
1577 switch (glslangIntermediate->getVertexOrder()) {
1578 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1579 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001580 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001581 }
John Kessenich4016e382016-07-15 11:53:56 -06001582 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001583 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1584
1585 if (glslangIntermediate->getPointMode())
1586 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001587 break;
1588
1589 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001590 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001591 switch (glslangIntermediate->getInputPrimitive()) {
1592 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1593 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1594 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001595 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001596 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001597 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001598 }
John Kessenich4016e382016-07-15 11:53:56 -06001599 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001600 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001601
John Kessenich140f3df2015-06-26 16:58:36 -06001602 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1603
1604 switch (glslangIntermediate->getOutputPrimitive()) {
1605 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1606 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1607 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001608 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001609 }
John Kessenich4016e382016-07-15 11:53:56 -06001610 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001611 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1612 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1613 break;
1614
Daniel Kochdb32b242020-03-17 20:42:47 -04001615 case EShLangRayGen:
1616 case EShLangIntersect:
1617 case EShLangAnyHit:
1618 case EShLangClosestHit:
1619 case EShLangMiss:
1620 case EShLangCallable:
1621 {
1622 auto& extensions = glslangIntermediate->getRequestedExtensions();
1623 if (extensions.find("GL_NV_ray_tracing") == extensions.end()) {
1624 builder.addCapability(spv::CapabilityRayTracingProvisionalKHR);
1625 builder.addExtension("SPV_KHR_ray_tracing");
1626 }
1627 else {
1628 builder.addCapability(spv::CapabilityRayTracingNV);
1629 builder.addExtension("SPV_NV_ray_tracing");
1630 }
Chao Chenb50c02e2018-09-19 11:42:24 -07001631 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04001632 }
Chao Chen3c366992018-09-19 11:41:59 -07001633 case EShLangTaskNV:
1634 case EShLangMeshNV:
1635 builder.addCapability(spv::CapabilityMeshShadingNV);
1636 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1637 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1638 glslangIntermediate->getLocalSize(1),
1639 glslangIntermediate->getLocalSize(2));
1640 if (glslangIntermediate->getStage() == EShLangMeshNV) {
John Kessenich8985fc92020-03-03 10:25:07 -07001641 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1642 glslangIntermediate->getVertices());
1643 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV,
1644 glslangIntermediate->getPrimitives());
Chao Chen3c366992018-09-19 11:41:59 -07001645
1646 switch (glslangIntermediate->getOutputPrimitive()) {
1647 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1648 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1649 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1650 default: mode = spv::ExecutionModeMax; break;
1651 }
1652 if (mode != spv::ExecutionModeMax)
1653 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1654 }
1655 break;
1656#endif
1657
John Kessenich140f3df2015-06-26 16:58:36 -06001658 default:
1659 break;
1660 }
John Kessenich140f3df2015-06-26 16:58:36 -06001661}
1662
John Kessenichfca82622016-11-26 13:23:20 -07001663// Finish creating SPV, after the traversal is complete.
1664void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001665{
John Kessenichf04c51b2018-08-03 15:56:12 -06001666 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001667 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001668 builder.setBuildPoint(shaderEntry->getLastBlock());
1669 builder.leaveFunction();
1670 }
1671
John Kessenich7ba63412015-12-20 17:37:07 -07001672 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001673 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1674 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001675
David Neto8c3d5b42019-10-21 14:50:31 -04001676 // Add capabilities, extensions, remove unneeded decorations, etc.,
John Kessenichf04c51b2018-08-03 15:56:12 -06001677 // based on the resulting SPIR-V.
David Neto8c3d5b42019-10-21 14:50:31 -04001678 // Note: WebGPU code generation must have the opportunity to aggressively
1679 // prune unreachable merge blocks and continue targets.
John Kessenichf04c51b2018-08-03 15:56:12 -06001680 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001681}
1682
John Kessenichfca82622016-11-26 13:23:20 -07001683// Write the SPV into 'out'.
1684void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001685{
John Kessenichfca82622016-11-26 13:23:20 -07001686 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001687}
1688
1689//
1690// Implement the traversal functions.
1691//
1692// Return true from interior nodes to have the external traversal
1693// continue on to children. Return false if children were
1694// already processed.
1695//
1696
1697//
qining25262b32016-05-06 17:25:16 -04001698// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001699// - uniform/input reads
1700// - output writes
1701// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1702// - something simple that degenerates into the last bullet
1703//
1704void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1705{
qining75d1d802016-04-06 14:42:01 -04001706 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
Roy05a5b532020-01-03 16:21:34 +08001707 if (symbol->getType().isStruct())
1708 glslangTypeToIdMap[symbol->getType().getStruct()] = symbol->getId();
1709
qining75d1d802016-04-06 14:42:01 -04001710 if (symbol->getType().getQualifier().isSpecConstant())
1711 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1712
John Kessenich140f3df2015-06-26 16:58:36 -06001713 // getSymbolId() will set up all the IO decorations on the first call.
1714 // Formal function parameters were mapped during makeFunctions().
1715 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001716
John Kessenich7ba63412015-12-20 17:37:07 -07001717 if (builder.isPointer(id)) {
John Kessenichc30d3352020-06-10 07:15:24 -06001718 if (!symbol->getType().getQualifier().isParamInput() &&
1719 !symbol->getType().getQualifier().isParamOutput()) {
1720 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1721 // Consider adding to the OpEntryPoint interface list.
1722 // Only looking at structures if they have at least one member.
1723 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1724 spv::StorageClass sc = builder.getStorageClass(id);
1725 // Before SPIR-V 1.4, we only want to include Input and Output.
1726 // Starting with SPIR-V 1.4, we want all globals.
John Kessenich4e13c902020-07-13 00:35:58 -06001727 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && builder.isGlobalStorage(id)) ||
John Kessenichc30d3352020-06-10 07:15:24 -06001728 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
1729 iOSet.insert(id);
1730 }
John Kessenich7c7731e2019-01-04 16:47:06 +07001731 }
John Kessenich5f77d862017-09-19 11:09:59 -06001732 }
John Kessenich9c14f772019-06-17 08:38:35 -06001733
Daniel Kochdb32b242020-03-17 20:42:47 -04001734 // If the SPIR-V type is required to be different than the AST type
1735 // (for ex SubgroupMasks or 3x4 ObjectToWorld/WorldToObject matrices),
John Kessenich9c14f772019-06-17 08:38:35 -06001736 // translate now from the SPIR-V type to the AST type, for the consuming
1737 // operation.
1738 // Note this turns it from an l-value to an r-value.
1739 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1740 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1741 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001742 }
1743
1744 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001745 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001746 // Prepare to generate code for the access
1747
1748 // L-value chains will be computed left to right. We're on the symbol now,
1749 // which is the left-most part of the access chain, so now is "clear" time,
1750 // followed by setting the base.
1751 builder.clearAccessChain();
1752
1753 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001754 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001755 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001756 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001757 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001758 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001759 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001760 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001761 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1762 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001763 builder.setAccessChainRValue(id);
1764 else
1765 builder.setAccessChainLValue(id);
1766 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001767
John Kessenichb9197c82019-08-11 07:41:45 -06001768#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001769 // Process linkage-only nodes for any special additional interface work.
1770 if (linkageOnly) {
1771 if (glslangIntermediate->getHlslFunctionality1()) {
1772 // Map implicit counter buffers to their originating buffers, which should have been
1773 // seen by now, given earlier pruning of unused counters, and preservation of order
1774 // of declaration.
1775 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1776 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1777 // Save possible originating buffers for counter buffers, keyed by
1778 // making the potential counter-buffer name.
1779 std::string keyName = symbol->getName().c_str();
1780 keyName = glslangIntermediate->addCounterBufferName(keyName);
1781 counterOriginator[keyName] = symbol;
1782 } else {
1783 // Handle a counter buffer, by finding the saved originating buffer.
1784 std::string keyName = symbol->getName().c_str();
1785 auto it = counterOriginator.find(keyName);
1786 if (it != counterOriginator.end()) {
1787 id = getSymbolId(it->second);
1788 if (id != spv::NoResult) {
1789 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001790 if (counterId != spv::NoResult) {
1791 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001792 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001793 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001794 }
1795 }
1796 }
1797 }
1798 }
1799 }
John Kessenich155d3512019-08-08 23:29:20 -06001800#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001801}
1802
1803bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1804{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001805 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Roy05a5b532020-01-03 16:21:34 +08001806 if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
1807 glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
1808 }
1809 if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
1810 glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
1811 }
John Kesseniche485c7a2017-05-31 18:50:53 -06001812
qining40887662016-04-03 22:20:42 -04001813 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1814 if (node->getType().getQualifier().isSpecConstant())
1815 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1816
John Kessenich140f3df2015-06-26 16:58:36 -06001817 // First, handle special cases
1818 switch (node->getOp()) {
1819 case glslang::EOpAssign:
1820 case glslang::EOpAddAssign:
1821 case glslang::EOpSubAssign:
1822 case glslang::EOpMulAssign:
1823 case glslang::EOpVectorTimesMatrixAssign:
1824 case glslang::EOpVectorTimesScalarAssign:
1825 case glslang::EOpMatrixTimesScalarAssign:
1826 case glslang::EOpMatrixTimesMatrixAssign:
1827 case glslang::EOpDivAssign:
1828 case glslang::EOpModAssign:
1829 case glslang::EOpAndAssign:
1830 case glslang::EOpInclusiveOrAssign:
1831 case glslang::EOpExclusiveOrAssign:
1832 case glslang::EOpLeftShiftAssign:
1833 case glslang::EOpRightShiftAssign:
1834 // A bin-op assign "a += b" means the same thing as "a = a + b"
1835 // where a is evaluated before b. For a simple assignment, GLSL
1836 // says to evaluate the left before the right. So, always, left
1837 // node then right node.
1838 {
1839 // get the left l-value, save it away
1840 builder.clearAccessChain();
1841 node->getLeft()->traverse(this);
1842 spv::Builder::AccessChain lValue = builder.getAccessChain();
1843
1844 // evaluate the right
1845 builder.clearAccessChain();
1846 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001847 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001848
1849 if (node->getOp() != glslang::EOpAssign) {
1850 // the left is also an r-value
1851 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001852 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001853
1854 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001855 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001856 TranslateNoContractionDecoration(node->getType().getQualifier()),
1857 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001858 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001859 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1860 node->getType().getBasicType());
1861
1862 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001863 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001864 }
1865
1866 // store the result
1867 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001868 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001869
1870 // assignments are expressions having an rValue after they are evaluated...
1871 builder.clearAccessChain();
1872 builder.setAccessChainRValue(rValue);
1873 }
1874 return false;
1875 case glslang::EOpIndexDirect:
1876 case glslang::EOpIndexDirectStruct:
1877 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001878 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001879 // Get the left part of the access chain.
1880 node->getLeft()->traverse(this);
1881
1882 // Add the next element in the chain
1883
David Netoa901ffe2016-06-08 14:11:40 +01001884 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001885 if (! node->getLeft()->getType().isArray() &&
1886 node->getLeft()->getType().isVector() &&
1887 node->getOp() == glslang::EOpIndexDirect) {
1888 // This is essentially a hard-coded vector swizzle of size 1,
1889 // so short circuit the access-chain stuff with a swizzle.
1890 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001891 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001892 int dummySize;
1893 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1894 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001895 glslangIntermediate->getBaseAlignmentScalar(
1896 node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001897 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001898
1899 // Load through a block reference is performed with a dot operator that
1900 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1901 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001902 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001903 !node->getLeft()->getType().isArray() &&
1904 node->getOp() == glslang::EOpIndexDirectStruct)
1905 {
1906 spv::Id left = accessChainLoad(node->getLeft()->getType());
1907 builder.clearAccessChain();
1908 builder.setAccessChainLValue(left);
1909 }
1910
David Netoa901ffe2016-06-08 14:11:40 +01001911 int spvIndex = glslangIndex;
1912 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1913 node->getOp() == glslang::EOpIndexDirectStruct)
1914 {
1915 // This may be, e.g., an anonymous block-member selection, which generally need
1916 // index remapping due to hidden members in anonymous blocks.
Roy05a5b532020-01-03 16:21:34 +08001917 int glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
1918 if (memberRemapper.find(glslangId) != memberRemapper.end()) {
1919 std::vector<int>& remapper = memberRemapper[glslangId];
1920 assert(remapper.size() > 0);
1921 spvIndex = remapper[glslangIndex];
1922 }
David Netoa901ffe2016-06-08 14:11:40 +01001923 }
John Kessenichebb50532016-05-16 19:22:05 -06001924
David Netoa901ffe2016-06-08 14:11:40 +01001925 // normal case for indexing array or structure or block
John Kessenich8985fc92020-03-03 10:25:07 -07001926 builder.accessChainPush(builder.makeIntConstant(spvIndex),
1927 TranslateCoherent(node->getLeft()->getType()),
1928 node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001929
1930 // Add capabilities here for accessing PointSize and clip/cull distance.
1931 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001932 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001933 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001934 }
1935 }
1936 return false;
1937 case glslang::EOpIndexIndirect:
1938 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001939 // Array, matrix, or vector indirection with variable index.
1940 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001941 // matrices are arrays of vectors, so will also work for a matrix.
1942 // Will use the access chain's 'component' for variable index into a vector.
1943
1944 // This adapter is building access chains left to right.
1945 // Set up the access chain to the left.
1946 node->getLeft()->traverse(this);
1947
1948 // save it so that computing the right side doesn't trash it
1949 spv::Builder::AccessChain partial = builder.getAccessChain();
1950
1951 // compute the next index in the chain
1952 builder.clearAccessChain();
1953 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001954 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001955
John Kessenich5611c6d2018-04-05 11:25:02 -06001956 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1957
John Kessenich140f3df2015-06-26 16:58:36 -06001958 // restore the saved access chain
1959 builder.setAccessChain(partial);
1960
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001961 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1962 int dummySize;
1963 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1964 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001965 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1966 dummySize));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001967 } else
John Kessenich8985fc92020-03-03 10:25:07 -07001968 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()),
1969 node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001970 }
1971 return false;
1972 case glslang::EOpVectorSwizzle:
1973 {
1974 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001975 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001976 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001977 int dummySize;
1978 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1979 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001980 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1981 dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001982 }
1983 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001984 case glslang::EOpMatrixSwizzle:
1985 logger->missingFunctionality("matrix swizzle");
1986 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001987 case glslang::EOpLogicalOr:
1988 case glslang::EOpLogicalAnd:
1989 {
1990
1991 // These may require short circuiting, but can sometimes be done as straight
1992 // binary operations. The right operand must be short circuited if it has
1993 // side effects, and should probably be if it is complex.
1994 if (isTrivial(node->getRight()->getAsTyped()))
1995 break; // handle below as a normal binary operation
1996 // otherwise, we need to do dynamic short circuiting on the right operand
John Kessenich8985fc92020-03-03 10:25:07 -07001997 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(),
1998 *node->getRight()->getAsTyped());
John Kessenich7c1aa102015-10-15 13:29:11 -06001999 builder.clearAccessChain();
2000 builder.setAccessChainRValue(result);
2001 }
2002 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06002003 default:
2004 break;
2005 }
2006
2007 // Assume generic binary op...
2008
John Kessenich32cfd492016-02-02 12:37:46 -07002009 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06002010 builder.clearAccessChain();
2011 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002012 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002013
John Kessenich32cfd492016-02-02 12:37:46 -07002014 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06002015 builder.clearAccessChain();
2016 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002017 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002018
John Kessenich32cfd492016-02-02 12:37:46 -07002019 // get result
John Kessenichead86222018-03-28 18:01:20 -06002020 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002021 TranslateNoContractionDecoration(node->getType().getQualifier()),
2022 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002023 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07002024 convertGlslangToSpvType(node->getType()), left, right,
2025 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002026
John Kessenich50e57562015-12-21 21:21:11 -07002027 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06002028 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002029 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07002030 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06002031 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06002032 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06002033 return false;
2034 }
John Kessenich140f3df2015-06-26 16:58:36 -06002035}
2036
John Kessenich9c14f772019-06-17 08:38:35 -06002037// Figure out what, if any, type changes are needed when accessing a specific built-in.
2038// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
2039// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
Daniel Kochdb32b242020-03-17 20:42:47 -04002040std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(glslang::TBuiltInVariable glslangBuiltIn,
John Kessenich9c14f772019-06-17 08:38:35 -06002041 const glslang::TType& glslangType)
2042{
Daniel Kochdb32b242020-03-17 20:42:47 -04002043 switch(glslangBuiltIn)
John Kessenich9c14f772019-06-17 08:38:35 -06002044 {
Daniel Kochdb32b242020-03-17 20:42:47 -04002045 case glslang::EbvSubGroupEqMask:
2046 case glslang::EbvSubGroupGeMask:
2047 case glslang::EbvSubGroupGtMask:
2048 case glslang::EbvSubGroupLeMask:
2049 case glslang::EbvSubGroupLtMask: {
John Kessenich9c14f772019-06-17 08:38:35 -06002050 // these require changing a 64-bit scaler -> a vector of 32-bit components
2051 if (glslangType.isVector())
2052 break;
2053 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
2054 builder.makeUintType(64));
2055 return ret;
2056 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002057 // There are no SPIR-V builtins defined for these and map onto original non-transposed
2058 // builtins. During visitBinary we insert a transpose
2059 case glslang::EbvWorldToObject3x4:
2060 case glslang::EbvObjectToWorld3x4: {
John Kessenichf80ef742020-07-14 01:44:35 -06002061 spv::Id mat43 = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
2062 spv::Id mat34 = builder.makeMatrixType(builder.makeFloatType(32), 3, 4);
2063 std::pair<spv::Id, spv::Id> ret(mat43, mat34);
Daniel Kochdb32b242020-03-17 20:42:47 -04002064 return ret;
2065 }
John Kessenich9c14f772019-06-17 08:38:35 -06002066 default:
2067 break;
2068 }
2069
2070 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2071 return ret;
2072}
2073
2074// For an object previously identified (see getForcedType() and forceType)
2075// as needing type translations, do the translation needed for a load, turning
2076// an L-value into in R-value.
2077spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2078{
2079 const auto forceIt = forceType.find(object);
2080 if (forceIt == forceType.end())
2081 return object;
2082
2083 spv::Id desiredTypeId = forceIt->second;
2084 spv::Id objectTypeId = builder.getTypeId(object);
2085 assert(builder.isPointerType(objectTypeId));
2086 objectTypeId = builder.getContainedTypeId(objectTypeId);
2087 if (builder.isVectorType(objectTypeId) &&
2088 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2089 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2090 // handle 32-bit v.xy* -> 64-bit
2091 builder.clearAccessChain();
2092 builder.setAccessChainLValue(object);
2093 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2094 std::vector<spv::Id> components;
2095 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2096 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2097
2098 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2099 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2100 builder.createCompositeConstruct(vecType, components));
2101 } else {
2102 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2103 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002104 } else if (builder.isMatrixType(objectTypeId)) {
2105 // There are no SPIR-V builtins defined for 3x4 variants of ObjectToWorld/WorldToObject
2106 // and we insert a transpose after loading the original non-transposed builtins
2107 builder.clearAccessChain();
2108 builder.setAccessChainLValue(object);
2109 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2110 return builder.createUnaryOp(spv::OpTranspose, desiredTypeId, object);
2111
2112 } else {
John Kessenich9c14f772019-06-17 08:38:35 -06002113 logger->missingFunctionality("forcing non 32-bit vector type");
2114 }
2115
2116 return object;
2117}
2118
John Kessenich140f3df2015-06-26 16:58:36 -06002119bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2120{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002121 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002122
qining40887662016-04-03 22:20:42 -04002123 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2124 if (node->getType().getQualifier().isSpecConstant())
2125 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2126
John Kessenichfc51d282015-08-19 13:34:18 -06002127 spv::Id result = spv::NoResult;
2128
2129 // try texturing first
2130 result = createImageTextureFunctionCall(node);
2131 if (result != spv::NoResult) {
2132 builder.clearAccessChain();
2133 builder.setAccessChainRValue(result);
2134
2135 return false; // done with this node
2136 }
2137
2138 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002139
2140 if (node->getOp() == glslang::EOpArrayLength) {
2141 // Quite special; won't want to evaluate the operand.
2142
John Kessenich5611c6d2018-04-05 11:25:02 -06002143 // Currently, the front-end does not allow .length() on an array until it is sized,
2144 // except for the last block membeor of an SSBO.
2145 // TODO: If this changes, link-time sized arrays might show up here, and need their
2146 // size extracted.
2147
John Kessenichc9a80832015-09-12 12:17:44 -06002148 // Normal .length() would have been constant folded by the front-end.
2149 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002150 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002151
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002152 spv::Id length;
2153 if (node->getOperand()->getType().isCoopMat()) {
2154 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2155
2156 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2157 assert(builder.isCooperativeMatrixType(typeId));
2158
2159 length = builder.createCooperativeMatrixLength(typeId);
2160 } else {
2161 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2162 block->traverse(this);
John Kessenich8985fc92020-03-03 10:25:07 -07002163 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()
2164 ->getConstArray()[0].getUConst();
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002165 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2166 }
John Kessenichc9a80832015-09-12 12:17:44 -06002167
John Kessenich8c869672018-11-28 07:01:37 -07002168 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2169 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2170 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002171 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2172 if (builder.isInSpecConstCodeGenMode()) {
2173 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2174 } else {
2175 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2176 }
2177 }
John Kessenich8c869672018-11-28 07:01:37 -07002178
John Kessenichc9a80832015-09-12 12:17:44 -06002179 builder.clearAccessChain();
2180 builder.setAccessChainRValue(length);
2181
2182 return false;
2183 }
2184
John Kessenichfc51d282015-08-19 13:34:18 -06002185 // Start by evaluating the operand
2186
John Kessenich8c8505c2016-07-26 12:50:38 -06002187 // Does it need a swizzle inversion? If so, evaluation is inverted;
2188 // operate first on the swizzle base, then apply the swizzle.
2189 spv::Id invertedType = spv::NoType;
John Kessenich8985fc92020-03-03 10:25:07 -07002190 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2191 invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenich8c8505c2016-07-26 12:50:38 -06002192 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2193 invertedType = getInvertedSwizzleType(*node->getOperand());
2194
John Kessenich140f3df2015-06-26 16:58:36 -06002195 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002196 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002197 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002198 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002199 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002200 operandNode = node->getOperand();
2201
2202 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002203
Rex Xufc618912015-09-09 16:42:49 +08002204 spv::Id operand = spv::NoResult;
2205
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002206 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2207
John Kessenichfb4f2332019-08-09 03:49:15 -06002208#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002209 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2210 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002211 node->getOp() == glslang::EOpAtomicCounter ||
Neslisah Torosdagli7d37a682020-03-26 10:52:33 -04002212 node->getOp() == glslang::EOpInterpolateAtCentroid ||
2213 node->getOp() == glslang::EOpRayQueryProceed ||
2214 node->getOp() == glslang::EOpRayQueryGetRayTMin ||
2215 node->getOp() == glslang::EOpRayQueryGetRayFlags ||
2216 node->getOp() == glslang::EOpRayQueryGetWorldRayOrigin ||
2217 node->getOp() == glslang::EOpRayQueryGetWorldRayDirection ||
2218 node->getOp() == glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque ||
2219 node->getOp() == glslang::EOpRayQueryTerminate ||
2220 node->getOp() == glslang::EOpRayQueryConfirmIntersection) {
Rex Xufc618912015-09-09 16:42:49 +08002221 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002222 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2223 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2224 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002225#endif
2226 {
John Kessenich32cfd492016-02-02 12:37:46 -07002227 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002228 }
John Kessenich140f3df2015-06-26 16:58:36 -06002229
John Kessenichead86222018-03-28 18:01:20 -06002230 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002231 TranslateNoContractionDecoration(node->getType().getQualifier()),
2232 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002233
2234 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002235 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002236 result = createConversion(node->getOp(), decorations, resultType(), operand,
2237 node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002238
2239 // if not, then possibly an operation
2240 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002241 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand,
2242 node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002243
2244 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002245 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002246 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002247 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002248 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002249
John Kessenich140f3df2015-06-26 16:58:36 -06002250 builder.clearAccessChain();
2251 builder.setAccessChainRValue(result);
2252
2253 return false; // done with this node
2254 }
2255
2256 // it must be a special case, check...
2257 switch (node->getOp()) {
2258 case glslang::EOpPostIncrement:
2259 case glslang::EOpPostDecrement:
2260 case glslang::EOpPreIncrement:
2261 case glslang::EOpPreDecrement:
2262 {
2263 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002264 spv::Id one = 0;
2265 if (node->getBasicType() == glslang::EbtFloat)
2266 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002267#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002268 else if (node->getBasicType() == glslang::EbtDouble)
2269 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002270 else if (node->getBasicType() == glslang::EbtFloat16)
2271 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002272 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2273 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002274 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2275 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002276 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2277 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002278#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002279 else
2280 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002281 glslang::TOperator op;
2282 if (node->getOp() == glslang::EOpPreIncrement ||
2283 node->getOp() == glslang::EOpPostIncrement)
2284 op = glslang::EOpAdd;
2285 else
2286 op = glslang::EOpSub;
2287
John Kessenichead86222018-03-28 18:01:20 -06002288 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002289 convertGlslangToSpvType(node->getType()), operand, one,
2290 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002291 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002292
2293 // The result of operation is always stored, but conditionally the
2294 // consumed result. The consumed result is always an r-value.
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02002295 builder.accessChainStore(result,
2296 TranslateNonUniformDecoration(node->getOperand()->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06002297 builder.clearAccessChain();
2298 if (node->getOp() == glslang::EOpPreIncrement ||
2299 node->getOp() == glslang::EOpPreDecrement)
2300 builder.setAccessChainRValue(result);
2301 else
2302 builder.setAccessChainRValue(operand);
2303 }
2304
2305 return false;
2306
John Kessenich155d3512019-08-08 23:29:20 -06002307#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002308 case glslang::EOpEmitStreamVertex:
2309 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2310 return false;
2311 case glslang::EOpEndStreamPrimitive:
2312 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2313 return false;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002314 case glslang::EOpRayQueryTerminate:
2315 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operand);
2316 return false;
2317 case glslang::EOpRayQueryConfirmIntersection:
2318 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operand);
2319 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002320#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002321
2322 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002323 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002324 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002325 }
John Kessenich140f3df2015-06-26 16:58:36 -06002326}
2327
Jeff Bolz53134492019-06-25 13:31:10 -05002328// Construct a composite object, recursively copying members if their types don't match
2329spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2330{
2331 for (int c = 0; c < (int)constituents.size(); ++c) {
2332 spv::Id& constituent = constituents[c];
2333 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2334 spv::Id rType = builder.getTypeId(constituent);
2335 if (lType != rType) {
2336 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2337 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2338 } else if (builder.isStructType(rType)) {
2339 std::vector<spv::Id> rTypeConstituents;
2340 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2341 for (int i = 0; i < numrTypeConstituents; ++i) {
John Kessenich8985fc92020-03-03 10:25:07 -07002342 rTypeConstituents.push_back(builder.createCompositeExtract(constituent,
2343 builder.getContainedTypeId(rType, i), i));
Jeff Bolz53134492019-06-25 13:31:10 -05002344 }
2345 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2346 } else {
2347 assert(builder.isArrayType(rType));
2348 std::vector<spv::Id> rTypeConstituents;
2349 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2350
2351 spv::Id elementRType = builder.getContainedTypeId(rType);
2352 for (int i = 0; i < numrTypeConstituents; ++i) {
2353 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2354 }
2355 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2356 }
2357 }
2358 }
2359 return builder.createCompositeConstruct(resultTypeId, constituents);
2360}
2361
John Kessenich140f3df2015-06-26 16:58:36 -06002362bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2363{
qining27e04a02016-04-14 16:40:20 -04002364 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2365 if (node->getType().getQualifier().isSpecConstant())
2366 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2367
John Kessenichfc51d282015-08-19 13:34:18 -06002368 spv::Id result = spv::NoResult;
Cody Northrop4d2298b2020-04-13 21:59:49 -06002369 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2370 std::vector<spv::Builder::AccessChain> complexLvalues; // for holding swizzling l-values too complex for
2371 // SPIR-V, for an out parameter
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02002372 std::vector<glslang::TQualifier> complexLValueQualifiers;
Cody Northrop4d2298b2020-04-13 21:59:49 -06002373 std::vector<spv::Id> temporaryLvalues; // temporaries to pass, as proxies for complexLValues
John Kessenichbbbd9a22020-03-03 07:21:37 -07002374
John Kessenich8985fc92020-03-03 10:25:07 -07002375 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2376 invertedType :
2377 convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002378
2379 // try texturing
2380 result = createImageTextureFunctionCall(node);
2381 if (result != spv::NoResult) {
2382 builder.clearAccessChain();
2383 builder.setAccessChainRValue(result);
2384
2385 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002386 }
2387#ifndef GLSLANG_WEB
2388 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002389 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002390 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002391 // "imageStore" is a special case, which has no result
2392 return false;
2393 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002394#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002395
John Kessenich140f3df2015-06-26 16:58:36 -06002396 glslang::TOperator binOp = glslang::EOpNull;
2397 bool reduceComparison = true;
2398 bool isMatrix = false;
2399 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002400 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002401
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002402 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2403
John Kessenich140f3df2015-06-26 16:58:36 -06002404 assert(node->getOp());
2405
John Kessenichf6640762016-08-01 19:44:00 -06002406 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002407
2408 switch (node->getOp()) {
2409 case glslang::EOpSequence:
2410 {
2411 if (preVisit)
2412 ++sequenceDepth;
2413 else
2414 --sequenceDepth;
2415
2416 if (sequenceDepth == 1) {
2417 // If this is the parent node of all the functions, we want to see them
2418 // early, so all call points have actual SPIR-V functions to reference.
2419 // In all cases, still let the traverser visit the children for us.
2420 makeFunctions(node->getAsAggregate()->getSequence());
2421
John Kessenich6fccb3c2016-09-19 16:01:41 -06002422 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002423 // anything else gets there, so visit out of order, doing them all now.
2424 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2425
John Kessenich6a60c2f2016-12-08 21:01:59 -07002426 // 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 -06002427 // so do them manually.
2428 visitFunctions(node->getAsAggregate()->getSequence());
2429
2430 return false;
2431 }
2432
2433 return true;
2434 }
2435 case glslang::EOpLinkerObjects:
2436 {
2437 if (visit == glslang::EvPreVisit)
2438 linkageOnly = true;
2439 else
2440 linkageOnly = false;
2441
2442 return true;
2443 }
2444 case glslang::EOpComma:
2445 {
2446 // processing from left to right naturally leaves the right-most
2447 // lying around in the access chain
2448 glslang::TIntermSequence& glslangOperands = node->getSequence();
2449 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2450 glslangOperands[i]->traverse(this);
2451
2452 return false;
2453 }
2454 case glslang::EOpFunction:
2455 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002456 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002457 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002458 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002459 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002460 } else {
2461 handleFunctionEntry(node);
2462 }
2463 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002464 if (inEntryPoint)
2465 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002466 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002467 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002468 }
2469
2470 return true;
2471 case glslang::EOpParameters:
2472 // Parameters will have been consumed by EOpFunction processing, but not
2473 // the body, so we still visited the function node's children, making this
2474 // child redundant.
2475 return false;
2476 case glslang::EOpFunctionCall:
2477 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002478 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002479 if (node->isUserDefined())
2480 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07002481 if (result) {
2482 builder.clearAccessChain();
2483 builder.setAccessChainRValue(result);
2484 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002485 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002486
2487 return false;
2488 }
2489 case glslang::EOpConstructMat2x2:
2490 case glslang::EOpConstructMat2x3:
2491 case glslang::EOpConstructMat2x4:
2492 case glslang::EOpConstructMat3x2:
2493 case glslang::EOpConstructMat3x3:
2494 case glslang::EOpConstructMat3x4:
2495 case glslang::EOpConstructMat4x2:
2496 case glslang::EOpConstructMat4x3:
2497 case glslang::EOpConstructMat4x4:
2498 case glslang::EOpConstructDMat2x2:
2499 case glslang::EOpConstructDMat2x3:
2500 case glslang::EOpConstructDMat2x4:
2501 case glslang::EOpConstructDMat3x2:
2502 case glslang::EOpConstructDMat3x3:
2503 case glslang::EOpConstructDMat3x4:
2504 case glslang::EOpConstructDMat4x2:
2505 case glslang::EOpConstructDMat4x3:
2506 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002507 case glslang::EOpConstructIMat2x2:
2508 case glslang::EOpConstructIMat2x3:
2509 case glslang::EOpConstructIMat2x4:
2510 case glslang::EOpConstructIMat3x2:
2511 case glslang::EOpConstructIMat3x3:
2512 case glslang::EOpConstructIMat3x4:
2513 case glslang::EOpConstructIMat4x2:
2514 case glslang::EOpConstructIMat4x3:
2515 case glslang::EOpConstructIMat4x4:
2516 case glslang::EOpConstructUMat2x2:
2517 case glslang::EOpConstructUMat2x3:
2518 case glslang::EOpConstructUMat2x4:
2519 case glslang::EOpConstructUMat3x2:
2520 case glslang::EOpConstructUMat3x3:
2521 case glslang::EOpConstructUMat3x4:
2522 case glslang::EOpConstructUMat4x2:
2523 case glslang::EOpConstructUMat4x3:
2524 case glslang::EOpConstructUMat4x4:
2525 case glslang::EOpConstructBMat2x2:
2526 case glslang::EOpConstructBMat2x3:
2527 case glslang::EOpConstructBMat2x4:
2528 case glslang::EOpConstructBMat3x2:
2529 case glslang::EOpConstructBMat3x3:
2530 case glslang::EOpConstructBMat3x4:
2531 case glslang::EOpConstructBMat4x2:
2532 case glslang::EOpConstructBMat4x3:
2533 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002534 case glslang::EOpConstructF16Mat2x2:
2535 case glslang::EOpConstructF16Mat2x3:
2536 case glslang::EOpConstructF16Mat2x4:
2537 case glslang::EOpConstructF16Mat3x2:
2538 case glslang::EOpConstructF16Mat3x3:
2539 case glslang::EOpConstructF16Mat3x4:
2540 case glslang::EOpConstructF16Mat4x2:
2541 case glslang::EOpConstructF16Mat4x3:
2542 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002543 isMatrix = true;
2544 // fall through
2545 case glslang::EOpConstructFloat:
2546 case glslang::EOpConstructVec2:
2547 case glslang::EOpConstructVec3:
2548 case glslang::EOpConstructVec4:
2549 case glslang::EOpConstructDouble:
2550 case glslang::EOpConstructDVec2:
2551 case glslang::EOpConstructDVec3:
2552 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002553 case glslang::EOpConstructFloat16:
2554 case glslang::EOpConstructF16Vec2:
2555 case glslang::EOpConstructF16Vec3:
2556 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002557 case glslang::EOpConstructBool:
2558 case glslang::EOpConstructBVec2:
2559 case glslang::EOpConstructBVec3:
2560 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002561 case glslang::EOpConstructInt8:
2562 case glslang::EOpConstructI8Vec2:
2563 case glslang::EOpConstructI8Vec3:
2564 case glslang::EOpConstructI8Vec4:
2565 case glslang::EOpConstructUint8:
2566 case glslang::EOpConstructU8Vec2:
2567 case glslang::EOpConstructU8Vec3:
2568 case glslang::EOpConstructU8Vec4:
2569 case glslang::EOpConstructInt16:
2570 case glslang::EOpConstructI16Vec2:
2571 case glslang::EOpConstructI16Vec3:
2572 case glslang::EOpConstructI16Vec4:
2573 case glslang::EOpConstructUint16:
2574 case glslang::EOpConstructU16Vec2:
2575 case glslang::EOpConstructU16Vec3:
2576 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002577 case glslang::EOpConstructInt:
2578 case glslang::EOpConstructIVec2:
2579 case glslang::EOpConstructIVec3:
2580 case glslang::EOpConstructIVec4:
2581 case glslang::EOpConstructUint:
2582 case glslang::EOpConstructUVec2:
2583 case glslang::EOpConstructUVec3:
2584 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002585 case glslang::EOpConstructInt64:
2586 case glslang::EOpConstructI64Vec2:
2587 case glslang::EOpConstructI64Vec3:
2588 case glslang::EOpConstructI64Vec4:
2589 case glslang::EOpConstructUint64:
2590 case glslang::EOpConstructU64Vec2:
2591 case glslang::EOpConstructU64Vec3:
2592 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002593 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002594 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002595 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002596 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002597 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002598 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002599 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002600 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002601 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002602 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002603 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002604 else if (node->getOp() == glslang::EOpConstructStruct ||
2605 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2606 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002607 std::vector<spv::Id> constituents;
2608 for (int c = 0; c < (int)arguments.size(); ++c)
2609 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002610 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002611 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002612 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002613 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002614 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002615
2616 builder.clearAccessChain();
2617 builder.setAccessChainRValue(constructed);
2618
2619 return false;
2620 }
2621
2622 // These six are component-wise compares with component-wise results.
2623 // Forward on to createBinaryOperation(), requesting a vector result.
2624 case glslang::EOpLessThan:
2625 case glslang::EOpGreaterThan:
2626 case glslang::EOpLessThanEqual:
2627 case glslang::EOpGreaterThanEqual:
2628 case glslang::EOpVectorEqual:
2629 case glslang::EOpVectorNotEqual:
2630 {
2631 // Map the operation to a binary
2632 binOp = node->getOp();
2633 reduceComparison = false;
2634 switch (node->getOp()) {
2635 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2636 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2637 default: binOp = node->getOp(); break;
2638 }
2639
2640 break;
2641 }
2642 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002643 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002644 binOp = glslang::EOpMul;
2645 break;
2646 case glslang::EOpOuterProduct:
2647 // two vectors multiplied to make a matrix
2648 binOp = glslang::EOpOuterProduct;
2649 break;
2650 case glslang::EOpDot:
2651 {
qining25262b32016-05-06 17:25:16 -04002652 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002653 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002654 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002655 binOp = glslang::EOpMul;
2656 break;
2657 }
2658 case glslang::EOpMod:
2659 // when an aggregate, this is the floating-point mod built-in function,
2660 // which can be emitted by the one in createBinaryOperation()
2661 binOp = glslang::EOpMod;
2662 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002663
John Kessenich140f3df2015-06-26 16:58:36 -06002664 case glslang::EOpEmitVertex:
2665 case glslang::EOpEndPrimitive:
2666 case glslang::EOpBarrier:
2667 case glslang::EOpMemoryBarrier:
2668 case glslang::EOpMemoryBarrierAtomicCounter:
2669 case glslang::EOpMemoryBarrierBuffer:
2670 case glslang::EOpMemoryBarrierImage:
2671 case glslang::EOpMemoryBarrierShared:
2672 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002673 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002674 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002675 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002676 case glslang::EOpWorkgroupMemoryBarrier:
2677 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002678 case glslang::EOpSubgroupBarrier:
2679 case glslang::EOpSubgroupMemoryBarrier:
2680 case glslang::EOpSubgroupMemoryBarrierBuffer:
2681 case glslang::EOpSubgroupMemoryBarrierImage:
2682 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002683 noReturnValue = true;
2684 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2685 break;
2686
John Kessenich426394d2015-07-23 10:22:48 -06002687 case glslang::EOpAtomicAdd:
2688 case glslang::EOpAtomicMin:
2689 case glslang::EOpAtomicMax:
2690 case glslang::EOpAtomicAnd:
2691 case glslang::EOpAtomicOr:
2692 case glslang::EOpAtomicXor:
2693 case glslang::EOpAtomicExchange:
2694 case glslang::EOpAtomicCompSwap:
2695 atomic = true;
2696 break;
2697
John Kesseniche5eee8f2019-10-18 01:03:11 -06002698#ifndef GLSLANG_WEB
2699 case glslang::EOpAtomicStore:
2700 noReturnValue = true;
2701 // fallthrough
2702 case glslang::EOpAtomicLoad:
2703 atomic = true;
2704 break;
2705
John Kessenich0d0c6d32017-07-23 16:08:26 -06002706 case glslang::EOpAtomicCounterAdd:
2707 case glslang::EOpAtomicCounterSubtract:
2708 case glslang::EOpAtomicCounterMin:
2709 case glslang::EOpAtomicCounterMax:
2710 case glslang::EOpAtomicCounterAnd:
2711 case glslang::EOpAtomicCounterOr:
2712 case glslang::EOpAtomicCounterXor:
2713 case glslang::EOpAtomicCounterExchange:
2714 case glslang::EOpAtomicCounterCompSwap:
2715 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2716 builder.addCapability(spv::CapabilityAtomicStorageOps);
2717 atomic = true;
2718 break;
2719
Ian Romanickb3bd4022019-01-21 08:57:25 -08002720 case glslang::EOpAbsDifference:
2721 case glslang::EOpAddSaturate:
2722 case glslang::EOpSubSaturate:
2723 case glslang::EOpAverage:
2724 case glslang::EOpAverageRounded:
2725 case glslang::EOpMul32x16:
2726 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2727 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2728 binOp = node->getOp();
2729 break;
2730
Daniel Kochdb32b242020-03-17 20:42:47 -04002731 case glslang::EOpIgnoreIntersection:
2732 case glslang::EOpTerminateRay:
2733 case glslang::EOpTrace:
2734 case glslang::EOpExecuteCallable:
Chao Chen3c366992018-09-19 11:41:59 -07002735 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2736 noReturnValue = true;
2737 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04002738 case glslang::EOpRayQueryInitialize:
2739 case glslang::EOpRayQueryTerminate:
2740 case glslang::EOpRayQueryGenerateIntersection:
2741 case glslang::EOpRayQueryConfirmIntersection:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002742 builder.addExtension("SPV_KHR_ray_query");
2743 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
Torosdagli06c2eee2020-03-19 11:09:57 -04002744 noReturnValue = true;
2745 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002746 case glslang::EOpRayQueryProceed:
2747 case glslang::EOpRayQueryGetIntersectionType:
2748 case glslang::EOpRayQueryGetRayTMin:
2749 case glslang::EOpRayQueryGetRayFlags:
2750 case glslang::EOpRayQueryGetIntersectionT:
2751 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2752 case glslang::EOpRayQueryGetIntersectionInstanceId:
2753 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2754 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2755 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2756 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2757 case glslang::EOpRayQueryGetIntersectionFrontFace:
2758 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
2759 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2760 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2761 case glslang::EOpRayQueryGetWorldRayDirection:
2762 case glslang::EOpRayQueryGetWorldRayOrigin:
2763 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2764 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2765 builder.addExtension("SPV_KHR_ray_query");
2766 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
2767 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002768 case glslang::EOpCooperativeMatrixLoad:
2769 case glslang::EOpCooperativeMatrixStore:
2770 noReturnValue = true;
2771 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002772 case glslang::EOpBeginInvocationInterlock:
2773 case glslang::EOpEndInvocationInterlock:
2774 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2775 noReturnValue = true;
2776 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002777#endif
Chao Chen3c366992018-09-19 11:41:59 -07002778
Jeff Bolz04d73732019-05-31 13:06:01 -05002779 case glslang::EOpDebugPrintf:
2780 noReturnValue = true;
2781 break;
2782
John Kessenich140f3df2015-06-26 16:58:36 -06002783 default:
2784 break;
2785 }
2786
2787 //
2788 // See if it maps to a regular operation.
2789 //
John Kessenich140f3df2015-06-26 16:58:36 -06002790 if (binOp != glslang::EOpNull) {
2791 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2792 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2793 assert(left && right);
2794
2795 builder.clearAccessChain();
2796 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002797 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002798
2799 builder.clearAccessChain();
2800 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002801 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002802
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002803 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002804 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002805 TranslateNoContractionDecoration(node->getType().getQualifier()),
2806 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002807 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002808 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002809 left->getType().getBasicType(), reduceComparison);
2810
2811 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002812 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002813 builder.clearAccessChain();
2814 builder.setAccessChainRValue(result);
2815
2816 return false;
2817 }
2818
John Kessenich426394d2015-07-23 10:22:48 -06002819 //
2820 // Create the list of operands.
2821 //
John Kessenich140f3df2015-06-26 16:58:36 -06002822 glslang::TIntermSequence& glslangOperands = node->getSequence();
2823 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002824 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002825 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002826 // special case l-value operands; there are just a few
2827 bool lvalue = false;
2828 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002829 case glslang::EOpModf:
2830 if (arg == 1)
2831 lvalue = true;
2832 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002833
Torosdagli06c2eee2020-03-19 11:09:57 -04002834 case glslang::EOpRayQueryInitialize:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002835 case glslang::EOpRayQueryTerminate:
2836 case glslang::EOpRayQueryConfirmIntersection:
2837 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04002838 case glslang::EOpRayQueryGenerateIntersection:
2839 case glslang::EOpRayQueryGetIntersectionType:
2840 case glslang::EOpRayQueryGetIntersectionT:
2841 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2842 case glslang::EOpRayQueryGetIntersectionInstanceId:
2843 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2844 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2845 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2846 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2847 case glslang::EOpRayQueryGetIntersectionFrontFace:
2848 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2849 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2850 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2851 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2852 if (arg == 0)
2853 lvalue = true;
2854 break;
2855
John Kesseniche5eee8f2019-10-18 01:03:11 -06002856 case glslang::EOpAtomicAdd:
2857 case glslang::EOpAtomicMin:
2858 case glslang::EOpAtomicMax:
2859 case glslang::EOpAtomicAnd:
2860 case glslang::EOpAtomicOr:
2861 case glslang::EOpAtomicXor:
2862 case glslang::EOpAtomicExchange:
2863 case glslang::EOpAtomicCompSwap:
2864 if (arg == 0)
2865 lvalue = true;
2866 break;
2867
John Kessenicha28f7a72019-08-06 07:00:58 -06002868#ifndef GLSLANG_WEB
2869 case glslang::EOpFrexp:
2870 if (arg == 1)
2871 lvalue = true;
2872 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002873 case glslang::EOpInterpolateAtSample:
2874 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002875 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002876 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002877 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002878
2879 // Does it need a swizzle inversion? If so, evaluation is inverted;
2880 // operate first on the swizzle base, then apply the swizzle.
John Kessenichbbbd9a22020-03-03 07:21:37 -07002881 // That is, we transform
2882 //
2883 // interpolate(v.zy) -> interpolate(v).zy
2884 //
John Kessenichecba76f2017-01-06 00:34:48 -07002885 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002886 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
John Kessenich8985fc92020-03-03 10:25:07 -07002887 invertedType = convertGlslangToSpvType(
2888 glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
John Kessenich8c8505c2016-07-26 12:50:38 -06002889 }
Rex Xu7a26c172015-12-08 17:12:09 +08002890 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002891 case glslang::EOpAtomicLoad:
2892 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002893 case glslang::EOpAtomicCounterAdd:
2894 case glslang::EOpAtomicCounterSubtract:
2895 case glslang::EOpAtomicCounterMin:
2896 case glslang::EOpAtomicCounterMax:
2897 case glslang::EOpAtomicCounterAnd:
2898 case glslang::EOpAtomicCounterOr:
2899 case glslang::EOpAtomicCounterXor:
2900 case glslang::EOpAtomicCounterExchange:
2901 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002902 if (arg == 0)
2903 lvalue = true;
2904 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002905 case glslang::EOpAddCarry:
2906 case glslang::EOpSubBorrow:
2907 if (arg == 2)
2908 lvalue = true;
2909 break;
2910 case glslang::EOpUMulExtended:
2911 case glslang::EOpIMulExtended:
2912 if (arg >= 2)
2913 lvalue = true;
2914 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002915 case glslang::EOpCooperativeMatrixLoad:
2916 if (arg == 0 || arg == 1)
2917 lvalue = true;
2918 break;
2919 case glslang::EOpCooperativeMatrixStore:
2920 if (arg == 1)
2921 lvalue = true;
2922 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002923#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002924 default:
2925 break;
2926 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002927 builder.clearAccessChain();
2928 if (invertedType != spv::NoType && arg == 0)
2929 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2930 else
2931 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002932
John Kessenichb9197c82019-08-11 07:41:45 -06002933#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002934 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2935 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2936
2937 if (arg == 1) {
2938 // fold "element" parameter into the access chain
2939 spv::Builder::AccessChain save = builder.getAccessChain();
2940 builder.clearAccessChain();
2941 glslangOperands[2]->traverse(this);
2942
2943 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2944
2945 builder.setAccessChain(save);
2946
2947 // Point to the first element of the array.
John Kessenich8985fc92020-03-03 10:25:07 -07002948 builder.accessChainPush(elementId,
2949 TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
2950 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002951
2952 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2953 unsigned int alignment = builder.getAccessChain().alignment;
2954
2955 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2956 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2957 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2958 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2959 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
John Kessenich8985fc92020-03-03 10:25:07 -07002960 if (builder.getStorageClass(builder.getAccessChain().base) ==
2961 spv::StorageClassPhysicalStorageBufferEXT) {
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002962 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2963 }
2964
2965 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2966
2967 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2968 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2969 }
2970
John Kessenich8985fc92020-03-03 10:25:07 -07002971 if (memoryAccess &
2972 (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2973 memoryAccessOperands.push_back(spv::IdImmediate(true,
2974 builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002975 }
2976 } else if (arg == 2) {
2977 continue;
2978 }
2979 }
John Kessenichb9197c82019-08-11 07:41:45 -06002980#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002981
John Kessenichbbbd9a22020-03-03 07:21:37 -07002982 // for l-values, pass the address, for r-values, pass the value
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002983 if (lvalue) {
John Kessenichbbbd9a22020-03-03 07:21:37 -07002984 if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
2985 // SPIR-V cannot represent an l-value containing a swizzle that doesn't
2986 // reduce to a simple access chain. So, we need a temporary vector to
2987 // receive the result, and must later swizzle that into the original
2988 // l-value.
Cody Northrop4d2298b2020-04-13 21:59:49 -06002989 complexLvalues.push_back(builder.getAccessChain());
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02002990 complexLValueQualifiers.push_back(glslangOperands[arg]->getAsTyped()->getType().getQualifier());
John Kessenich435dd802020-06-30 01:27:08 -06002991 temporaryLvalues.push_back(builder.createVariable(
2992 spv::NoPrecision, spv::StorageClassFunction,
Cody Northrop4d2298b2020-04-13 21:59:49 -06002993 builder.accessChainGetInferredType(), "swizzleTemp"));
2994 operands.push_back(temporaryLvalues.back());
John Kessenichbbbd9a22020-03-03 07:21:37 -07002995 } else {
2996 operands.push_back(builder.accessChainGetLValue());
2997 }
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002998 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2999 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
3000 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003001 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Torosdagli06c2eee2020-03-19 11:09:57 -04003002 glslang::TOperator glslangOp = node->getOp();
3003 if (arg == 1 &&
3004 (glslangOp == glslang::EOpRayQueryGetIntersectionType ||
3005 glslangOp == glslang::EOpRayQueryGetIntersectionT ||
3006 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceCustomIndex ||
3007 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceId ||
3008 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset ||
3009 glslangOp == glslang::EOpRayQueryGetIntersectionGeometryIndex ||
3010 glslangOp == glslang::EOpRayQueryGetIntersectionPrimitiveIndex ||
3011 glslangOp == glslang::EOpRayQueryGetIntersectionBarycentrics ||
3012 glslangOp == glslang::EOpRayQueryGetIntersectionFrontFace ||
3013 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayDirection ||
3014 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayOrigin ||
3015 glslangOp == glslang::EOpRayQueryGetIntersectionObjectToWorld ||
3016 glslangOp == glslang::EOpRayQueryGetIntersectionWorldToObject
3017 )) {
3018 bool cond = glslangOperands[arg]->getAsConstantUnion()->getConstArray()[0].getBConst();
3019 operands.push_back(builder.makeIntConstant(cond ? 1 : 0));
3020 }
3021 else {
3022 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
3023 }
3024
John Kesseniche485c7a2017-05-31 18:50:53 -06003025 }
John Kessenich140f3df2015-06-26 16:58:36 -06003026 }
John Kessenich426394d2015-07-23 10:22:48 -06003027
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003028 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06003029#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003030 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
3031 std::vector<spv::IdImmediate> idImmOps;
3032
3033 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
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 // get the pointee type
3038 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
3039 assert(builder.isCooperativeMatrixType(typeId));
3040 // do the op
3041 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
3042 // store the result to the pointer (out param 'm')
3043 builder.createStore(result, operands[0]);
3044 result = 0;
3045 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
3046 std::vector<spv::IdImmediate> idImmOps;
3047
3048 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3049 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
3050 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3051 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3052 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3053
3054 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
3055 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06003056 } else
3057#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06003058 if (atomic) {
3059 // Handle all atomics
John Kessenich8985fc92020-03-03 10:25:07 -07003060 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
3061 lvalueCoherentFlags);
Jeff Bolz04d73732019-05-31 13:06:01 -05003062 } else if (node->getOp() == glslang::EOpDebugPrintf) {
3063 if (!nonSemanticDebugPrintf) {
3064 nonSemanticDebugPrintf = builder.import("NonSemantic.DebugPrintf");
3065 }
3066 result = builder.createBuiltinCall(builder.makeVoidType(), nonSemanticDebugPrintf, spv::NonSemanticDebugPrintfDebugPrintf, operands);
3067 builder.addExtension(spv::E_SPV_KHR_non_semantic_info);
John Kesseniche5eee8f2019-10-18 01:03:11 -06003068 } else {
John Kessenich426394d2015-07-23 10:22:48 -06003069 // Pass through to generic operations.
3070 switch (glslangOperands.size()) {
3071 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06003072 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06003073 break;
3074 case 1:
John Kessenichead86222018-03-28 18:01:20 -06003075 {
3076 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06003077 TranslateNoContractionDecoration(node->getType().getQualifier()),
3078 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06003079 result = createUnaryOperation(
3080 node->getOp(), decorations,
3081 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003082 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06003083 }
John Kessenich426394d2015-07-23 10:22:48 -06003084 break;
3085 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06003086 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06003087 break;
3088 }
Cody Northrop4d2298b2020-04-13 21:59:49 -06003089
John Kessenichbbbd9a22020-03-03 07:21:37 -07003090 if (invertedType != spv::NoResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003091 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
Cody Northrop4d2298b2020-04-13 21:59:49 -06003092
3093 for (unsigned int i = 0; i < temporaryLvalues.size(); ++i) {
3094 builder.setAccessChain(complexLvalues[i]);
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02003095 builder.accessChainStore(builder.createLoad(temporaryLvalues[i], spv::NoPrecision), TranslateNonUniformDecoration(complexLValueQualifiers[i]));
John Kessenichbbbd9a22020-03-03 07:21:37 -07003096 }
John Kessenich140f3df2015-06-26 16:58:36 -06003097 }
3098
3099 if (noReturnValue)
3100 return false;
3101
3102 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04003103 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07003104 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06003105 } else {
3106 builder.clearAccessChain();
3107 builder.setAccessChainRValue(result);
3108 return false;
3109 }
3110}
3111
John Kessenich433e9ff2017-01-26 20:31:11 -07003112// This path handles both if-then-else and ?:
3113// The if-then-else has a node type of void, while
3114// ?: has either a void or a non-void node type
3115//
3116// Leaving the result, when not void:
3117// GLSL only has r-values as the result of a :?, but
3118// if we have an l-value, that can be more efficient if it will
3119// become the base of a complex r-value expression, because the
3120// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06003121bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
3122{
John Kessenich0c1e71a2019-01-10 18:23:06 +07003123 // see if OpSelect can handle it
3124 const auto isOpSelectable = [&]() {
3125 if (node->getBasicType() == glslang::EbtVoid)
3126 return false;
3127 // OpSelect can do all other types starting with SPV 1.4
3128 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
3129 // pre-1.4, only scalars and vectors can be handled
3130 if ((!node->getType().isScalar() && !node->getType().isVector()))
3131 return false;
3132 }
3133 return true;
3134 };
3135
John Kessenich4bee5312018-02-20 21:29:05 -07003136 // See if it simple and safe, or required, to execute both sides.
3137 // Crucially, side effects must be either semantically required or avoided,
3138 // and there are performance trade-offs.
3139 // Return true if required or a good idea (and safe) to execute both sides,
3140 // false otherwise.
3141 const auto bothSidesPolicy = [&]() -> bool {
3142 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07003143 if (node->getTrueBlock() == nullptr ||
3144 node->getFalseBlock() == nullptr)
3145 return false;
3146
John Kessenich4bee5312018-02-20 21:29:05 -07003147 // required? (unless we write additional code to look for side effects
3148 // and make performance trade-offs if none are present)
3149 if (!node->getShortCircuit())
3150 return true;
3151
3152 // if not required to execute both, decide based on performance/practicality...
3153
John Kessenich0c1e71a2019-01-10 18:23:06 +07003154 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07003155 return false;
3156
John Kessenich433e9ff2017-01-26 20:31:11 -07003157 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
3158 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
3159
3160 // return true if a single operand to ? : is okay for OpSelect
3161 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003162 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07003163 };
3164
3165 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
3166 operandOkay(node->getFalseBlock()->getAsTyped());
3167 };
3168
John Kessenich4bee5312018-02-20 21:29:05 -07003169 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
3170 // emit the condition before doing anything with selection
3171 node->getCondition()->traverse(this);
3172 spv::Id condition = accessChainLoad(node->getCondition()->getType());
3173
3174 // Find a way of executing both sides and selecting the right result.
3175 const auto executeBothSides = [&]() -> void {
3176 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07003177 node->getTrueBlock()->traverse(this);
3178 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3179 node->getFalseBlock()->traverse(this);
3180 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3181
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003182 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003183
John Kessenich4bee5312018-02-20 21:29:05 -07003184 // done if void
3185 if (node->getBasicType() == glslang::EbtVoid)
3186 return;
John Kesseniche434ad92017-03-30 10:09:28 -06003187
John Kessenich4bee5312018-02-20 21:29:05 -07003188 // emit code to select between trueValue and falseValue
3189
3190 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07003191 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07003192 // Emit OpSelect for this selection.
3193
3194 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07003195 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
3196 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07003197 condition = builder.smearScalar(spv::NoPrecision, condition,
3198 builder.makeVectorType(builder.makeBoolType(),
3199 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07003200 }
John Kessenich4bee5312018-02-20 21:29:05 -07003201
3202 // OpSelect
3203 result = builder.createTriOp(spv::OpSelect,
3204 convertGlslangToSpvType(node->getType()), condition,
3205 trueValue, falseValue);
3206
3207 builder.clearAccessChain();
3208 builder.setAccessChainRValue(result);
3209 } else {
3210 // We need control flow to select the result.
3211 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
John Kessenich435dd802020-06-30 01:27:08 -06003212 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()),
3213 spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich4bee5312018-02-20 21:29:05 -07003214
3215 // Selection control:
3216 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3217
3218 // make an "if" based on the value created by the condition
3219 spv::Builder::If ifBuilder(condition, control, builder);
3220
3221 // emit the "then" statement
3222 builder.createStore(trueValue, result);
3223 ifBuilder.makeBeginElse();
3224 // emit the "else" statement
3225 builder.createStore(falseValue, result);
3226
3227 // finish off the control flow
3228 ifBuilder.makeEndIf();
3229
3230 builder.clearAccessChain();
3231 builder.setAccessChainLValue(result);
3232 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003233 };
3234
John Kessenich4bee5312018-02-20 21:29:05 -07003235 // Execute the one side needed, as per the condition
3236 const auto executeOneSide = [&]() {
3237 // Always emit control flow.
John Kessenich435dd802020-06-30 01:27:08 -06003238 if (node->getBasicType() != glslang::EbtVoid) {
3239 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()), spv::StorageClassFunction,
3240 convertGlslangToSpvType(node->getType()));
3241 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003242
John Kessenich4bee5312018-02-20 21:29:05 -07003243 // Selection control:
3244 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3245
3246 // make an "if" based on the value created by the condition
3247 spv::Builder::If ifBuilder(condition, control, builder);
3248
3249 // emit the "then" statement
3250 if (node->getTrueBlock() != nullptr) {
3251 node->getTrueBlock()->traverse(this);
3252 if (result != spv::NoResult)
3253 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3254 }
3255
3256 if (node->getFalseBlock() != nullptr) {
3257 ifBuilder.makeBeginElse();
3258 // emit the "else" statement
3259 node->getFalseBlock()->traverse(this);
3260 if (result != spv::NoResult)
3261 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3262 }
3263
3264 // finish off the control flow
3265 ifBuilder.makeEndIf();
3266
3267 if (result != spv::NoResult) {
3268 builder.clearAccessChain();
3269 builder.setAccessChainLValue(result);
3270 }
3271 };
3272
3273 // Try for OpSelect (or a requirement to execute both sides)
3274 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003275 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3276 if (node->getType().getQualifier().isSpecConstant())
3277 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003278 executeBothSides();
3279 } else
3280 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003281
3282 return false;
3283}
3284
3285bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3286{
3287 // emit and get the condition before doing anything with switch
3288 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003289 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003290
Rex Xu57e65922017-07-04 23:23:40 +08003291 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003292 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003293
John Kessenich140f3df2015-06-26 16:58:36 -06003294 // browse the children to sort out code segments
3295 int defaultSegment = -1;
3296 std::vector<TIntermNode*> codeSegments;
3297 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3298 std::vector<int> caseValues;
3299 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3300 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3301 TIntermNode* child = *c;
3302 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003303 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003304 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003305 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich8985fc92020-03-03 10:25:07 -07003306 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()
3307 ->getConstArray()[0].getIConst());
John Kessenich140f3df2015-06-26 16:58:36 -06003308 } else
3309 codeSegments.push_back(child);
3310 }
3311
qining25262b32016-05-06 17:25:16 -04003312 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003313 // statements between the last case and the end of the switch statement
3314 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3315 (int)codeSegments.size() == defaultSegment)
3316 codeSegments.push_back(nullptr);
3317
3318 // make the switch statement
3319 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
John Kessenich8985fc92020-03-03 10:25:07 -07003320 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment,
3321 segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003322
3323 // emit all the code in the segments
3324 breakForLoop.push(false);
3325 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3326 builder.nextSwitchSegment(segmentBlocks, s);
3327 if (codeSegments[s])
3328 codeSegments[s]->traverse(this);
3329 else
3330 builder.addSwitchBreak();
3331 }
3332 breakForLoop.pop();
3333
3334 builder.endSwitch(segmentBlocks);
3335
3336 return false;
3337}
3338
3339void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3340{
3341 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003342 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003343
3344 builder.clearAccessChain();
3345 builder.setAccessChainRValue(constant);
3346}
3347
3348bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3349{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003350 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003351 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003352
3353 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003354 std::vector<unsigned int> operands;
3355 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003356
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003357 // Spec requires back edges to target header blocks, and every header block
3358 // must dominate its merge block. Make a header block first to ensure these
3359 // conditions are met. By definition, it will contain OpLoopMerge, followed
3360 // by a block-ending branch. But we don't want to put any other body/test
3361 // instructions in it, since the body/test may have arbitrary instructions,
3362 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003363 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003364 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003365 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003366 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003367 spv::Block& test = builder.makeNewBlock();
3368 builder.createBranch(&test);
3369
3370 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003371 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003372 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003373 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3374
3375 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003376 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003377 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003378 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003379 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003380 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003381
3382 builder.setBuildPoint(&blocks.continue_target);
3383 if (node->getTerminal())
3384 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003385 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003386 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003387 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003388 builder.createBranch(&blocks.body);
3389
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003390 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003391 builder.setBuildPoint(&blocks.body);
3392 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003393 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003394 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003395 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003396
3397 builder.setBuildPoint(&blocks.continue_target);
3398 if (node->getTerminal())
3399 node->getTerminal()->traverse(this);
3400 if (node->getTest()) {
3401 node->getTest()->traverse(this);
3402 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003403 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003404 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003405 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003406 // TODO: unless there was a break/return/discard instruction
3407 // somewhere in the body, this is an infinite loop, so we should
3408 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003409 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003410 }
John Kessenich140f3df2015-06-26 16:58:36 -06003411 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003412 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003413 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003414 return false;
3415}
3416
3417bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3418{
3419 if (node->getExpression())
3420 node->getExpression()->traverse(this);
3421
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003422 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003423
John Kessenich140f3df2015-06-26 16:58:36 -06003424 switch (node->getFlowOp()) {
3425 case glslang::EOpKill:
3426 builder.makeDiscard();
3427 break;
3428 case glslang::EOpBreak:
3429 if (breakForLoop.top())
3430 builder.createLoopExit();
3431 else
3432 builder.addSwitchBreak();
3433 break;
3434 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003435 builder.createLoopContinue();
3436 break;
3437 case glslang::EOpReturn:
John Kessenich435dd802020-06-30 01:27:08 -06003438 if (node->getExpression() != nullptr) {
John Kesseniched33e052016-10-06 12:59:51 -06003439 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3440 spv::Id returnId = accessChainLoad(glslangReturnType);
John Kessenich435dd802020-06-30 01:27:08 -06003441 if (builder.getTypeId(returnId) != currentFunction->getReturnType() ||
3442 TranslatePrecisionDecoration(glslangReturnType) != currentFunction->getReturnPrecision()) {
John Kesseniched33e052016-10-06 12:59:51 -06003443 builder.clearAccessChain();
John Kessenich435dd802020-06-30 01:27:08 -06003444 spv::Id copyId = builder.createVariable(currentFunction->getReturnPrecision(),
3445 spv::StorageClassFunction, currentFunction->getReturnType());
John Kesseniched33e052016-10-06 12:59:51 -06003446 builder.setAccessChainLValue(copyId);
3447 multiTypeStore(glslangReturnType, returnId);
John Kessenich435dd802020-06-30 01:27:08 -06003448 returnId = builder.createLoad(copyId, currentFunction->getReturnPrecision());
John Kesseniched33e052016-10-06 12:59:51 -06003449 }
3450 builder.makeReturn(false, returnId);
3451 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003452 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003453
3454 builder.clearAccessChain();
3455 break;
3456
John Kessenichb9197c82019-08-11 07:41:45 -06003457#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003458 case glslang::EOpDemote:
3459 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3460 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3461 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3462 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003463#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003464
John Kessenich140f3df2015-06-26 16:58:36 -06003465 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003466 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003467 break;
3468 }
3469
3470 return false;
3471}
3472
John Kessenich9c14f772019-06-17 08:38:35 -06003473spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003474{
qining25262b32016-05-06 17:25:16 -04003475 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003476 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003477 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003478 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003479 spv::Id result = createSpvConstant(*node);
3480 if (result != spv::NoResult)
3481 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003482 }
3483
3484 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003485 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003486 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3487 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003488
John Kessenichb9197c82019-08-11 07:41:45 -06003489 const bool contains16BitType = node->getType().contains16BitFloat() ||
3490 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003491 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003492 switch (storageClass) {
3493 case spv::StorageClassInput:
3494 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003495 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003496 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003497 break;
John Kessenich18310872018-05-14 22:08:53 -06003498 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003499 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003500 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3501 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003502 else
3503 builder.addCapability(spv::CapabilityStorageUniform16);
3504 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003505#ifndef GLSLANG_WEB
3506 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003507 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003508 builder.addCapability(spv::CapabilityStoragePushConstant16);
3509 break;
John Kessenich18310872018-05-14 22:08:53 -06003510 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003511 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003512 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003513 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3514 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003515#endif
John Kessenich18310872018-05-14 22:08:53 -06003516 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003517 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003518 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003519 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003520 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003521 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003522 }
3523 }
Rex Xuf89ad982017-04-07 23:22:33 +08003524
John Kessenichb9197c82019-08-11 07:41:45 -06003525 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003526 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003527 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003528 builder.addCapability(spv::CapabilityStoragePushConstant8);
3529 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003530 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003531 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003532 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003533 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003534 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003535 } else {
3536 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003537 }
3538 }
3539
John Kessenich140f3df2015-06-26 16:58:36 -06003540 const char* name = node->getName().c_str();
3541 if (glslang::IsAnonymous(name))
3542 name = "";
3543
Alejandro Piñeiroff6dcca2020-06-04 09:39:31 +02003544 spv::Id initializer = spv::NoResult;
3545
3546 if (node->getType().getQualifier().storage == glslang::EvqUniform &&
3547 !node->getConstArray().empty()) {
3548 int nextConst = 0;
3549 initializer = createSpvConstantFromConstUnionArray(node->getType(),
3550 node->getConstArray(),
3551 nextConst,
3552 false /* specConst */);
3553 }
3554
John Kessenich435dd802020-06-30 01:27:08 -06003555 return builder.createVariable(spv::NoPrecision, storageClass, spvType, name, initializer);
John Kessenich140f3df2015-06-26 16:58:36 -06003556}
3557
3558// Return type Id of the sampled type.
3559spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3560{
3561 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003562 case glslang::EbtInt: return builder.makeIntType(32);
3563 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003564 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003565#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003566 case glslang::EbtFloat16:
3567 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3568 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3569 return builder.makeFloatType(16);
3570#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003571 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003572 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003573 return builder.makeFloatType(32);
3574 }
3575}
3576
John Kessenich8c8505c2016-07-26 12:50:38 -06003577// If node is a swizzle operation, return the type that should be used if
3578// the swizzle base is first consumed by another operation, before the swizzle
3579// is applied.
3580spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3581{
John Kessenichecba76f2017-01-06 00:34:48 -07003582 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003583 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3584 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3585 else
3586 return spv::NoType;
3587}
3588
3589// When inverting a swizzle with a parent op, this function
3590// will apply the swizzle operation to a completed parent operation.
John Kessenich8985fc92020-03-03 10:25:07 -07003591spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
3592 spv::Id parentResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003593{
3594 std::vector<unsigned> swizzle;
3595 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3596 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3597}
3598
John Kessenich8c8505c2016-07-26 12:50:38 -06003599// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3600void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3601{
3602 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3603 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3604 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3605}
3606
John Kessenich3ac051e2015-12-20 11:29:16 -07003607// Convert from a glslang type to an SPV type, by calling into a
3608// recursive version of this function. This establishes the inherited
3609// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003610spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003611{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003612 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003613}
3614
3615// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003616// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003617// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003618spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003619 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3620 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003621{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003622 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003623
3624 switch (type.getBasicType()) {
3625 case glslang::EbtVoid:
3626 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003627 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003628 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003629 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003630 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3631 // a 32-bit int where non-0 means true.
3632 if (explicitLayout != glslang::ElpNone)
3633 spvType = builder.makeUintType(32);
3634 else
3635 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003636 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003637 case glslang::EbtInt:
3638 spvType = builder.makeIntType(32);
3639 break;
3640 case glslang::EbtUint:
3641 spvType = builder.makeUintType(32);
3642 break;
3643 case glslang::EbtFloat:
3644 spvType = builder.makeFloatType(32);
3645 break;
3646#ifndef GLSLANG_WEB
3647 case glslang::EbtDouble:
3648 spvType = builder.makeFloatType(64);
3649 break;
3650 case glslang::EbtFloat16:
3651 spvType = builder.makeFloatType(16);
3652 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003653 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003654 spvType = builder.makeIntType(8);
3655 break;
3656 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003657 spvType = builder.makeUintType(8);
3658 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003659 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003660 spvType = builder.makeIntType(16);
3661 break;
3662 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003663 spvType = builder.makeUintType(16);
3664 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003665 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003666 spvType = builder.makeIntType(64);
3667 break;
3668 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003669 spvType = builder.makeUintType(64);
3670 break;
John Kessenich426394d2015-07-23 10:22:48 -06003671 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003672 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003673 spvType = builder.makeUintType(32);
3674 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04003675 case glslang::EbtAccStruct:
3676 spvType = builder.makeAccelerationStructureType();
Chao Chenb50c02e2018-09-19 11:42:24 -07003677 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04003678 case glslang::EbtRayQuery:
3679 spvType = builder.makeRayQueryType();
3680 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003681 case glslang::EbtReference:
3682 {
3683 // Make the forward pointer, then recurse to convert the structure type, then
3684 // patch up the forward pointer with a real pointer type.
3685 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3686 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3687 forwardPointers[type.getReferentType()] = forwardId;
3688 }
3689 spvType = forwardPointers[type.getReferentType()];
3690 if (!forwardReferenceOnly) {
3691 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3692 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3693 forwardPointers[type.getReferentType()],
3694 referentType);
3695 }
3696 }
3697 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003698#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003699 case glslang::EbtSampler:
3700 {
3701 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003702 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003703 spvType = builder.makeSamplerType();
3704 } else {
3705 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003706 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3707 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3708 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3709 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003710 // already has both image and sampler, make the combined type
3711 spvType = builder.makeSampledImageType(spvType);
3712 }
John Kessenich55e7d112015-11-15 21:33:39 -07003713 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003714 }
John Kessenich140f3df2015-06-26 16:58:36 -06003715 break;
3716 case glslang::EbtStruct:
3717 case glslang::EbtBlock:
3718 {
3719 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003720 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003721
3722 // Try to share structs for different layouts, but not yet for other
3723 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003724 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003725 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003726 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003727 break;
3728
3729 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003730 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003731 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003732 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003733 }
3734 break;
Jeff Bolz04d73732019-05-31 13:06:01 -05003735 case glslang::EbtString:
3736 // no type used for OpString
3737 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003738 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003739 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003740 break;
3741 }
3742
3743 if (type.isMatrix())
3744 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3745 else {
3746 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3747 if (type.getVectorSize() > 1)
3748 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3749 }
3750
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003751 if (type.isCoopMat()) {
3752 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3753 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3754 if (type.getBasicType() == glslang::EbtFloat16)
3755 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003756 if (type.getBasicType() == glslang::EbtUint8 ||
3757 type.getBasicType() == glslang::EbtInt8) {
3758 builder.addCapability(spv::CapabilityInt8);
3759 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003760
3761 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3762 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3763 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3764
3765 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3766 }
3767
John Kessenich140f3df2015-06-26 16:58:36 -06003768 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003769 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3770
John Kessenichc9a80832015-09-12 12:17:44 -06003771 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003772 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003773 // We need to decorate array strides for types needing explicit layout, except blocks.
3774 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003775 // Use a dummy glslang type for querying internal strides of
3776 // arrays of arrays, but using just a one-dimensional array.
3777 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003778 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3779 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003780
3781 // Will compute the higher-order strides here, rather than making a whole
3782 // pile of types and doing repetitive recursion on their contents.
3783 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3784 }
John Kessenichf8842e52016-01-04 19:22:56 -07003785
3786 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003787 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003788 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003789 if (stride > 0)
3790 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003791 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003792 }
3793 } else {
3794 // single-dimensional array, and don't yet have stride
3795
John Kessenichf8842e52016-01-04 19:22:56 -07003796 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003797 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3798 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003799 }
John Kessenich31ed4832015-09-09 17:51:38 -06003800
John Kessenichead86222018-03-28 18:01:20 -06003801 // Do the outer dimension, which might not be known for a runtime-sized array.
3802 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3803 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003804 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003805 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003806#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003807 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003808 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003809 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3810 }
John Kessenichb9197c82019-08-11 07:41:45 -06003811#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003812 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003813 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003814 if (stride > 0)
3815 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003816 }
3817
3818 return spvType;
3819}
3820
John Kessenich0e737842017-03-24 18:38:16 -06003821// TODO: this functionality should exist at a higher level, in creating the AST
3822//
3823// Identify interface members that don't have their required extension turned on.
3824//
3825bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3826{
John Kessenicha28f7a72019-08-06 07:00:58 -06003827#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003828 auto& extensions = glslangIntermediate->getRequestedExtensions();
3829
Rex Xubcf291a2017-03-29 23:01:36 +08003830 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3831 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3832 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003833 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3834 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3835 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003836
3837 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3838 if (member.getFieldName() == "gl_ViewportMask" &&
3839 extensions.find("GL_NV_viewport_array2") == extensions.end())
3840 return true;
3841 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3842 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3843 return true;
3844 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3845 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3846 return true;
3847 }
3848#endif
John Kessenich0e737842017-03-24 18:38:16 -06003849
3850 return false;
3851};
3852
John Kessenich6090df02016-06-30 21:18:02 -06003853// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3854// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3855// Mutually recursive with convertGlslangToSpvType().
3856spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3857 const glslang::TTypeList* glslangMembers,
3858 glslang::TLayoutPacking explicitLayout,
3859 const glslang::TQualifier& qualifier)
3860{
3861 // Create a vector of struct types for SPIR-V to consume
3862 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07003863 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
3864 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003865 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003866 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3867 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3868 if (glslangMember.hiddenMember()) {
3869 ++memberDelta;
3870 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003871 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06003872 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003873 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003874 if (filterMember(glslangMember)) {
3875 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08003876 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003877 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003878 }
Roy05a5b532020-01-03 16:21:34 +08003879 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003880 }
John Kessenich6090df02016-06-30 21:18:02 -06003881 // modify just this child's view of the qualifier
3882 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3883 InheritQualifiers(memberQualifier, qualifier);
3884
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003885 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003886 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003887 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003888
3889 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003890 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3891 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003892
3893 // Make forward pointers for any pointer members, and create a list of members to
3894 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003895 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003896 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3897 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3898 }
3899 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003900 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3901 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003902 } else {
3903 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003904 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3905 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003906 }
John Kessenich6090df02016-06-30 21:18:02 -06003907 }
3908 }
3909
3910 // Make the SPIR-V type
3911 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003912 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003913 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3914
3915 // Decorate it
3916 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3917
John Kessenichd72f4882019-01-16 14:55:37 +07003918 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003919 auto it = deferredForwardPointers[i];
3920 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3921 }
3922
John Kessenich6090df02016-06-30 21:18:02 -06003923 return spvType;
3924}
3925
3926void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3927 const glslang::TTypeList* glslangMembers,
3928 glslang::TLayoutPacking explicitLayout,
3929 const glslang::TQualifier& qualifier,
3930 spv::Id spvType)
3931{
3932 // Name and decorate the non-hidden members
3933 int offset = -1;
3934 int locationOffset = 0; // for use within the members of this struct
3935 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3936 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3937 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003938 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08003939 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06003940 if (filterMember(glslangMember))
3941 continue;
3942 }
John Kessenich6090df02016-06-30 21:18:02 -06003943
3944 // modify just this child's view of the qualifier
3945 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3946 InheritQualifiers(memberQualifier, qualifier);
3947
3948 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003949 if (member < 0)
3950 continue;
3951
3952 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3953 builder.addMemberDecoration(spvType, member,
3954 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3955 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3956 // Add interpolation and auxiliary storage decorations only to
3957 // top-level members of Input and Output storage classes
3958 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3959 type.getQualifier().storage == glslang::EvqVaryingOut) {
3960 if (type.getBasicType() == glslang::EbtBlock ||
3961 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3962 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3963 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003964#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003965 addMeshNVDecoration(spvType, member, memberQualifier);
3966#endif
John Kessenich6090df02016-06-30 21:18:02 -06003967 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003968 }
3969 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003970
John Kessenichb9197c82019-08-11 07:41:45 -06003971#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003972 if (type.getBasicType() == glslang::EbtBlock &&
3973 qualifier.storage == glslang::EvqBuffer) {
3974 // Add memory decorations only to top-level members of shader storage block
3975 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003976 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003977 for (unsigned int i = 0; i < memory.size(); ++i)
3978 builder.addMemberDecoration(spvType, member, memory[i]);
3979 }
John Kessenichf8d1d742019-10-21 06:55:11 -06003980
John Kessenichb9197c82019-08-11 07:41:45 -06003981#endif
John Kessenich6090df02016-06-30 21:18:02 -06003982
John Kessenich5d610ee2018-03-07 18:05:55 -07003983 // Location assignment was already completed correctly by the front end,
3984 // just track whether a member needs to be decorated.
3985 // Ignore member locations if the container is an array, as that's
3986 // ill-specified and decisions have been made to not allow this.
3987 if (! type.isArray() && memberQualifier.hasLocation())
3988 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003989
John Kessenich5d610ee2018-03-07 18:05:55 -07003990 if (qualifier.hasLocation()) // track for upcoming inheritance
3991 locationOffset += glslangIntermediate->computeTypeLocationSize(
3992 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003993
John Kessenich5d610ee2018-03-07 18:05:55 -07003994 // component, XFB, others
3995 if (glslangMember.getQualifier().hasComponent())
3996 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3997 glslangMember.getQualifier().layoutComponent);
3998 if (glslangMember.getQualifier().hasXfbOffset())
3999 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
4000 glslangMember.getQualifier().layoutXfbOffset);
4001 else if (explicitLayout != glslang::ElpNone) {
4002 // figure out what to do with offset, which is accumulating
4003 int nextOffset;
4004 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
4005 if (offset >= 0)
4006 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
4007 offset = nextOffset;
4008 }
John Kessenich6090df02016-06-30 21:18:02 -06004009
John Kessenich5d610ee2018-03-07 18:05:55 -07004010 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
4011 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
4012 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06004013
John Kessenich5d610ee2018-03-07 18:05:55 -07004014 // built-in variable decorations
4015 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
4016 if (builtIn != spv::BuiltInMax)
4017 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08004018
John Kessenichb9197c82019-08-11 07:41:45 -06004019#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06004020 // nonuniform
4021 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
4022
John Kessenichead86222018-03-28 18:01:20 -06004023 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
4024 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
4025 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
4026 memberQualifier.semanticName);
4027 }
4028
John Kessenich5d610ee2018-03-07 18:05:55 -07004029 if (builtIn == spv::BuiltInLayer) {
4030 // SPV_NV_viewport_array2 extension
4031 if (glslangMember.getQualifier().layoutViewportRelative){
4032 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
4033 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4034 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08004035 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004036 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
4037 builder.addMemberDecoration(spvType, member,
4038 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
4039 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
4040 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4041 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08004042 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004043 }
4044 if (glslangMember.getQualifier().layoutPassthrough) {
4045 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
4046 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
4047 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4048 }
chaoc771d89f2017-01-13 01:10:53 -08004049#endif
John Kessenich6090df02016-06-30 21:18:02 -06004050 }
4051
4052 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07004053 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
4054 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06004055}
4056
John Kessenich6c292d32016-02-15 20:58:50 -07004057// Turn the expression forming the array size into an id.
4058// This is not quite trivial, because of specialization constants.
4059// Sometimes, a raw constant is turned into an Id, and sometimes
4060// a specialization constant expression is.
4061spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
4062{
4063 // First, see if this is sized with a node, meaning a specialization constant:
4064 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
4065 if (specNode != nullptr) {
4066 builder.clearAccessChain();
4067 specNode->traverse(this);
4068 return accessChainLoad(specNode->getAsTyped()->getType());
4069 }
qining25262b32016-05-06 17:25:16 -04004070
John Kessenich6c292d32016-02-15 20:58:50 -07004071 // Otherwise, need a compile-time (front end) size, get it:
4072 int size = arraySizes.getDimSize(dim);
4073 assert(size > 0);
4074 return builder.makeUintConstant(size);
4075}
4076
John Kessenich103bef92016-02-08 21:38:15 -07004077// Wrap the builder's accessChainLoad to:
4078// - localize handling of RelaxedPrecision
4079// - use the SPIR-V inferred type instead of another conversion of the glslang type
4080// (avoids unnecessary work and possible type punning for structures)
4081// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07004082spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
4083{
John Kessenich103bef92016-02-08 21:38:15 -07004084 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004085
4086 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4087 coherentFlags |= TranslateCoherent(type);
4088
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004089 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004090 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004091
John Kessenich5611c6d2018-04-05 11:25:02 -06004092 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
John Kessenich8985fc92020-03-03 10:25:07 -07004093 TranslateNonUniformDecoration(type.getQualifier()),
4094 nominalTypeId,
4095 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
4096 TranslateMemoryScope(coherentFlags),
4097 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07004098
4099 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08004100 if (type.getBasicType() == glslang::EbtBool) {
4101 if (builder.isScalarType(nominalTypeId)) {
4102 // Conversion for bool
4103 spv::Id boolType = builder.makeBoolType();
4104 if (nominalTypeId != boolType)
4105 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
4106 } else if (builder.isVectorType(nominalTypeId)) {
4107 // Conversion for bvec
4108 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4109 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
4110 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07004111 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
4112 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004113 }
4114 }
John Kessenich103bef92016-02-08 21:38:15 -07004115
4116 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07004117}
4118
Rex Xu27253232016-02-23 17:51:09 +08004119// Wrap the builder's accessChainStore to:
4120// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06004121//
4122// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08004123void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
4124{
4125 // Need to convert to abstract types when necessary
4126 if (type.getBasicType() == glslang::EbtBool) {
4127 spv::Id nominalTypeId = builder.accessChainGetInferredType();
4128
4129 if (builder.isScalarType(nominalTypeId)) {
4130 // Conversion for bool
4131 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06004132 if (nominalTypeId != boolType) {
4133 // keep these outside arguments, for determinant order-of-evaluation
4134 spv::Id one = builder.makeUintConstant(1);
4135 spv::Id zero = builder.makeUintConstant(0);
4136 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
4137 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06004138 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08004139 } else if (builder.isVectorType(nominalTypeId)) {
4140 // Conversion for bvec
4141 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4142 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06004143 if (nominalTypeId != bvecType) {
4144 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06004145 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
4146 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
4147 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06004148 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06004149 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
4150 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004151 }
4152 }
4153
Jeff Bolz36831c92018-09-05 10:11:41 -05004154 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4155 coherentFlags |= TranslateCoherent(type);
4156
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004157 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004158 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004159
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02004160 builder.accessChainStore(rvalue, TranslateNonUniformDecoration(type.getQualifier()),
John Kessenich8985fc92020-03-03 10:25:07 -07004161 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
4162 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004163 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08004164}
4165
John Kessenich4bf71552016-09-02 11:20:21 -06004166// For storing when types match at the glslang level, but not might match at the
4167// SPIR-V level.
4168//
4169// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004170// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004171// as in a member-decorated way.
4172//
4173// NOTE: This function can handle any store request; if it's not special it
4174// simplifies to a simple OpStore.
4175//
4176// Implicitly uses the existing builder.accessChain as the storage target.
4177void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4178{
John Kessenichb3e24e42016-09-11 12:33:43 -06004179 // we only do the complex path here if it's an aggregate
4180 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004181 accessChainStore(type, rValue);
4182 return;
4183 }
4184
John Kessenichb3e24e42016-09-11 12:33:43 -06004185 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004186 spv::Id rType = builder.getTypeId(rValue);
4187 spv::Id lValue = builder.accessChainGetLValue();
4188 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4189 if (lType == rType) {
4190 accessChainStore(type, rValue);
4191 return;
4192 }
4193
John Kessenichb3e24e42016-09-11 12:33:43 -06004194 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004195 // where the two types were the same type in GLSL. This requires member
4196 // by member copy, recursively.
4197
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004198 // SPIR-V 1.4 added an instruction to do help do this.
4199 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4200 // However, bool in uniform space is changed to int, so
4201 // OpCopyLogical does not work for that.
4202 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4203 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4204 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4205 if (lBool == rBool) {
4206 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4207 accessChainStore(type, logicalCopy);
4208 return;
4209 }
4210 }
4211
John Kessenichb3e24e42016-09-11 12:33:43 -06004212 // If an array, copy element by element.
4213 if (type.isArray()) {
4214 glslang::TType glslangElementType(type, 0);
4215 spv::Id elementRType = builder.getContainedTypeId(rType);
4216 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4217 // get the source member
4218 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004219
John Kessenichb3e24e42016-09-11 12:33:43 -06004220 // set up the target storage
4221 builder.clearAccessChain();
4222 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004223 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4224 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004225
John Kessenichb3e24e42016-09-11 12:33:43 -06004226 // store the member
4227 multiTypeStore(glslangElementType, elementRValue);
4228 }
4229 } else {
4230 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004231
John Kessenichb3e24e42016-09-11 12:33:43 -06004232 // loop over structure members
4233 const glslang::TTypeList& members = *type.getStruct();
4234 for (int m = 0; m < (int)members.size(); ++m) {
4235 const glslang::TType& glslangMemberType = *members[m].type;
4236
4237 // get the source member
4238 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4239 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4240
4241 // set up the target storage
4242 builder.clearAccessChain();
4243 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004244 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4245 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004246
4247 // store the member
4248 multiTypeStore(glslangMemberType, memberRValue);
4249 }
John Kessenich4bf71552016-09-02 11:20:21 -06004250 }
4251}
4252
John Kessenichf85e8062015-12-19 13:57:10 -07004253// Decide whether or not this type should be
4254// decorated with offsets and strides, and if so
4255// whether std140 or std430 rules should be applied.
4256glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004257{
John Kessenichf85e8062015-12-19 13:57:10 -07004258 // has to be a block
4259 if (type.getBasicType() != glslang::EbtBlock)
4260 return glslang::ElpNone;
4261
Chao Chen3c366992018-09-19 11:41:59 -07004262 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004263 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004264 type.getQualifier().storage != glslang::EvqBuffer &&
4265 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004266 return glslang::ElpNone;
4267
4268 // return the layout to use
4269 switch (type.getQualifier().layoutPacking) {
4270 case glslang::ElpStd140:
4271 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004272 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004273 return type.getQualifier().layoutPacking;
4274 default:
4275 return glslang::ElpNone;
4276 }
John Kessenich31ed4832015-09-09 17:51:38 -06004277}
4278
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004279// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004280int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4281 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004282{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004283 int size;
John Kessenich49987892015-12-29 17:11:44 -07004284 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004285 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4286 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004287
4288 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004289}
4290
John Kessenich49987892015-12-29 17:11:44 -07004291// 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 -07004292// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004293int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4294 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004295{
John Kessenich49987892015-12-29 17:11:44 -07004296 glslang::TType elementType;
4297 elementType.shallowCopy(matrixType);
4298 elementType.clearArraySizes();
4299
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004300 int size;
John Kessenich49987892015-12-29 17:11:44 -07004301 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004302 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4303 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004304
4305 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004306}
4307
John Kessenich5e4b1242015-08-06 22:53:06 -06004308// Given a member type of a struct, realign the current offset for it, and compute
4309// the next (not yet aligned) offset for the next member, which will get aligned
4310// on the next call.
4311// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4312// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4313// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004314void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4315 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004316{
4317 // this will get a positive value when deemed necessary
4318 nextOffset = -1;
4319
John Kessenich5e4b1242015-08-06 22:53:06 -06004320 // override anything in currentOffset with user-set offset
4321 if (memberType.getQualifier().hasOffset())
4322 currentOffset = memberType.getQualifier().layoutOffset;
4323
4324 // It could be that current linker usage in glslang updated all the layoutOffset,
4325 // in which case the following code does not matter. But, that's not quite right
4326 // once cross-compilation unit GLSL validation is done, as the original user
4327 // settings are needed in layoutOffset, and then the following will come into play.
4328
John Kessenichf85e8062015-12-19 13:57:10 -07004329 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004330 if (! memberType.getQualifier().hasOffset())
4331 currentOffset = -1;
4332
4333 return;
4334 }
4335
John Kessenichf85e8062015-12-19 13:57:10 -07004336 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004337 if (currentOffset < 0)
4338 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004339
John Kessenich5e4b1242015-08-06 22:53:06 -06004340 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4341 // but possibly not yet correctly aligned.
4342
4343 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004344 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004345 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4346 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004347
4348 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004349 // TODO: make this consistent in early phases of code:
4350 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4351 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4352 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004353 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004354 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004355 int dummySize;
4356 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4357 if (componentAlignment <= 4)
4358 memberAlignment = componentAlignment;
4359 }
4360
4361 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004362 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004363
4364 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004365 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4366 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004367 glslang::RoundToPow2(currentOffset, 16);
4368
John Kessenich5e4b1242015-08-06 22:53:06 -06004369 nextOffset = currentOffset + memberSize;
4370}
4371
David Netoa901ffe2016-06-08 14:11:40 +01004372void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004373{
David Netoa901ffe2016-06-08 14:11:40 +01004374 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4375 switch (glslangBuiltIn)
4376 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004377 case glslang::EbvPointSize:
4378#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004379 case glslang::EbvClipDistance:
4380 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004381 case glslang::EbvViewportMaskNV:
4382 case glslang::EbvSecondaryPositionNV:
4383 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004384 case glslang::EbvPositionPerViewNV:
4385 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004386 case glslang::EbvTaskCountNV:
4387 case glslang::EbvPrimitiveCountNV:
4388 case glslang::EbvPrimitiveIndicesNV:
4389 case glslang::EbvClipDistancePerViewNV:
4390 case glslang::EbvCullDistancePerViewNV:
4391 case glslang::EbvLayerPerViewNV:
4392 case glslang::EbvMeshViewCountNV:
4393 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004394#endif
David Netoa901ffe2016-06-08 14:11:40 +01004395 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4396 // Alternately, we could just call this for any glslang built-in, since the
4397 // capability already guards against duplicates.
4398 TranslateBuiltInDecoration(glslangBuiltIn, false);
4399 break;
4400 default:
4401 // Capabilities were already generated when the struct was declared.
4402 break;
4403 }
John Kessenichebb50532016-05-16 19:22:05 -06004404}
4405
John Kessenich6fccb3c2016-09-19 16:01:41 -06004406bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004407{
John Kessenicheee9d532016-09-19 18:09:30 -06004408 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004409}
4410
John Kessenichd41993d2017-09-10 15:21:05 -06004411// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004412// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4413// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004414bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004415{
John Kessenich6a14f782017-12-04 02:48:10 -07004416 assert(qualifier == glslang::EvqIn ||
4417 qualifier == glslang::EvqOut ||
4418 qualifier == glslang::EvqInOut ||
rdbd8edfd82020-06-02 08:30:07 +02004419 qualifier == glslang::EvqUniform ||
John Kessenich6a14f782017-12-04 02:48:10 -07004420 qualifier == glslang::EvqConstReadOnly);
rdbd8edfd82020-06-02 08:30:07 +02004421 return qualifier != glslang::EvqConstReadOnly &&
4422 qualifier != glslang::EvqUniform;
John Kessenichd41993d2017-09-10 15:21:05 -06004423}
4424
4425// Is parameter pass-by-original?
4426bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4427 bool implicitThisParam)
4428{
4429 if (implicitThisParam) // implicit this
4430 return true;
4431 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004432 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004433 return paramType.containsOpaque() || // sampler, etc.
4434 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4435}
4436
John Kessenich140f3df2015-06-26 16:58:36 -06004437// Make all the functions, skeletally, without actually visiting their bodies.
4438void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4439{
John Kessenich8985fc92020-03-03 10:25:07 -07004440 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4441 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004442 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4443 if (paramPrecision != spv::NoPrecision)
4444 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004445 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004446 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004447 // Original and non-writable params pass the pointer directly and
4448 // use restrict/aliased, others are stored to a pointer in Function
4449 // memory and use RestrictPointer/AliasedPointer.
4450 if (originalParam(type.getQualifier().storage, type, false) ||
4451 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004452 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4453 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004454 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004455 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4456 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004457 }
4458 }
John Kessenichfad62972017-07-18 02:35:46 -06004459 };
4460
John Kessenich140f3df2015-06-26 16:58:36 -06004461 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4462 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004463 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004464 continue;
4465
4466 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004467 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004468 //
qining25262b32016-05-06 17:25:16 -04004469 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004470 // function. What it is an address of varies:
4471 //
John Kessenich4bf71552016-09-02 11:20:21 -06004472 // - "in" parameters not marked as "const" can be written to without modifying the calling
4473 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004474 //
4475 // - "const in" parameters can just be the r-value, as no writes need occur.
4476 //
John Kessenich4bf71552016-09-02 11:20:21 -06004477 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4478 // 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 -06004479
4480 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004481 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004482 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4483
John Kessenich155d3512019-08-08 23:29:20 -06004484#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004485 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4486 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004487#else
4488 bool implicitThis = false;
4489#endif
John Kessenich37789792017-03-21 23:56:40 -06004490
John Kessenichfad62972017-07-18 02:35:46 -06004491 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004492 for (int p = 0; p < (int)parameters.size(); ++p) {
4493 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4494 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004495 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004496 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004497 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004498 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4499 else
John Kessenich4bf71552016-09-02 11:20:21 -06004500 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004501 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004502 paramTypes.push_back(typeId);
4503 }
4504
4505 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004506 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4507 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004508 glslFunction->getName().c_str(), paramTypes,
4509 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004510 if (implicitThis)
4511 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004512
4513 // Track function to emit/call later
4514 functionMap[glslFunction->getName().c_str()] = function;
4515
4516 // Set the parameter id's
4517 for (int p = 0; p < (int)parameters.size(); ++p) {
4518 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4519 // give a name too
4520 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004521
4522 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004523 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004524 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004525 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004526 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004527 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004528 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004529 }
4530 }
4531}
4532
4533// Process all the initializers, while skipping the functions and link objects
4534void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4535{
4536 builder.setBuildPoint(shaderEntry->getLastBlock());
4537 for (int i = 0; i < (int)initializers.size(); ++i) {
4538 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004539 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4540 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004541
4542 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004543 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004544 initializer->traverse(this);
4545 }
4546 }
4547}
4548
4549// Process all the functions, while skipping initializers.
4550void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4551{
4552 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4553 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004554 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004555 node->traverse(this);
4556 }
4557}
4558
4559void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4560{
qining25262b32016-05-06 17:25:16 -04004561 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004562 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004563 currentFunction = functionMap[node->getName().c_str()];
4564 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004565 builder.setBuildPoint(functionBlock);
4566}
4567
John Kessenich8985fc92020-03-03 10:25:07 -07004568void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4569 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004570{
Rex Xufc618912015-09-09 16:42:49 +08004571 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004572
4573 glslang::TSampler sampler = {};
4574 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004575#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004576 bool f16ShadowCompare = false;
4577#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004578 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004579 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4580 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004581#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004582 f16ShadowCompare = sampler.shadow &&
4583 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004584#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004585 }
4586
John Kessenich140f3df2015-06-26 16:58:36 -06004587 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4588 builder.clearAccessChain();
4589 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004590
John Kessenicha28f7a72019-08-06 07:00:58 -06004591#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004592 // Special case l-value operands
4593 bool lvalue = false;
4594 switch (node.getOp()) {
4595 case glslang::EOpImageAtomicAdd:
4596 case glslang::EOpImageAtomicMin:
4597 case glslang::EOpImageAtomicMax:
4598 case glslang::EOpImageAtomicAnd:
4599 case glslang::EOpImageAtomicOr:
4600 case glslang::EOpImageAtomicXor:
4601 case glslang::EOpImageAtomicExchange:
4602 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004603 case glslang::EOpImageAtomicLoad:
4604 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004605 if (i == 0)
4606 lvalue = true;
4607 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004608 case glslang::EOpSparseImageLoad:
4609 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4610 lvalue = true;
4611 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004612 case glslang::EOpSparseTexture:
4613 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4614 lvalue = true;
4615 break;
4616 case glslang::EOpSparseTextureClamp:
4617 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4618 lvalue = true;
4619 break;
4620 case glslang::EOpSparseTextureLod:
4621 case glslang::EOpSparseTextureOffset:
4622 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4623 lvalue = true;
4624 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004625 case glslang::EOpSparseTextureFetch:
4626 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4627 lvalue = true;
4628 break;
4629 case glslang::EOpSparseTextureFetchOffset:
4630 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4631 lvalue = true;
4632 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004633 case glslang::EOpSparseTextureLodOffset:
4634 case glslang::EOpSparseTextureGrad:
4635 case glslang::EOpSparseTextureOffsetClamp:
4636 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4637 lvalue = true;
4638 break;
4639 case glslang::EOpSparseTextureGradOffset:
4640 case glslang::EOpSparseTextureGradClamp:
4641 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4642 lvalue = true;
4643 break;
4644 case glslang::EOpSparseTextureGradOffsetClamp:
4645 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4646 lvalue = true;
4647 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004648 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004649 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4650 lvalue = true;
4651 break;
4652 case glslang::EOpSparseTextureGatherOffset:
4653 case glslang::EOpSparseTextureGatherOffsets:
4654 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4655 lvalue = true;
4656 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004657 case glslang::EOpSparseTextureGatherLod:
4658 if (i == 3)
4659 lvalue = true;
4660 break;
4661 case glslang::EOpSparseTextureGatherLodOffset:
4662 case glslang::EOpSparseTextureGatherLodOffsets:
4663 if (i == 4)
4664 lvalue = true;
4665 break;
Rex Xu129799a2017-07-05 17:23:28 +08004666 case glslang::EOpSparseImageLoadLod:
4667 if (i == 3)
4668 lvalue = true;
4669 break;
Chao Chen3a137962018-09-19 11:41:27 -07004670 case glslang::EOpImageSampleFootprintNV:
4671 if (i == 4)
4672 lvalue = true;
4673 break;
4674 case glslang::EOpImageSampleFootprintClampNV:
4675 case glslang::EOpImageSampleFootprintLodNV:
4676 if (i == 5)
4677 lvalue = true;
4678 break;
4679 case glslang::EOpImageSampleFootprintGradNV:
4680 if (i == 6)
4681 lvalue = true;
4682 break;
4683 case glslang::EOpImageSampleFootprintGradClampNV:
4684 if (i == 7)
4685 lvalue = true;
4686 break;
Rex Xufc618912015-09-09 16:42:49 +08004687 default:
4688 break;
4689 }
4690
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004691 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004692 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004693 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4694 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4695 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004696#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004697 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004698 }
4699}
4700
John Kessenichfc51d282015-08-19 13:34:18 -06004701void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004702{
John Kessenichfc51d282015-08-19 13:34:18 -06004703 builder.clearAccessChain();
4704 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004705 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004706}
John Kessenich140f3df2015-06-26 16:58:36 -06004707
John Kessenichfc51d282015-08-19 13:34:18 -06004708spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4709{
John Kesseniche485c7a2017-05-31 18:50:53 -06004710 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004711 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004712
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004713 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004714
John Kessenichfc51d282015-08-19 13:34:18 -06004715 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004716
John Kessenichf43c7392019-03-31 10:51:57 -06004717 const glslang::TType &imageType = node->getAsAggregate()
4718 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4719 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004720 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004721#ifdef GLSLANG_WEB
4722 const bool f16ShadowCompare = false;
4723#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004724 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004725 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4726 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004727#endif
4728
John Kessenichf43c7392019-03-31 10:51:57 -06004729 const auto signExtensionMask = [&]() {
4730 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4731 if (sampler.type == glslang::EbtUint)
4732 return spv::ImageOperandsZeroExtendMask;
4733 else if (sampler.type == glslang::EbtInt)
4734 return spv::ImageOperandsSignExtendMask;
4735 }
4736 return spv::ImageOperandsMaskNone;
4737 };
4738
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004739 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4740
John Kessenichfc51d282015-08-19 13:34:18 -06004741 std::vector<spv::Id> arguments;
4742 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004743 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004744 else
4745 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenich12c155f2020-06-30 07:52:05 -06004746 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
John Kessenichfc51d282015-08-19 13:34:18 -06004747
4748 spv::Builder::TextureParameters params = { };
4749 params.sampler = arguments[0];
4750
Rex Xu04db3f52015-09-16 11:44:02 +08004751 glslang::TCrackedTextureOp cracked;
4752 node->crackTexture(sampler, cracked);
4753
amhagan05506bb2017-06-13 16:53:02 -04004754 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004755
Bas Nieuwenhuizen58064312020-09-03 03:04:13 +02004756 if (builder.isSampledImage(params.sampler) &&
4757 ((cracked.query && node->getOp() != glslang::EOpTextureQueryLod) || cracked.fragMask || cracked.fetch)) {
4758 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4759 if (imageType.getQualifier().isNonUniform()) {
4760 builder.addDecoration(params.sampler, spv::DecorationNonUniformEXT);
4761 }
4762 }
John Kessenichfc51d282015-08-19 13:34:18 -06004763 // Check for queries
4764 if (cracked.query) {
4765 switch (node->getOp()) {
4766 case glslang::EOpImageQuerySize:
4767 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004768 if (arguments.size() > 1) {
4769 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004770 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004771 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004772 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004773#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004774 case glslang::EOpImageQuerySamples:
4775 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004776 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004777 case glslang::EOpTextureQueryLod:
4778 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004779 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004780 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004781 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004782 case glslang::EOpSparseTexelsResident:
4783 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004784#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004785 default:
4786 assert(0);
4787 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004788 }
John Kessenich140f3df2015-06-26 16:58:36 -06004789 }
4790
LoopDawg4425f242018-02-18 11:40:01 -07004791 int components = node->getType().getVectorSize();
4792
4793 if (node->getOp() == glslang::EOpTextureFetch) {
4794 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4795 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4796 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4797 // here around e.g. which ones return scalars or other types.
4798 components = 4;
4799 }
4800
4801 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4802
4803 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4804
Rex Xufc618912015-09-09 16:42:49 +08004805 // Check for image functions other than queries
4806 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004807 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004808 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004809 spv::IdImmediate image = { true, *(opIt++) };
4810 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004811
4812 // Handle subpass operations
4813 // TODO: GLSL should change to have the "MS" only on the type rather than the
4814 // built-in function.
4815 if (cracked.subpass) {
4816 // add on the (0,0) coordinate
4817 spv::Id zero = builder.makeIntConstant(0);
4818 std::vector<spv::Id> comps;
4819 comps.push_back(zero);
4820 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004821 spv::IdImmediate coord = { true,
4822 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4823 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004824 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4825 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004826 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004827 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4828 }
4829 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004830 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004831 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004832 spv::IdImmediate imageOperand = { true, *(opIt++) };
4833 operands.push_back(imageOperand);
4834 }
John Kessenich6c292d32016-02-15 20:58:50 -07004835 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004836 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4837 builder.setPrecision(result, precision);
4838 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004839 }
4840
John Kessenich149afc32018-08-14 13:31:43 -06004841 spv::IdImmediate coord = { true, *(opIt++) };
4842 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004843 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004844 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004845 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004846 mask = mask | spv::ImageOperandsSampleMask;
4847 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004848 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004849 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4850 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004851 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004852 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004853 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4854 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004855 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004856 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004857 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4858 operands.push_back(imageOperands);
4859 }
4860 if (mask & spv::ImageOperandsSampleMask) {
4861 spv::IdImmediate imageOperand = { true, *opIt++ };
4862 operands.push_back(imageOperand);
4863 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004864 if (mask & spv::ImageOperandsLodMask) {
4865 spv::IdImmediate imageOperand = { true, *opIt++ };
4866 operands.push_back(imageOperand);
4867 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004868 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004869 spv::IdImmediate imageOperand = { true,
4870 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004871 operands.push_back(imageOperand);
4872 }
4873
John Kessenich149afc32018-08-14 13:31:43 -06004874 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004875 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004876
John Kessenich149afc32018-08-14 13:31:43 -06004877 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004878 builder.setPrecision(result[0], precision);
4879
4880 // If needed, add a conversion constructor to the proper size.
4881 if (components != node->getType().getVectorSize())
4882 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4883
4884 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004885 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004886
Jeff Bolz36831c92018-09-05 10:11:41 -05004887 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004888 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004889 spv::IdImmediate texel = { true, *(opIt + 1) };
4890 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004891 } else {
4892 spv::IdImmediate texel = { true, *opIt };
4893 operands.push_back(texel);
4894 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004895
4896 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004897 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004898 mask = mask | spv::ImageOperandsSampleMask;
4899 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004900 if (cracked.lod) {
4901 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4902 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4903 mask = mask | spv::ImageOperandsLodMask;
4904 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004905 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4906 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004907 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004908 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004909 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4910 operands.push_back(imageOperands);
4911 }
4912 if (mask & spv::ImageOperandsSampleMask) {
4913 spv::IdImmediate imageOperand = { true, *opIt++ };
4914 operands.push_back(imageOperand);
4915 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004916 if (mask & spv::ImageOperandsLodMask) {
4917 spv::IdImmediate imageOperand = { true, *opIt++ };
4918 operands.push_back(imageOperand);
4919 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004920 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004921 spv::IdImmediate imageOperand = { true,
4922 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004923 operands.push_back(imageOperand);
4924 }
4925
John Kessenich56bab042015-09-16 10:54:31 -06004926 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004927 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004928 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004929 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004930 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4931 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004932 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004933 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004934 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4935
Jeff Bolz36831c92018-09-05 10:11:41 -05004936 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004937 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004938 mask = mask | spv::ImageOperandsSampleMask;
4939 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004940 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004941 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4942 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4943
Jeff Bolz36831c92018-09-05 10:11:41 -05004944 mask = mask | spv::ImageOperandsLodMask;
4945 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004946 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4947 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004948 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004949 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004950 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004951 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004952 }
4953 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004954 spv::IdImmediate imageOperand = { true, *opIt++ };
4955 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004956 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004957 if (mask & spv::ImageOperandsLodMask) {
4958 spv::IdImmediate imageOperand = { true, *opIt++ };
4959 operands.push_back(imageOperand);
4960 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004961 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07004962 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
4963 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004964 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004965 }
4966
4967 // Create the return type that was a special structure
4968 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004969 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004970 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4971 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4972
4973 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4974
4975 // Decode the return type
4976 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4977 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004978 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004979 // Process image atomic operations
4980
4981 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4982 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004983 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004984 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004985 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004986
Jeff Bolz36831c92018-09-05 10:11:41 -05004987 spv::Id resultTypeId;
4988 // imageAtomicStore has a void return type so base the pointer type on
4989 // the type of the value operand.
4990 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08004991 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05004992 } else {
4993 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4994 }
John Kessenich56bab042015-09-16 10:54:31 -06004995 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Jeff Bolz39ffdaf2020-03-09 10:48:12 -05004996 if (imageType.getQualifier().nonUniform) {
4997 builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
4998 }
Rex Xufc618912015-09-09 16:42:49 +08004999
5000 std::vector<spv::Id> operands;
5001 operands.push_back(pointer);
5002 for (; opIt != arguments.end(); ++opIt)
5003 operands.push_back(*opIt);
5004
John Kessenich8985fc92020-03-03 10:25:07 -07005005 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
5006 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08005007 }
5008 }
5009
John Kessenicha28f7a72019-08-06 07:00:58 -06005010#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04005011 // Check for fragment mask functions other than queries
5012 if (cracked.fragMask) {
5013 assert(sampler.ms);
5014
5015 auto opIt = arguments.begin();
5016 std::vector<spv::Id> operands;
5017
amhagan05506bb2017-06-13 16:53:02 -04005018 operands.push_back(params.sampler);
5019 ++opIt;
5020
5021 if (sampler.isSubpass()) {
5022 // add on the (0,0) coordinate
5023 spv::Id zero = builder.makeIntConstant(0);
5024 std::vector<spv::Id> comps;
5025 comps.push_back(zero);
5026 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07005027 operands.push_back(builder.makeCompositeConstant(
5028 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04005029 }
5030
5031 for (; opIt != arguments.end(); ++opIt)
5032 operands.push_back(*opIt);
5033
5034 spv::Op fragMaskOp = spv::OpNop;
5035 if (node->getOp() == glslang::EOpFragmentMaskFetch)
5036 fragMaskOp = spv::OpFragmentMaskFetchAMD;
5037 else if (node->getOp() == glslang::EOpFragmentFetch)
5038 fragMaskOp = spv::OpFragmentFetchAMD;
5039
5040 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
5041 builder.addCapability(spv::CapabilityFragmentMaskAMD);
5042 return builder.createOp(fragMaskOp, resultType(), operands);
5043 }
5044#endif
5045
Rex Xufc618912015-09-09 16:42:49 +08005046 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08005047 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07005048 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005049 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08005050
John Kessenichfc51d282015-08-19 13:34:18 -06005051 // check for bias argument
5052 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08005053 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005054 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08005055 if (cracked.gather)
5056 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08005057
5058 if (f16ShadowCompare)
5059 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005060 if (cracked.offset)
5061 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08005062 else if (cracked.offsets)
5063 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005064 if (cracked.grad)
5065 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08005066 if (cracked.lodClamp)
5067 ++nonBiasArgCount;
5068 if (sparse)
5069 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07005070 if (imageFootprint)
5071 //Following three extra arguments
5072 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5073 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06005074 if ((int)arguments.size() > nonBiasArgCount)
5075 bias = true;
5076 }
5077
John Kessenicha28f7a72019-08-06 07:00:58 -06005078#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08005079 if (cracked.gather) {
5080 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
5081 if (bias || cracked.lod ||
5082 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
5083 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08005084 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08005085 }
5086 }
5087#endif
5088
John Kessenichfc51d282015-08-19 13:34:18 -06005089 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07005090
John Kessenichfc51d282015-08-19 13:34:18 -06005091 params.coords = arguments[1];
5092 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07005093 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07005094
5095 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08005096 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005097 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08005098 ++extraArgs;
5099 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07005100 params.Dref = arguments[2];
5101 ++extraArgs;
5102 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06005103 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06005104 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06005105 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06005106 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06005107 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005108 dRefComp = builder.getNumComponents(params.coords) - 1;
5109 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07005110 params.Dref = builder.createCompositeExtract(params.coords,
5111 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06005112 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005113
5114 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06005115 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005116 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06005117 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06005118 } else if (glslangIntermediate->getStage() != EShLangFragment &&
5119 !(glslangIntermediate->getStage() == EShLangCompute &&
5120 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07005121 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
5122 noImplicitLod = true;
5123 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005124
5125 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005126 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005127 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08005128 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005129 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005130
5131 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06005132 if (cracked.grad) {
5133 params.gradX = arguments[2 + extraArgs];
5134 params.gradY = arguments[3 + extraArgs];
5135 extraArgs += 2;
5136 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005137
5138 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07005139 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06005140 params.offset = arguments[2 + extraArgs];
5141 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005142 } else if (cracked.offsets) {
5143 params.offsets = arguments[2 + extraArgs];
5144 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005145 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005146
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005147#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005148 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005149 if (cracked.lodClamp) {
5150 params.lodClamp = arguments[2 + extraArgs];
5151 ++extraArgs;
5152 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005153 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005154 if (sparse) {
5155 params.texelOut = arguments[2 + extraArgs];
5156 ++extraArgs;
5157 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005158 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005159 if (cracked.gather && ! sampler.shadow) {
5160 // default component is 0, if missing, otherwise an argument
5161 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005162 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005163 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005164 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005165 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005166 }
Chao Chen3a137962018-09-19 11:41:27 -07005167 spv::Id resultStruct = spv::NoResult;
5168 if (imageFootprint) {
5169 //Following three extra arguments
5170 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5171 params.granularity = arguments[2 + extraArgs];
5172 params.coarse = arguments[3 + extraArgs];
5173 resultStruct = arguments[4 + extraArgs];
5174 extraArgs += 3;
5175 }
5176#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005177 // bias
5178 if (bias) {
5179 params.bias = arguments[2 + extraArgs];
5180 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005181 }
John Kessenichfc51d282015-08-19 13:34:18 -06005182
John Kessenicha28f7a72019-08-06 07:00:58 -06005183#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005184 if (imageFootprint) {
5185 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5186 builder.addCapability(spv::CapabilityImageFootprintNV);
5187
5188
5189 //resultStructType(OpenGL type) contains 5 elements:
5190 //struct gl_TextureFootprint2DNV {
5191 // uvec2 anchor;
5192 // uvec2 offset;
5193 // uvec2 mask;
5194 // uint lod;
5195 // uint granularity;
5196 //};
5197 //or
5198 //struct gl_TextureFootprint3DNV {
5199 // uvec3 anchor;
5200 // uvec3 offset;
5201 // uvec2 mask;
5202 // uint lod;
5203 // uint granularity;
5204 //};
5205 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5206 assert(builder.isStructType(resultStructType));
5207
5208 //resType (SPIR-V type) contains 6 elements:
5209 //Member 0 must be a Boolean type scalar(LOD),
5210 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5211 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5212 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5213 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5214 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5215 std::vector<spv::Id> members;
5216 members.push_back(resultType());
5217 for (int i = 0; i < 5; i++) {
5218 members.push_back(builder.getContainedTypeId(resultStructType, i));
5219 }
5220 spv::Id resType = builder.makeStructType(members, "ResType");
5221
5222 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005223 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5224 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005225
5226 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5227 for (int i = 0; i < 5; i++) {
5228 builder.clearAccessChain();
5229 builder.setAccessChainLValue(resultStruct);
5230
5231 //Accessing to a struct we created, no coherent flag is set
5232 spv::Builder::AccessChain::CoherentFlags flags;
5233 flags.clear();
5234
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005235 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005236 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02005237 i+1), TranslateNonUniformDecoration(imageType.getQualifier()));
Chao Chen3a137962018-09-19 11:41:27 -07005238 }
5239 return builder.createCompositeExtract(res, resultType(), 0);
5240 }
5241#endif
5242
John Kessenich65336482016-06-16 14:06:26 -06005243 // projective component (might not to move)
5244 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5245 // are divided by the last component of P."
5246 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5247 // unused components will appear after all used components."
5248 if (cracked.proj) {
5249 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5250 int projTargetComp;
5251 switch (sampler.dim) {
5252 case glslang::Esd1D: projTargetComp = 1; break;
5253 case glslang::Esd2D: projTargetComp = 2; break;
5254 case glslang::EsdRect: projTargetComp = 2; break;
5255 default: projTargetComp = projSourceComp; break;
5256 }
5257 // copy the projective coordinate if we have to
5258 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005259 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005260 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005261 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005262 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005263 }
5264 }
5265
John Kessenichf8d1d742019-10-21 06:55:11 -06005266#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005267 // nonprivate
5268 if (imageType.getQualifier().nonprivate) {
5269 params.nonprivate = true;
5270 }
5271
5272 // volatile
5273 if (imageType.getQualifier().volatil) {
5274 params.volatil = true;
5275 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005276#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005277
St0fFa1184dd2018-04-09 21:08:14 +02005278 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005279 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5280 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005281 );
LoopDawg4425f242018-02-18 11:40:01 -07005282
5283 if (components != node->getType().getVectorSize())
5284 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5285
5286 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005287}
5288
5289spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5290{
5291 // Grab the function's pointer from the previously created function
5292 spv::Function* function = functionMap[node->getName().c_str()];
5293 if (! function)
5294 return 0;
5295
5296 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5297 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5298
5299 // See comments in makeFunctions() for details about the semantics for parameter passing.
5300 //
5301 // These imply we need a four step process:
5302 // 1. Evaluate the arguments
5303 // 2. Allocate and make copies of in, out, and inout arguments
5304 // 3. Make the call
5305 // 4. Copy back the results
5306
John Kessenichd3ed90b2018-05-04 11:43:03 -06005307 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005308 std::vector<spv::Builder::AccessChain> lValues;
5309 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005310 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005311 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005312 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005313 // build l-value
5314 builder.clearAccessChain();
5315 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005316 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005317 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005318 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005319 // save l-value
5320 lValues.push_back(builder.getAccessChain());
5321 } else {
5322 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005323 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005324 }
5325 }
5326
5327 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5328 // copy the original into that space.
5329 //
5330 // Also, build up the list of actual arguments to pass in for the call
5331 int lValueCount = 0;
5332 int rValueCount = 0;
5333 std::vector<spv::Id> spvArgs;
5334 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5335 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005336 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005337 builder.setAccessChain(lValues[lValueCount]);
5338 arg = builder.accessChainGetLValue();
5339 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005340 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005341 // need space to hold the copy
John Kessenich435dd802020-06-30 01:27:08 -06005342 arg = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction,
John Kessenich8985fc92020-03-03 10:25:07 -07005343 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005344 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5345 // need to copy the input into output space
5346 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005347 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005348 builder.clearAccessChain();
5349 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005350 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005351 }
5352 ++lValueCount;
5353 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005354 // process r-value, which involves a copy for a type mismatch
John Kessenich4df10332020-06-26 08:37:06 -06005355 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a]) ||
John Kessenich435dd802020-06-30 01:27:08 -06005356 TranslatePrecisionDecoration(*argTypes[a]) != function->getParamPrecision(a))
John Kessenich4df10332020-06-26 08:37:06 -06005357 {
John Kessenich435dd802020-06-30 01:27:08 -06005358 spv::Id argCopy = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction, function->getParamType(a), "arg");
John Kessenichd3ed90b2018-05-04 11:43:03 -06005359 builder.clearAccessChain();
5360 builder.setAccessChainLValue(argCopy);
5361 multiTypeStore(*argTypes[a], rValues[rValueCount]);
John Kessenich435dd802020-06-30 01:27:08 -06005362 arg = builder.createLoad(argCopy, function->getParamPrecision(a));
John Kessenichd3ed90b2018-05-04 11:43:03 -06005363 } else
5364 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005365 ++rValueCount;
5366 }
5367 spvArgs.push_back(arg);
5368 }
5369
5370 // 3. Make the call.
5371 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005372 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005373
5374 // 4. Copy back out an "out" arguments.
5375 lValueCount = 0;
5376 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005377 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005378 ++lValueCount;
5379 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005380 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
John Kessenich435dd802020-06-30 01:27:08 -06005381 spv::Id copy = builder.createLoad(spvArgs[a], spv::NoPrecision);
John Kessenich140f3df2015-06-26 16:58:36 -06005382 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005383 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005384 }
5385 ++lValueCount;
5386 }
5387 }
5388
5389 return result;
5390}
5391
5392// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005393spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005394 spv::Id typeId, spv::Id left, spv::Id right,
5395 glslang::TBasicType typeProxy, bool reduceComparison)
5396{
John Kessenich66011cb2018-03-06 16:12:04 -07005397 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5398 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005399 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005400
5401 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005402 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005403 bool comparison = false;
5404
5405 switch (op) {
5406 case glslang::EOpAdd:
5407 case glslang::EOpAddAssign:
5408 if (isFloat)
5409 binOp = spv::OpFAdd;
5410 else
5411 binOp = spv::OpIAdd;
5412 break;
5413 case glslang::EOpSub:
5414 case glslang::EOpSubAssign:
5415 if (isFloat)
5416 binOp = spv::OpFSub;
5417 else
5418 binOp = spv::OpISub;
5419 break;
5420 case glslang::EOpMul:
5421 case glslang::EOpMulAssign:
5422 if (isFloat)
5423 binOp = spv::OpFMul;
5424 else
5425 binOp = spv::OpIMul;
5426 break;
5427 case glslang::EOpVectorTimesScalar:
5428 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005429 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005430 if (builder.isVector(right))
5431 std::swap(left, right);
5432 assert(builder.isScalar(right));
5433 needMatchingVectors = false;
5434 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005435 } else if (isFloat)
5436 binOp = spv::OpFMul;
5437 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005438 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005439 break;
5440 case glslang::EOpVectorTimesMatrix:
5441 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005442 binOp = spv::OpVectorTimesMatrix;
5443 break;
5444 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005445 binOp = spv::OpMatrixTimesVector;
5446 break;
5447 case glslang::EOpMatrixTimesScalar:
5448 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005449 binOp = spv::OpMatrixTimesScalar;
5450 break;
5451 case glslang::EOpMatrixTimesMatrix:
5452 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005453 binOp = spv::OpMatrixTimesMatrix;
5454 break;
5455 case glslang::EOpOuterProduct:
5456 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005457 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005458 break;
5459
5460 case glslang::EOpDiv:
5461 case glslang::EOpDivAssign:
5462 if (isFloat)
5463 binOp = spv::OpFDiv;
5464 else if (isUnsigned)
5465 binOp = spv::OpUDiv;
5466 else
5467 binOp = spv::OpSDiv;
5468 break;
5469 case glslang::EOpMod:
5470 case glslang::EOpModAssign:
5471 if (isFloat)
5472 binOp = spv::OpFMod;
5473 else if (isUnsigned)
5474 binOp = spv::OpUMod;
5475 else
5476 binOp = spv::OpSMod;
5477 break;
5478 case glslang::EOpRightShift:
5479 case glslang::EOpRightShiftAssign:
5480 if (isUnsigned)
5481 binOp = spv::OpShiftRightLogical;
5482 else
5483 binOp = spv::OpShiftRightArithmetic;
5484 break;
5485 case glslang::EOpLeftShift:
5486 case glslang::EOpLeftShiftAssign:
5487 binOp = spv::OpShiftLeftLogical;
5488 break;
5489 case glslang::EOpAnd:
5490 case glslang::EOpAndAssign:
5491 binOp = spv::OpBitwiseAnd;
5492 break;
5493 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005494 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005495 binOp = spv::OpLogicalAnd;
5496 break;
5497 case glslang::EOpInclusiveOr:
5498 case glslang::EOpInclusiveOrAssign:
5499 binOp = spv::OpBitwiseOr;
5500 break;
5501 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005502 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005503 binOp = spv::OpLogicalOr;
5504 break;
5505 case glslang::EOpExclusiveOr:
5506 case glslang::EOpExclusiveOrAssign:
5507 binOp = spv::OpBitwiseXor;
5508 break;
5509 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005510 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005511 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005512 break;
5513
Ian Romanickb3bd4022019-01-21 08:57:25 -08005514 case glslang::EOpAbsDifference:
5515 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5516 break;
5517
5518 case glslang::EOpAddSaturate:
5519 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5520 break;
5521
5522 case glslang::EOpSubSaturate:
5523 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5524 break;
5525
5526 case glslang::EOpAverage:
5527 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5528 break;
5529
5530 case glslang::EOpAverageRounded:
5531 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5532 break;
5533
5534 case glslang::EOpMul32x16:
5535 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5536 break;
5537
John Kessenich140f3df2015-06-26 16:58:36 -06005538 case glslang::EOpLessThan:
5539 case glslang::EOpGreaterThan:
5540 case glslang::EOpLessThanEqual:
5541 case glslang::EOpGreaterThanEqual:
5542 case glslang::EOpEqual:
5543 case glslang::EOpNotEqual:
5544 case glslang::EOpVectorEqual:
5545 case glslang::EOpVectorNotEqual:
5546 comparison = true;
5547 break;
5548 default:
5549 break;
5550 }
5551
John Kessenich7c1aa102015-10-15 13:29:11 -06005552 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005553 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005554 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005555 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5556 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005557 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005558
5559 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005560 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005561 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005562
qining25262b32016-05-06 17:25:16 -04005563 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005564 decorations.addNoContraction(builder, result);
5565 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005566 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005567 }
5568
5569 if (! comparison)
5570 return 0;
5571
John Kessenich7c1aa102015-10-15 13:29:11 -06005572 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005573
John Kessenich4583b612016-08-07 19:14:22 -06005574 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005575 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5576 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005577 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005578 return result;
5579 }
John Kessenich140f3df2015-06-26 16:58:36 -06005580
5581 switch (op) {
5582 case glslang::EOpLessThan:
5583 if (isFloat)
5584 binOp = spv::OpFOrdLessThan;
5585 else if (isUnsigned)
5586 binOp = spv::OpULessThan;
5587 else
5588 binOp = spv::OpSLessThan;
5589 break;
5590 case glslang::EOpGreaterThan:
5591 if (isFloat)
5592 binOp = spv::OpFOrdGreaterThan;
5593 else if (isUnsigned)
5594 binOp = spv::OpUGreaterThan;
5595 else
5596 binOp = spv::OpSGreaterThan;
5597 break;
5598 case glslang::EOpLessThanEqual:
5599 if (isFloat)
5600 binOp = spv::OpFOrdLessThanEqual;
5601 else if (isUnsigned)
5602 binOp = spv::OpULessThanEqual;
5603 else
5604 binOp = spv::OpSLessThanEqual;
5605 break;
5606 case glslang::EOpGreaterThanEqual:
5607 if (isFloat)
5608 binOp = spv::OpFOrdGreaterThanEqual;
5609 else if (isUnsigned)
5610 binOp = spv::OpUGreaterThanEqual;
5611 else
5612 binOp = spv::OpSGreaterThanEqual;
5613 break;
5614 case glslang::EOpEqual:
5615 case glslang::EOpVectorEqual:
5616 if (isFloat)
5617 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005618 else if (isBool)
5619 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005620 else
5621 binOp = spv::OpIEqual;
5622 break;
5623 case glslang::EOpNotEqual:
5624 case glslang::EOpVectorNotEqual:
5625 if (isFloat)
Graeme Leese65ce5662020-06-05 13:32:51 +01005626 binOp = spv::OpFUnordNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005627 else if (isBool)
5628 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005629 else
5630 binOp = spv::OpINotEqual;
5631 break;
5632 default:
5633 break;
5634 }
5635
qining25262b32016-05-06 17:25:16 -04005636 if (binOp != spv::OpNop) {
5637 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005638 decorations.addNoContraction(builder, result);
5639 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005640 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005641 }
John Kessenich140f3df2015-06-26 16:58:36 -06005642
5643 return 0;
5644}
5645
John Kessenich04bb8a02015-12-12 12:28:14 -07005646//
5647// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5648// These can be any of:
5649//
5650// matrix * scalar
5651// scalar * matrix
5652// matrix * matrix linear algebraic
5653// matrix * vector
5654// vector * matrix
5655// matrix * matrix componentwise
5656// matrix op matrix op in {+, -, /}
5657// matrix op scalar op in {+, -, /}
5658// scalar op matrix op in {+, -, /}
5659//
John Kessenichead86222018-03-28 18:01:20 -06005660spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5661 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005662{
5663 bool firstClass = true;
5664
5665 // First, handle first-class matrix operations (* and matrix/scalar)
5666 switch (op) {
5667 case spv::OpFDiv:
5668 if (builder.isMatrix(left) && builder.isScalar(right)) {
5669 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005670 spv::Id resultType = builder.getTypeId(right);
5671 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005672 op = spv::OpMatrixTimesScalar;
5673 } else
5674 firstClass = false;
5675 break;
5676 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005677 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005678 std::swap(left, right);
5679 assert(builder.isScalar(right));
5680 break;
5681 case spv::OpVectorTimesMatrix:
5682 assert(builder.isVector(left));
5683 assert(builder.isMatrix(right));
5684 break;
5685 case spv::OpMatrixTimesVector:
5686 assert(builder.isMatrix(left));
5687 assert(builder.isVector(right));
5688 break;
5689 case spv::OpMatrixTimesMatrix:
5690 assert(builder.isMatrix(left));
5691 assert(builder.isMatrix(right));
5692 break;
5693 default:
5694 firstClass = false;
5695 break;
5696 }
5697
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005698 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5699 firstClass = true;
5700
qining25262b32016-05-06 17:25:16 -04005701 if (firstClass) {
5702 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005703 decorations.addNoContraction(builder, result);
5704 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005705 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005706 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005707
LoopDawg592860c2016-06-09 08:57:35 -06005708 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005709 // The result type of all of them is the same type as the (a) matrix operand.
5710 // The algorithm is to:
5711 // - break the matrix(es) into vectors
5712 // - smear any scalar to a vector
5713 // - do vector operations
5714 // - make a matrix out the vector results
5715 switch (op) {
5716 case spv::OpFAdd:
5717 case spv::OpFSub:
5718 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005719 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005720 case spv::OpFMul:
5721 {
5722 // one time set up...
5723 bool leftMat = builder.isMatrix(left);
5724 bool rightMat = builder.isMatrix(right);
5725 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5726 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5727 spv::Id scalarType = builder.getScalarTypeId(typeId);
5728 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5729 std::vector<spv::Id> results;
5730 spv::Id smearVec = spv::NoResult;
5731 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005732 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005733 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005734 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005735
5736 // do each vector op
5737 for (unsigned int c = 0; c < numCols; ++c) {
5738 std::vector<unsigned int> indexes;
5739 indexes.push_back(c);
5740 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5741 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005742 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005743 decorations.addNoContraction(builder, result);
5744 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005745 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005746 }
5747
5748 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005749 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005750 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005751 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005752 }
5753 default:
5754 assert(0);
5755 return spv::NoResult;
5756 }
5757}
5758
John Kessenichead86222018-03-28 18:01:20 -06005759spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005760 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005761{
5762 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005763 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005764 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005765 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5766 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005767
5768 switch (op) {
5769 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005770 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005771 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005772 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005773 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005774 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005775 unaryOp = spv::OpSNegate;
5776 break;
5777
5778 case glslang::EOpLogicalNot:
5779 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005780 unaryOp = spv::OpLogicalNot;
5781 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005782 case glslang::EOpBitwiseNot:
5783 unaryOp = spv::OpNot;
5784 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005785
John Kessenich140f3df2015-06-26 16:58:36 -06005786 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005787 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005788 break;
5789 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005790 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005791 break;
5792 case glslang::EOpTranspose:
5793 unaryOp = spv::OpTranspose;
5794 break;
5795
5796 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005797 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005798 break;
5799 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005800 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005801 break;
5802 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005803 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005804 break;
5805 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005806 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005807 break;
5808 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005809 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005810 break;
5811 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005812 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005813 break;
5814 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005815 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005816 break;
5817 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005818 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005819 break;
5820
5821 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005822 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005823 break;
5824 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005825 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005826 break;
5827 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005828 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005829 break;
5830 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005831 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005832 break;
5833 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005834 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005835 break;
5836 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005837 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005838 break;
5839
5840 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005841 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005842 break;
5843 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005844 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005845 break;
5846
5847 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005848 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005849 break;
5850 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005851 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005852 break;
5853 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005854 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005855 break;
5856 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005857 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005858 break;
5859 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005860 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005861 break;
5862 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005863 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005864 break;
5865
5866 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005867 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005868 break;
5869 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005870 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005871 break;
5872 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005873 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005874 break;
5875 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005876 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005877 break;
5878 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005879 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005880 break;
5881 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005882 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005883 break;
5884
5885 case glslang::EOpIsNan:
5886 unaryOp = spv::OpIsNan;
5887 break;
5888 case glslang::EOpIsInf:
5889 unaryOp = spv::OpIsInf;
5890 break;
LoopDawg592860c2016-06-09 08:57:35 -06005891 case glslang::EOpIsFinite:
5892 unaryOp = spv::OpIsFinite;
5893 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005894
Rex Xucbc426e2015-12-15 16:03:10 +08005895 case glslang::EOpFloatBitsToInt:
5896 case glslang::EOpFloatBitsToUint:
5897 case glslang::EOpIntBitsToFloat:
5898 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005899 case glslang::EOpDoubleBitsToInt64:
5900 case glslang::EOpDoubleBitsToUint64:
5901 case glslang::EOpInt64BitsToDouble:
5902 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005903 case glslang::EOpFloat16BitsToInt16:
5904 case glslang::EOpFloat16BitsToUint16:
5905 case glslang::EOpInt16BitsToFloat16:
5906 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005907 unaryOp = spv::OpBitcast;
5908 break;
5909
John Kessenich140f3df2015-06-26 16:58:36 -06005910 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005911 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005912 break;
5913 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005914 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005915 break;
5916 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005917 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005918 break;
5919 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005920 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005921 break;
5922 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005923 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005924 break;
5925 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005926 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005927 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005928#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005929 case glslang::EOpPackSnorm4x8:
5930 libCall = spv::GLSLstd450PackSnorm4x8;
5931 break;
5932 case glslang::EOpUnpackSnorm4x8:
5933 libCall = spv::GLSLstd450UnpackSnorm4x8;
5934 break;
5935 case glslang::EOpPackUnorm4x8:
5936 libCall = spv::GLSLstd450PackUnorm4x8;
5937 break;
5938 case glslang::EOpUnpackUnorm4x8:
5939 libCall = spv::GLSLstd450UnpackUnorm4x8;
5940 break;
5941 case glslang::EOpPackDouble2x32:
5942 libCall = spv::GLSLstd450PackDouble2x32;
5943 break;
5944 case glslang::EOpUnpackDouble2x32:
5945 libCall = spv::GLSLstd450UnpackDouble2x32;
5946 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005947#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005948
Rex Xu8ff43de2016-04-22 16:51:45 +08005949 case glslang::EOpPackInt2x32:
5950 case glslang::EOpUnpackInt2x32:
5951 case glslang::EOpPackUint2x32:
5952 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005953 case glslang::EOpPack16:
5954 case glslang::EOpPack32:
5955 case glslang::EOpPack64:
5956 case glslang::EOpUnpack32:
5957 case glslang::EOpUnpack16:
5958 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005959 case glslang::EOpPackInt2x16:
5960 case glslang::EOpUnpackInt2x16:
5961 case glslang::EOpPackUint2x16:
5962 case glslang::EOpUnpackUint2x16:
5963 case glslang::EOpPackInt4x16:
5964 case glslang::EOpUnpackInt4x16:
5965 case glslang::EOpPackUint4x16:
5966 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005967 case glslang::EOpPackFloat2x16:
5968 case glslang::EOpUnpackFloat2x16:
5969 unaryOp = spv::OpBitcast;
5970 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005971
John Kessenich140f3df2015-06-26 16:58:36 -06005972 case glslang::EOpDPdx:
5973 unaryOp = spv::OpDPdx;
5974 break;
5975 case glslang::EOpDPdy:
5976 unaryOp = spv::OpDPdy;
5977 break;
5978 case glslang::EOpFwidth:
5979 unaryOp = spv::OpFwidth;
5980 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005981
John Kessenich140f3df2015-06-26 16:58:36 -06005982 case glslang::EOpAny:
5983 unaryOp = spv::OpAny;
5984 break;
5985 case glslang::EOpAll:
5986 unaryOp = spv::OpAll;
5987 break;
5988
5989 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005990 if (isFloat)
5991 libCall = spv::GLSLstd450FAbs;
5992 else
5993 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005994 break;
5995 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005996 if (isFloat)
5997 libCall = spv::GLSLstd450FSign;
5998 else
5999 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06006000 break;
6001
John Kessenicha28f7a72019-08-06 07:00:58 -06006002#ifndef GLSLANG_WEB
6003 case glslang::EOpDPdxFine:
6004 unaryOp = spv::OpDPdxFine;
6005 break;
6006 case glslang::EOpDPdyFine:
6007 unaryOp = spv::OpDPdyFine;
6008 break;
6009 case glslang::EOpFwidthFine:
6010 unaryOp = spv::OpFwidthFine;
6011 break;
6012 case glslang::EOpDPdxCoarse:
6013 unaryOp = spv::OpDPdxCoarse;
6014 break;
6015 case glslang::EOpDPdyCoarse:
6016 unaryOp = spv::OpDPdyCoarse;
6017 break;
6018 case glslang::EOpFwidthCoarse:
6019 unaryOp = spv::OpFwidthCoarse;
6020 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04006021 case glslang::EOpRayQueryProceed:
6022 unaryOp = spv::OpRayQueryProceedKHR;
6023 break;
6024 case glslang::EOpRayQueryGetRayTMin:
6025 unaryOp = spv::OpRayQueryGetRayTMinKHR;
6026 break;
6027 case glslang::EOpRayQueryGetRayFlags:
6028 unaryOp = spv::OpRayQueryGetRayFlagsKHR;
6029 break;
6030 case glslang::EOpRayQueryGetWorldRayOrigin:
6031 unaryOp = spv::OpRayQueryGetWorldRayOriginKHR;
6032 break;
6033 case glslang::EOpRayQueryGetWorldRayDirection:
6034 unaryOp = spv::OpRayQueryGetWorldRayDirectionKHR;
6035 break;
6036 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
6037 unaryOp = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
6038 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006039 case glslang::EOpInterpolateAtCentroid:
6040 if (typeProxy == glslang::EbtFloat16)
6041 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6042 libCall = spv::GLSLstd450InterpolateAtCentroid;
6043 break;
John Kessenichfc51d282015-08-19 13:34:18 -06006044 case glslang::EOpAtomicCounterIncrement:
6045 case glslang::EOpAtomicCounterDecrement:
6046 case glslang::EOpAtomicCounter:
6047 {
6048 // Handle all of the atomics in one place, in createAtomicOperation()
6049 std::vector<spv::Id> operands;
6050 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006051 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06006052 }
6053
John Kessenichfc51d282015-08-19 13:34:18 -06006054 case glslang::EOpBitFieldReverse:
6055 unaryOp = spv::OpBitReverse;
6056 break;
6057 case glslang::EOpBitCount:
6058 unaryOp = spv::OpBitCount;
6059 break;
6060 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006061 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006062 break;
6063 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006064 if (isUnsigned)
6065 libCall = spv::GLSLstd450FindUMsb;
6066 else
6067 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006068 break;
6069
Ian Romanickb3bd4022019-01-21 08:57:25 -08006070 case glslang::EOpCountLeadingZeros:
6071 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6072 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6073 unaryOp = spv::OpUCountLeadingZerosINTEL;
6074 break;
6075
6076 case glslang::EOpCountTrailingZeros:
6077 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6078 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6079 unaryOp = spv::OpUCountTrailingZerosINTEL;
6080 break;
6081
Rex Xu574ab042016-04-14 16:53:07 +08006082 case glslang::EOpBallot:
6083 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006084 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006085 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08006086 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08006087 case glslang::EOpMinInvocations:
6088 case glslang::EOpMaxInvocations:
6089 case glslang::EOpAddInvocations:
6090 case glslang::EOpMinInvocationsNonUniform:
6091 case glslang::EOpMaxInvocationsNonUniform:
6092 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006093 case glslang::EOpMinInvocationsInclusiveScan:
6094 case glslang::EOpMaxInvocationsInclusiveScan:
6095 case glslang::EOpAddInvocationsInclusiveScan:
6096 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6097 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6098 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6099 case glslang::EOpMinInvocationsExclusiveScan:
6100 case glslang::EOpMaxInvocationsExclusiveScan:
6101 case glslang::EOpAddInvocationsExclusiveScan:
6102 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6103 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6104 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08006105 {
6106 std::vector<spv::Id> operands;
6107 operands.push_back(operand);
6108 return createInvocationsOperation(op, typeId, operands, typeProxy);
6109 }
John Kessenich66011cb2018-03-06 16:12:04 -07006110 case glslang::EOpSubgroupAll:
6111 case glslang::EOpSubgroupAny:
6112 case glslang::EOpSubgroupAllEqual:
6113 case glslang::EOpSubgroupBroadcastFirst:
6114 case glslang::EOpSubgroupBallot:
6115 case glslang::EOpSubgroupInverseBallot:
6116 case glslang::EOpSubgroupBallotBitCount:
6117 case glslang::EOpSubgroupBallotInclusiveBitCount:
6118 case glslang::EOpSubgroupBallotExclusiveBitCount:
6119 case glslang::EOpSubgroupBallotFindLSB:
6120 case glslang::EOpSubgroupBallotFindMSB:
6121 case glslang::EOpSubgroupAdd:
6122 case glslang::EOpSubgroupMul:
6123 case glslang::EOpSubgroupMin:
6124 case glslang::EOpSubgroupMax:
6125 case glslang::EOpSubgroupAnd:
6126 case glslang::EOpSubgroupOr:
6127 case glslang::EOpSubgroupXor:
6128 case glslang::EOpSubgroupInclusiveAdd:
6129 case glslang::EOpSubgroupInclusiveMul:
6130 case glslang::EOpSubgroupInclusiveMin:
6131 case glslang::EOpSubgroupInclusiveMax:
6132 case glslang::EOpSubgroupInclusiveAnd:
6133 case glslang::EOpSubgroupInclusiveOr:
6134 case glslang::EOpSubgroupInclusiveXor:
6135 case glslang::EOpSubgroupExclusiveAdd:
6136 case glslang::EOpSubgroupExclusiveMul:
6137 case glslang::EOpSubgroupExclusiveMin:
6138 case glslang::EOpSubgroupExclusiveMax:
6139 case glslang::EOpSubgroupExclusiveAnd:
6140 case glslang::EOpSubgroupExclusiveOr:
6141 case glslang::EOpSubgroupExclusiveXor:
6142 case glslang::EOpSubgroupQuadSwapHorizontal:
6143 case glslang::EOpSubgroupQuadSwapVertical:
6144 case glslang::EOpSubgroupQuadSwapDiagonal: {
6145 std::vector<spv::Id> operands;
6146 operands.push_back(operand);
6147 return createSubgroupOperation(op, typeId, operands, typeProxy);
6148 }
Rex Xu9d93a232016-05-05 12:30:44 +08006149 case glslang::EOpMbcnt:
6150 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6151 libCall = spv::MbcntAMD;
6152 break;
6153
6154 case glslang::EOpCubeFaceIndex:
6155 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6156 libCall = spv::CubeFaceIndexAMD;
6157 break;
6158
6159 case glslang::EOpCubeFaceCoord:
6160 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6161 libCall = spv::CubeFaceCoordAMD;
6162 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006163 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006164 unaryOp = spv::OpGroupNonUniformPartitionNV;
6165 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006166 case glslang::EOpConstructReference:
6167 unaryOp = spv::OpBitcast;
6168 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006169#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006170
6171 case glslang::EOpCopyObject:
6172 unaryOp = spv::OpCopyObject;
6173 break;
6174
John Kessenich140f3df2015-06-26 16:58:36 -06006175 default:
6176 return 0;
6177 }
6178
6179 spv::Id id;
6180 if (libCall >= 0) {
6181 std::vector<spv::Id> args;
6182 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006183 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006184 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006185 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006186 }
John Kessenich140f3df2015-06-26 16:58:36 -06006187
John Kessenichb9197c82019-08-11 07:41:45 -06006188 decorations.addNoContraction(builder, id);
6189 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006190 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006191}
6192
John Kessenich7a53f762016-01-20 11:19:27 -07006193// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006194spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6195 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006196{
6197 // Handle unary operations vector by vector.
6198 // The result type is the same type as the original type.
6199 // The algorithm is to:
6200 // - break the matrix into vectors
6201 // - apply the operation to each vector
6202 // - make a matrix out the vector results
6203
6204 // get the types sorted out
6205 int numCols = builder.getNumColumns(operand);
6206 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006207 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6208 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006209 std::vector<spv::Id> results;
6210
6211 // do each vector op
6212 for (int c = 0; c < numCols; ++c) {
6213 std::vector<unsigned int> indexes;
6214 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006215 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6216 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006217 decorations.addNoContraction(builder, destVec);
6218 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006219 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006220 }
6221
6222 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006223 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006224 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006225 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006226}
6227
John Kessenichad7645f2018-06-04 19:11:25 -06006228// For converting integers where both the bitwidth and the signedness could
6229// change, but only do the width change here. The caller is still responsible
6230// for the signedness conversion.
6231spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006232{
John Kessenichad7645f2018-06-04 19:11:25 -06006233 // Get the result type width, based on the type to convert to.
6234 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006235 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006236 case glslang::EOpConvInt16ToUint8:
6237 case glslang::EOpConvIntToUint8:
6238 case glslang::EOpConvInt64ToUint8:
6239 case glslang::EOpConvUint16ToInt8:
6240 case glslang::EOpConvUintToInt8:
6241 case glslang::EOpConvUint64ToInt8:
6242 width = 8;
6243 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006244 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006245 case glslang::EOpConvIntToUint16:
6246 case glslang::EOpConvInt64ToUint16:
6247 case glslang::EOpConvUint8ToInt16:
6248 case glslang::EOpConvUintToInt16:
6249 case glslang::EOpConvUint64ToInt16:
6250 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006251 break;
6252 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006253 case glslang::EOpConvInt16ToUint:
6254 case glslang::EOpConvInt64ToUint:
6255 case glslang::EOpConvUint8ToInt:
6256 case glslang::EOpConvUint16ToInt:
6257 case glslang::EOpConvUint64ToInt:
6258 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006259 break;
6260 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006261 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006262 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006263 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006264 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006265 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006266 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006267 break;
6268
6269 default:
6270 assert(false && "Default missing");
6271 break;
6272 }
6273
John Kessenichad7645f2018-06-04 19:11:25 -06006274 // Get the conversion operation and result type,
6275 // based on the target width, but the source type.
6276 spv::Id type = spv::NoType;
6277 spv::Op convOp = spv::OpNop;
6278 switch(op) {
6279 case glslang::EOpConvInt8ToUint16:
6280 case glslang::EOpConvInt8ToUint:
6281 case glslang::EOpConvInt8ToUint64:
6282 case glslang::EOpConvInt16ToUint8:
6283 case glslang::EOpConvInt16ToUint:
6284 case glslang::EOpConvInt16ToUint64:
6285 case glslang::EOpConvIntToUint8:
6286 case glslang::EOpConvIntToUint16:
6287 case glslang::EOpConvIntToUint64:
6288 case glslang::EOpConvInt64ToUint8:
6289 case glslang::EOpConvInt64ToUint16:
6290 case glslang::EOpConvInt64ToUint:
6291 convOp = spv::OpSConvert;
6292 type = builder.makeIntType(width);
6293 break;
6294 default:
6295 convOp = spv::OpUConvert;
6296 type = builder.makeUintType(width);
6297 break;
6298 }
6299
John Kessenich66011cb2018-03-06 16:12:04 -07006300 if (vectorSize > 0)
6301 type = builder.makeVectorType(type, vectorSize);
6302
John Kessenichad7645f2018-06-04 19:11:25 -06006303 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006304}
6305
John Kessenichead86222018-03-28 18:01:20 -06006306spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6307 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006308{
6309 spv::Op convOp = spv::OpNop;
6310 spv::Id zero = 0;
6311 spv::Id one = 0;
6312
6313 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6314
6315 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006316 case glslang::EOpConvIntToBool:
6317 case glslang::EOpConvUintToBool:
6318 zero = builder.makeUintConstant(0);
6319 zero = makeSmearedConstant(zero, vectorSize);
6320 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006321 case glslang::EOpConvFloatToBool:
6322 zero = builder.makeFloatConstant(0.0F);
6323 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006324 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006325 case glslang::EOpConvBoolToFloat:
6326 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006327 zero = builder.makeFloatConstant(0.0F);
6328 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006329 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006330
John Kessenich140f3df2015-06-26 16:58:36 -06006331 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006332 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006333#ifndef GLSLANG_WEB
6334 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006335 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006336 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006337 } else
6338#endif
6339 {
6340 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006341 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006342 }
Rex Xucabbb782017-03-24 13:41:14 +08006343
John Kessenich140f3df2015-06-26 16:58:36 -06006344 convOp = spv::OpSelect;
6345 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006346
John Kessenich140f3df2015-06-26 16:58:36 -06006347 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006348 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006349#ifndef GLSLANG_WEB
6350 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006351 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006352 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006353 } else
6354#endif
6355 {
6356 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006357 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006358 }
Rex Xucabbb782017-03-24 13:41:14 +08006359
John Kessenich140f3df2015-06-26 16:58:36 -06006360 convOp = spv::OpSelect;
6361 break;
6362
John Kessenich66011cb2018-03-06 16:12:04 -07006363 case glslang::EOpConvInt8ToFloat16:
6364 case glslang::EOpConvInt8ToFloat:
6365 case glslang::EOpConvInt8ToDouble:
6366 case glslang::EOpConvInt16ToFloat16:
6367 case glslang::EOpConvInt16ToFloat:
6368 case glslang::EOpConvInt16ToDouble:
6369 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006370 case glslang::EOpConvIntToFloat:
6371 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006372 case glslang::EOpConvInt64ToFloat:
6373 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006374 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006375 convOp = spv::OpConvertSToF;
6376 break;
6377
John Kessenich66011cb2018-03-06 16:12:04 -07006378 case glslang::EOpConvUint8ToFloat16:
6379 case glslang::EOpConvUint8ToFloat:
6380 case glslang::EOpConvUint8ToDouble:
6381 case glslang::EOpConvUint16ToFloat16:
6382 case glslang::EOpConvUint16ToFloat:
6383 case glslang::EOpConvUint16ToDouble:
6384 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006385 case glslang::EOpConvUintToFloat:
6386 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006387 case glslang::EOpConvUint64ToFloat:
6388 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006389 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006390 convOp = spv::OpConvertUToF;
6391 break;
6392
John Kessenich66011cb2018-03-06 16:12:04 -07006393 case glslang::EOpConvFloat16ToInt8:
6394 case glslang::EOpConvFloatToInt8:
6395 case glslang::EOpConvDoubleToInt8:
6396 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006397 case glslang::EOpConvFloatToInt16:
6398 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006399 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006400 case glslang::EOpConvFloatToInt:
6401 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006402 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006403 case glslang::EOpConvFloatToInt64:
6404 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006405 convOp = spv::OpConvertFToS;
6406 break;
6407
John Kessenich66011cb2018-03-06 16:12:04 -07006408 case glslang::EOpConvUint8ToInt8:
6409 case glslang::EOpConvInt8ToUint8:
6410 case glslang::EOpConvUint16ToInt16:
6411 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006412 case glslang::EOpConvUintToInt:
6413 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006414 case glslang::EOpConvUint64ToInt64:
6415 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006416 if (builder.isInSpecConstCodeGenMode()) {
6417 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006418#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006419 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6420 zero = builder.makeUint8Constant(0);
6421 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006422 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006423 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6424 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006425 } else
6426#endif
6427 {
Rex Xucabbb782017-03-24 13:41:14 +08006428 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006429 }
qining189b2032016-04-12 23:16:20 -04006430 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006431 // Use OpIAdd, instead of OpBitcast to do the conversion when
6432 // generating for OpSpecConstantOp instruction.
6433 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6434 }
6435 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006436 convOp = spv::OpBitcast;
6437 break;
6438
John Kessenich66011cb2018-03-06 16:12:04 -07006439 case glslang::EOpConvFloat16ToUint8:
6440 case glslang::EOpConvFloatToUint8:
6441 case glslang::EOpConvDoubleToUint8:
6442 case glslang::EOpConvFloat16ToUint16:
6443 case glslang::EOpConvFloatToUint16:
6444 case glslang::EOpConvDoubleToUint16:
6445 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006446 case glslang::EOpConvFloatToUint:
6447 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006448 case glslang::EOpConvFloatToUint64:
6449 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006450 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006451 convOp = spv::OpConvertFToU;
6452 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006453
John Kessenich39697cd2019-08-08 10:35:51 -06006454#ifndef GLSLANG_WEB
6455 case glslang::EOpConvInt8ToBool:
6456 case glslang::EOpConvUint8ToBool:
6457 zero = builder.makeUint8Constant(0);
6458 zero = makeSmearedConstant(zero, vectorSize);
6459 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6460 case glslang::EOpConvInt16ToBool:
6461 case glslang::EOpConvUint16ToBool:
6462 zero = builder.makeUint16Constant(0);
6463 zero = makeSmearedConstant(zero, vectorSize);
6464 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6465 case glslang::EOpConvInt64ToBool:
6466 case glslang::EOpConvUint64ToBool:
6467 zero = builder.makeUint64Constant(0);
6468 zero = makeSmearedConstant(zero, vectorSize);
6469 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6470 case glslang::EOpConvDoubleToBool:
6471 zero = builder.makeDoubleConstant(0.0);
6472 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006473 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006474 case glslang::EOpConvFloat16ToBool:
6475 zero = builder.makeFloat16Constant(0.0F);
6476 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006477 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006478 case glslang::EOpConvBoolToDouble:
6479 convOp = spv::OpSelect;
6480 zero = builder.makeDoubleConstant(0.0);
6481 one = builder.makeDoubleConstant(1.0);
6482 break;
6483 case glslang::EOpConvBoolToFloat16:
6484 convOp = spv::OpSelect;
6485 zero = builder.makeFloat16Constant(0.0F);
6486 one = builder.makeFloat16Constant(1.0F);
6487 break;
6488 case glslang::EOpConvBoolToInt8:
6489 zero = builder.makeInt8Constant(0);
6490 one = builder.makeInt8Constant(1);
6491 convOp = spv::OpSelect;
6492 break;
6493 case glslang::EOpConvBoolToUint8:
6494 zero = builder.makeUint8Constant(0);
6495 one = builder.makeUint8Constant(1);
6496 convOp = spv::OpSelect;
6497 break;
6498 case glslang::EOpConvBoolToInt16:
6499 zero = builder.makeInt16Constant(0);
6500 one = builder.makeInt16Constant(1);
6501 convOp = spv::OpSelect;
6502 break;
6503 case glslang::EOpConvBoolToUint16:
6504 zero = builder.makeUint16Constant(0);
6505 one = builder.makeUint16Constant(1);
6506 convOp = spv::OpSelect;
6507 break;
6508 case glslang::EOpConvDoubleToFloat:
6509 case glslang::EOpConvFloatToDouble:
6510 case glslang::EOpConvDoubleToFloat16:
6511 case glslang::EOpConvFloat16ToDouble:
6512 case glslang::EOpConvFloatToFloat16:
6513 case glslang::EOpConvFloat16ToFloat:
6514 convOp = spv::OpFConvert;
6515 if (builder.isMatrixType(destType))
6516 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6517 break;
6518
John Kessenich66011cb2018-03-06 16:12:04 -07006519 case glslang::EOpConvInt8ToInt16:
6520 case glslang::EOpConvInt8ToInt:
6521 case glslang::EOpConvInt8ToInt64:
6522 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006523 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006524 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006525 case glslang::EOpConvIntToInt8:
6526 case glslang::EOpConvIntToInt16:
6527 case glslang::EOpConvIntToInt64:
6528 case glslang::EOpConvInt64ToInt8:
6529 case glslang::EOpConvInt64ToInt16:
6530 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006531 convOp = spv::OpSConvert;
6532 break;
6533
John Kessenich66011cb2018-03-06 16:12:04 -07006534 case glslang::EOpConvUint8ToUint16:
6535 case glslang::EOpConvUint8ToUint:
6536 case glslang::EOpConvUint8ToUint64:
6537 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006538 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006539 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006540 case glslang::EOpConvUintToUint8:
6541 case glslang::EOpConvUintToUint16:
6542 case glslang::EOpConvUintToUint64:
6543 case glslang::EOpConvUint64ToUint8:
6544 case glslang::EOpConvUint64ToUint16:
6545 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006546 convOp = spv::OpUConvert;
6547 break;
6548
John Kessenich66011cb2018-03-06 16:12:04 -07006549 case glslang::EOpConvInt8ToUint16:
6550 case glslang::EOpConvInt8ToUint:
6551 case glslang::EOpConvInt8ToUint64:
6552 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006553 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006554 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006555 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006556 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006557 case glslang::EOpConvIntToUint64:
6558 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006559 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006560 case glslang::EOpConvInt64ToUint:
6561 case glslang::EOpConvUint8ToInt16:
6562 case glslang::EOpConvUint8ToInt:
6563 case glslang::EOpConvUint8ToInt64:
6564 case glslang::EOpConvUint16ToInt8:
6565 case glslang::EOpConvUint16ToInt:
6566 case glslang::EOpConvUint16ToInt64:
6567 case glslang::EOpConvUintToInt8:
6568 case glslang::EOpConvUintToInt16:
6569 case glslang::EOpConvUintToInt64:
6570 case glslang::EOpConvUint64ToInt8:
6571 case glslang::EOpConvUint64ToInt16:
6572 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006573 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006574 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006575
6576 if (builder.isInSpecConstCodeGenMode()) {
6577 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006578 switch(op) {
6579 case glslang::EOpConvInt16ToUint8:
6580 case glslang::EOpConvIntToUint8:
6581 case glslang::EOpConvInt64ToUint8:
6582 case glslang::EOpConvUint16ToInt8:
6583 case glslang::EOpConvUintToInt8:
6584 case glslang::EOpConvUint64ToInt8:
6585 zero = builder.makeUint8Constant(0);
6586 break;
6587 case glslang::EOpConvInt8ToUint16:
6588 case glslang::EOpConvIntToUint16:
6589 case glslang::EOpConvInt64ToUint16:
6590 case glslang::EOpConvUint8ToInt16:
6591 case glslang::EOpConvUintToInt16:
6592 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006593 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006594 break;
6595 case glslang::EOpConvInt8ToUint:
6596 case glslang::EOpConvInt16ToUint:
6597 case glslang::EOpConvInt64ToUint:
6598 case glslang::EOpConvUint8ToInt:
6599 case glslang::EOpConvUint16ToInt:
6600 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006601 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006602 break;
6603 case glslang::EOpConvInt8ToUint64:
6604 case glslang::EOpConvInt16ToUint64:
6605 case glslang::EOpConvIntToUint64:
6606 case glslang::EOpConvUint8ToInt64:
6607 case glslang::EOpConvUint16ToInt64:
6608 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006609 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006610 break;
6611 default:
6612 assert(false && "Default missing");
6613 break;
6614 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006615 zero = makeSmearedConstant(zero, vectorSize);
6616 // Use OpIAdd, instead of OpBitcast to do the conversion when
6617 // generating for OpSpecConstantOp instruction.
6618 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6619 }
6620 // For normal run-time conversion instruction, use OpBitcast.
6621 convOp = spv::OpBitcast;
6622 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006623 case glslang::EOpConvUint64ToPtr:
6624 convOp = spv::OpConvertUToPtr;
6625 break;
6626 case glslang::EOpConvPtrToUint64:
6627 convOp = spv::OpConvertPtrToU;
6628 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006629 case glslang::EOpConvPtrToUvec2:
6630 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006631 if (builder.isVector(operand))
6632 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6633 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006634 convOp = spv::OpBitcast;
6635 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006636#endif
6637
John Kessenich140f3df2015-06-26 16:58:36 -06006638 default:
6639 break;
6640 }
6641
6642 spv::Id result = 0;
6643 if (convOp == spv::OpNop)
6644 return result;
6645
6646 if (convOp == spv::OpSelect) {
6647 zero = makeSmearedConstant(zero, vectorSize);
6648 one = makeSmearedConstant(one, vectorSize);
6649 result = builder.createTriOp(convOp, destType, operand, one, zero);
6650 } else
6651 result = builder.createUnaryOp(convOp, destType, operand);
6652
John Kessenichead86222018-03-28 18:01:20 -06006653 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006654 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006655 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006656}
6657
6658spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6659{
6660 if (vectorSize == 0)
6661 return constant;
6662
6663 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6664 std::vector<spv::Id> components;
6665 for (int c = 0; c < vectorSize; ++c)
6666 components.push_back(constant);
6667 return builder.makeCompositeConstant(vectorTypeId, components);
6668}
6669
John Kessenich426394d2015-07-23 10:22:48 -06006670// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006671spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6672 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6673 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006674{
6675 spv::Op opCode = spv::OpNop;
6676
6677 switch (op) {
6678 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006679 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006680 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006681 opCode = spv::OpAtomicIAdd;
Vikram Kushwaha79b93922020-07-19 15:45:01 -07006682 if (typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble) {
6683 opCode = spv::OpAtomicFAddEXT;
6684 builder.addExtension(spv::E_SPV_EXT_shader_atomic_float_add);
6685 if (typeProxy == glslang::EbtFloat)
6686 builder.addCapability(spv::CapabilityAtomicFloat32AddEXT);
6687 else
6688 builder.addCapability(spv::CapabilityAtomicFloat64AddEXT);
6689 }
John Kessenich426394d2015-07-23 10:22:48 -06006690 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006691 case glslang::EOpAtomicCounterSubtract:
6692 opCode = spv::OpAtomicISub;
6693 break;
John Kessenich426394d2015-07-23 10:22:48 -06006694 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006695 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006696 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006697 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6698 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006699 break;
6700 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006701 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006702 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006703 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6704 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006705 break;
6706 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006707 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006708 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006709 opCode = spv::OpAtomicAnd;
6710 break;
6711 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006712 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006713 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006714 opCode = spv::OpAtomicOr;
6715 break;
6716 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006717 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006718 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006719 opCode = spv::OpAtomicXor;
6720 break;
6721 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006722 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006723 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006724 opCode = spv::OpAtomicExchange;
6725 break;
6726 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006727 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006728 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006729 opCode = spv::OpAtomicCompareExchange;
6730 break;
6731 case glslang::EOpAtomicCounterIncrement:
6732 opCode = spv::OpAtomicIIncrement;
6733 break;
6734 case glslang::EOpAtomicCounterDecrement:
6735 opCode = spv::OpAtomicIDecrement;
6736 break;
6737 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006738 case glslang::EOpImageAtomicLoad:
6739 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006740 opCode = spv::OpAtomicLoad;
6741 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006742 case glslang::EOpAtomicStore:
6743 case glslang::EOpImageAtomicStore:
6744 opCode = spv::OpAtomicStore;
6745 break;
John Kessenich426394d2015-07-23 10:22:48 -06006746 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006747 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006748 break;
6749 }
6750
Rex Xue8fe8b02017-09-26 15:42:56 +08006751 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6752 builder.addCapability(spv::CapabilityInt64Atomics);
6753
John Kessenich426394d2015-07-23 10:22:48 -06006754 // Sort out the operands
6755 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006756 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006757 // - compare-exchange swaps the value and comparator
6758 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006759 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006760 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6761 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6762 spv::Id scopeId;
6763 if (glslangIntermediate->usingVulkanMemoryModel()) {
6764 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6765 } else {
6766 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6767 }
6768 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006769 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6770 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006771 spv::MemorySemanticsVolatileMask :
6772 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006773 spv::Id semanticsId2 = semanticsId;
6774
6775 pointerId = operands[0];
6776 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6777 // no additional operands
6778 } else if (opCode == spv::OpAtomicCompareExchange) {
6779 compareId = operands[1];
6780 valueId = operands[2];
6781 if (operands.size() > 3) {
6782 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006783 semanticsId = builder.makeUintConstant(
6784 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6785 semanticsId2 = builder.makeUintConstant(
6786 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006787 }
6788 } else if (opCode == spv::OpAtomicLoad) {
6789 if (operands.size() > 1) {
6790 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006791 semanticsId = builder.makeUintConstant(
6792 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006793 }
6794 } else {
6795 // atomic store or RMW
6796 valueId = operands[1];
6797 if (operands.size() > 2) {
6798 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006799 semanticsId = builder.makeUintConstant
6800 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006801 }
Rex Xu04db3f52015-09-16 11:44:02 +08006802 }
John Kessenich426394d2015-07-23 10:22:48 -06006803
Jeff Bolz36831c92018-09-05 10:11:41 -05006804 // Check for capabilities
6805 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006806 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6807 spv::MemorySemanticsMakeVisibleKHRMask |
6808 spv::MemorySemanticsOutputMemoryKHRMask |
6809 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006810 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6811 }
John Kessenich426394d2015-07-23 10:22:48 -06006812
Jeff Bolz36831c92018-09-05 10:11:41 -05006813 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6814 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6815 }
John Kessenich48d6e792017-10-06 21:21:48 -06006816
Jeff Bolz36831c92018-09-05 10:11:41 -05006817 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6818 spvAtomicOperands.push_back(pointerId);
6819 spvAtomicOperands.push_back(scopeId);
6820 spvAtomicOperands.push_back(semanticsId);
6821 if (opCode == spv::OpAtomicCompareExchange) {
6822 spvAtomicOperands.push_back(semanticsId2);
6823 spvAtomicOperands.push_back(valueId);
6824 spvAtomicOperands.push_back(compareId);
6825 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6826 spvAtomicOperands.push_back(valueId);
6827 }
John Kessenich48d6e792017-10-06 21:21:48 -06006828
Jeff Bolz36831c92018-09-05 10:11:41 -05006829 if (opCode == spv::OpAtomicStore) {
6830 builder.createNoResultOp(opCode, spvAtomicOperands);
6831 return 0;
6832 } else {
6833 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6834
6835 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6836 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6837 if (op == glslang::EOpAtomicCounterDecrement)
6838 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6839
6840 return resultId;
6841 }
John Kessenich426394d2015-07-23 10:22:48 -06006842}
6843
John Kessenich91cef522016-05-05 16:45:40 -06006844// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07006845spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
6846 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006847{
John Kessenich66011cb2018-03-06 16:12:04 -07006848 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6849 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006850
Rex Xu51596642016-09-21 18:56:12 +08006851 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006852 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006853 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6854
chaocf200da82016-12-20 12:44:35 -08006855 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6856 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006857 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6858 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006859 } else if (op == glslang::EOpAnyInvocation ||
6860 op == glslang::EOpAllInvocations ||
6861 op == glslang::EOpAllInvocationsEqual) {
6862 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6863 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006864 } else {
6865 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006866 if (op == glslang::EOpMinInvocationsNonUniform ||
6867 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006868 op == glslang::EOpAddInvocationsNonUniform ||
6869 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6870 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6871 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6872 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6873 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6874 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006875 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006876
Rex Xu430ef402016-10-14 17:22:23 +08006877 switch (op) {
6878 case glslang::EOpMinInvocations:
6879 case glslang::EOpMaxInvocations:
6880 case glslang::EOpAddInvocations:
6881 case glslang::EOpMinInvocationsNonUniform:
6882 case glslang::EOpMaxInvocationsNonUniform:
6883 case glslang::EOpAddInvocationsNonUniform:
6884 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006885 break;
6886 case glslang::EOpMinInvocationsInclusiveScan:
6887 case glslang::EOpMaxInvocationsInclusiveScan:
6888 case glslang::EOpAddInvocationsInclusiveScan:
6889 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6890 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6891 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6892 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006893 break;
6894 case glslang::EOpMinInvocationsExclusiveScan:
6895 case glslang::EOpMaxInvocationsExclusiveScan:
6896 case glslang::EOpAddInvocationsExclusiveScan:
6897 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6898 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6899 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6900 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006901 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006902 default:
6903 break;
Rex Xu430ef402016-10-14 17:22:23 +08006904 }
John Kessenich149afc32018-08-14 13:31:43 -06006905 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6906 spvGroupOperands.push_back(scope);
6907 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006908 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006909 spvGroupOperands.push_back(groupOp);
6910 }
Rex Xu51596642016-09-21 18:56:12 +08006911 }
6912
John Kessenich149afc32018-08-14 13:31:43 -06006913 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6914 spv::IdImmediate op = { true, *opIt };
6915 spvGroupOperands.push_back(op);
6916 }
John Kessenich91cef522016-05-05 16:45:40 -06006917
6918 switch (op) {
6919 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006920 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006921 break;
John Kessenich91cef522016-05-05 16:45:40 -06006922 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006923 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006924 break;
John Kessenich91cef522016-05-05 16:45:40 -06006925 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006926 opCode = spv::OpSubgroupAllEqualKHR;
6927 break;
Rex Xu51596642016-09-21 18:56:12 +08006928 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006929 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006930 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006931 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006932 break;
6933 case glslang::EOpReadFirstInvocation:
6934 opCode = spv::OpSubgroupFirstInvocationKHR;
6935 break;
6936 case glslang::EOpBallot:
6937 {
6938 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6939 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6940 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6941 //
6942 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6943 //
6944 spv::Id uintType = builder.makeUintType(32);
6945 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6946 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6947
6948 std::vector<spv::Id> components;
6949 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6950 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6951
6952 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6953 return builder.createUnaryOp(spv::OpBitcast, typeId,
6954 builder.createCompositeConstruct(uvec2Type, components));
6955 }
6956
Rex Xu9d93a232016-05-05 12:30:44 +08006957 case glslang::EOpMinInvocations:
6958 case glslang::EOpMaxInvocations:
6959 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006960 case glslang::EOpMinInvocationsInclusiveScan:
6961 case glslang::EOpMaxInvocationsInclusiveScan:
6962 case glslang::EOpAddInvocationsInclusiveScan:
6963 case glslang::EOpMinInvocationsExclusiveScan:
6964 case glslang::EOpMaxInvocationsExclusiveScan:
6965 case glslang::EOpAddInvocationsExclusiveScan:
6966 if (op == glslang::EOpMinInvocations ||
6967 op == glslang::EOpMinInvocationsInclusiveScan ||
6968 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006969 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006970 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006971 else {
6972 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006973 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006974 else
Rex Xu51596642016-09-21 18:56:12 +08006975 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006976 }
Rex Xu430ef402016-10-14 17:22:23 +08006977 } else if (op == glslang::EOpMaxInvocations ||
6978 op == glslang::EOpMaxInvocationsInclusiveScan ||
6979 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006980 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006981 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006982 else {
6983 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006984 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006985 else
Rex Xu51596642016-09-21 18:56:12 +08006986 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006987 }
6988 } else {
6989 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006990 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006991 else
Rex Xu51596642016-09-21 18:56:12 +08006992 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006993 }
6994
Rex Xu2bbbe062016-08-23 15:41:05 +08006995 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006996 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006997
6998 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006999 case glslang::EOpMinInvocationsNonUniform:
7000 case glslang::EOpMaxInvocationsNonUniform:
7001 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08007002 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
7003 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
7004 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
7005 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
7006 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
7007 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
7008 if (op == glslang::EOpMinInvocationsNonUniform ||
7009 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
7010 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007011 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007012 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007013 else {
7014 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007015 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007016 else
Rex Xu51596642016-09-21 18:56:12 +08007017 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007018 }
7019 }
Rex Xu430ef402016-10-14 17:22:23 +08007020 else if (op == glslang::EOpMaxInvocationsNonUniform ||
7021 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
7022 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007023 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007024 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007025 else {
7026 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007027 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007028 else
Rex Xu51596642016-09-21 18:56:12 +08007029 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007030 }
7031 }
7032 else {
7033 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007034 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007035 else
Rex Xu51596642016-09-21 18:56:12 +08007036 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007037 }
7038
Rex Xu2bbbe062016-08-23 15:41:05 +08007039 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007040 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007041
7042 break;
John Kessenich91cef522016-05-05 16:45:40 -06007043 default:
7044 logger->missingFunctionality("invocation operation");
7045 return spv::NoResult;
7046 }
Rex Xu51596642016-09-21 18:56:12 +08007047
7048 assert(opCode != spv::OpNop);
7049 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06007050}
7051
Rex Xu2bbbe062016-08-23 15:41:05 +08007052// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06007053spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
7054 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08007055{
7056 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
7057 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08007058 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08007059 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07007060 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
7061 op == spv::OpGroupSMinNonUniformAMD ||
7062 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
7063 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08007064 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
7065
7066 // Handle group invocation operations scalar by scalar.
7067 // The result type is the same type as the original type.
7068 // The algorithm is to:
7069 // - break the vector into scalars
7070 // - apply the operation to each scalar
7071 // - make a vector out the scalar results
7072
7073 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08007074 int numComponents = builder.getNumComponents(operands[0]);
7075 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08007076 std::vector<spv::Id> results;
7077
7078 // do each scalar op
7079 for (int comp = 0; comp < numComponents; ++comp) {
7080 std::vector<unsigned int> indexes;
7081 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06007082 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
7083 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08007084 if (op == spv::OpSubgroupReadInvocationKHR) {
7085 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007086 spv::IdImmediate operand = { true, operands[1] };
7087 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08007088 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06007089 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7090 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08007091 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007092 spv::IdImmediate operand = { true, operands[1] };
7093 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08007094 } else {
John Kessenich149afc32018-08-14 13:31:43 -06007095 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7096 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06007097 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007098 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08007099 spvGroupOperands.push_back(scalar);
7100 }
Rex Xu2bbbe062016-08-23 15:41:05 +08007101
Rex Xub7072052016-09-26 15:53:40 +08007102 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08007103 }
7104
7105 // put the pieces together
7106 return builder.createCompositeConstruct(typeId, results);
7107}
Rex Xu2bbbe062016-08-23 15:41:05 +08007108
John Kessenich66011cb2018-03-06 16:12:04 -07007109// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06007110spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
7111 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07007112{
7113 // Add the required capabilities.
7114 switch (op) {
7115 case glslang::EOpSubgroupElect:
7116 builder.addCapability(spv::CapabilityGroupNonUniform);
7117 break;
7118 case glslang::EOpSubgroupAll:
7119 case glslang::EOpSubgroupAny:
7120 case glslang::EOpSubgroupAllEqual:
7121 builder.addCapability(spv::CapabilityGroupNonUniform);
7122 builder.addCapability(spv::CapabilityGroupNonUniformVote);
7123 break;
7124 case glslang::EOpSubgroupBroadcast:
7125 case glslang::EOpSubgroupBroadcastFirst:
7126 case glslang::EOpSubgroupBallot:
7127 case glslang::EOpSubgroupInverseBallot:
7128 case glslang::EOpSubgroupBallotBitExtract:
7129 case glslang::EOpSubgroupBallotBitCount:
7130 case glslang::EOpSubgroupBallotInclusiveBitCount:
7131 case glslang::EOpSubgroupBallotExclusiveBitCount:
7132 case glslang::EOpSubgroupBallotFindLSB:
7133 case glslang::EOpSubgroupBallotFindMSB:
7134 builder.addCapability(spv::CapabilityGroupNonUniform);
7135 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
7136 break;
7137 case glslang::EOpSubgroupShuffle:
7138 case glslang::EOpSubgroupShuffleXor:
7139 builder.addCapability(spv::CapabilityGroupNonUniform);
7140 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
7141 break;
7142 case glslang::EOpSubgroupShuffleUp:
7143 case glslang::EOpSubgroupShuffleDown:
7144 builder.addCapability(spv::CapabilityGroupNonUniform);
7145 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
7146 break;
7147 case glslang::EOpSubgroupAdd:
7148 case glslang::EOpSubgroupMul:
7149 case glslang::EOpSubgroupMin:
7150 case glslang::EOpSubgroupMax:
7151 case glslang::EOpSubgroupAnd:
7152 case glslang::EOpSubgroupOr:
7153 case glslang::EOpSubgroupXor:
7154 case glslang::EOpSubgroupInclusiveAdd:
7155 case glslang::EOpSubgroupInclusiveMul:
7156 case glslang::EOpSubgroupInclusiveMin:
7157 case glslang::EOpSubgroupInclusiveMax:
7158 case glslang::EOpSubgroupInclusiveAnd:
7159 case glslang::EOpSubgroupInclusiveOr:
7160 case glslang::EOpSubgroupInclusiveXor:
7161 case glslang::EOpSubgroupExclusiveAdd:
7162 case glslang::EOpSubgroupExclusiveMul:
7163 case glslang::EOpSubgroupExclusiveMin:
7164 case glslang::EOpSubgroupExclusiveMax:
7165 case glslang::EOpSubgroupExclusiveAnd:
7166 case glslang::EOpSubgroupExclusiveOr:
7167 case glslang::EOpSubgroupExclusiveXor:
7168 builder.addCapability(spv::CapabilityGroupNonUniform);
7169 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
7170 break;
7171 case glslang::EOpSubgroupClusteredAdd:
7172 case glslang::EOpSubgroupClusteredMul:
7173 case glslang::EOpSubgroupClusteredMin:
7174 case glslang::EOpSubgroupClusteredMax:
7175 case glslang::EOpSubgroupClusteredAnd:
7176 case glslang::EOpSubgroupClusteredOr:
7177 case glslang::EOpSubgroupClusteredXor:
7178 builder.addCapability(spv::CapabilityGroupNonUniform);
7179 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7180 break;
7181 case glslang::EOpSubgroupQuadBroadcast:
7182 case glslang::EOpSubgroupQuadSwapHorizontal:
7183 case glslang::EOpSubgroupQuadSwapVertical:
7184 case glslang::EOpSubgroupQuadSwapDiagonal:
7185 builder.addCapability(spv::CapabilityGroupNonUniform);
7186 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7187 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007188 case glslang::EOpSubgroupPartitionedAdd:
7189 case glslang::EOpSubgroupPartitionedMul:
7190 case glslang::EOpSubgroupPartitionedMin:
7191 case glslang::EOpSubgroupPartitionedMax:
7192 case glslang::EOpSubgroupPartitionedAnd:
7193 case glslang::EOpSubgroupPartitionedOr:
7194 case glslang::EOpSubgroupPartitionedXor:
7195 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7196 case glslang::EOpSubgroupPartitionedInclusiveMul:
7197 case glslang::EOpSubgroupPartitionedInclusiveMin:
7198 case glslang::EOpSubgroupPartitionedInclusiveMax:
7199 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7200 case glslang::EOpSubgroupPartitionedInclusiveOr:
7201 case glslang::EOpSubgroupPartitionedInclusiveXor:
7202 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7203 case glslang::EOpSubgroupPartitionedExclusiveMul:
7204 case glslang::EOpSubgroupPartitionedExclusiveMin:
7205 case glslang::EOpSubgroupPartitionedExclusiveMax:
7206 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7207 case glslang::EOpSubgroupPartitionedExclusiveOr:
7208 case glslang::EOpSubgroupPartitionedExclusiveXor:
7209 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7210 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7211 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007212 default: assert(0 && "Unhandled subgroup operation!");
7213 }
7214
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007215
7216 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7217 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007218 const bool isBool = typeProxy == glslang::EbtBool;
7219
7220 spv::Op opCode = spv::OpNop;
7221
7222 // Figure out which opcode to use.
7223 switch (op) {
7224 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7225 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7226 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7227 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7228 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7229 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7230 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7231 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7232 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7233 case glslang::EOpSubgroupBallotBitCount:
7234 case glslang::EOpSubgroupBallotInclusiveBitCount:
7235 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7236 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7237 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7238 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7239 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7240 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7241 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7242 case glslang::EOpSubgroupAdd:
7243 case glslang::EOpSubgroupInclusiveAdd:
7244 case glslang::EOpSubgroupExclusiveAdd:
7245 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007246 case glslang::EOpSubgroupPartitionedAdd:
7247 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7248 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007249 if (isFloat) {
7250 opCode = spv::OpGroupNonUniformFAdd;
7251 } else {
7252 opCode = spv::OpGroupNonUniformIAdd;
7253 }
7254 break;
7255 case glslang::EOpSubgroupMul:
7256 case glslang::EOpSubgroupInclusiveMul:
7257 case glslang::EOpSubgroupExclusiveMul:
7258 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007259 case glslang::EOpSubgroupPartitionedMul:
7260 case glslang::EOpSubgroupPartitionedInclusiveMul:
7261 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007262 if (isFloat) {
7263 opCode = spv::OpGroupNonUniformFMul;
7264 } else {
7265 opCode = spv::OpGroupNonUniformIMul;
7266 }
7267 break;
7268 case glslang::EOpSubgroupMin:
7269 case glslang::EOpSubgroupInclusiveMin:
7270 case glslang::EOpSubgroupExclusiveMin:
7271 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007272 case glslang::EOpSubgroupPartitionedMin:
7273 case glslang::EOpSubgroupPartitionedInclusiveMin:
7274 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007275 if (isFloat) {
7276 opCode = spv::OpGroupNonUniformFMin;
7277 } else if (isUnsigned) {
7278 opCode = spv::OpGroupNonUniformUMin;
7279 } else {
7280 opCode = spv::OpGroupNonUniformSMin;
7281 }
7282 break;
7283 case glslang::EOpSubgroupMax:
7284 case glslang::EOpSubgroupInclusiveMax:
7285 case glslang::EOpSubgroupExclusiveMax:
7286 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007287 case glslang::EOpSubgroupPartitionedMax:
7288 case glslang::EOpSubgroupPartitionedInclusiveMax:
7289 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007290 if (isFloat) {
7291 opCode = spv::OpGroupNonUniformFMax;
7292 } else if (isUnsigned) {
7293 opCode = spv::OpGroupNonUniformUMax;
7294 } else {
7295 opCode = spv::OpGroupNonUniformSMax;
7296 }
7297 break;
7298 case glslang::EOpSubgroupAnd:
7299 case glslang::EOpSubgroupInclusiveAnd:
7300 case glslang::EOpSubgroupExclusiveAnd:
7301 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007302 case glslang::EOpSubgroupPartitionedAnd:
7303 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7304 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007305 if (isBool) {
7306 opCode = spv::OpGroupNonUniformLogicalAnd;
7307 } else {
7308 opCode = spv::OpGroupNonUniformBitwiseAnd;
7309 }
7310 break;
7311 case glslang::EOpSubgroupOr:
7312 case glslang::EOpSubgroupInclusiveOr:
7313 case glslang::EOpSubgroupExclusiveOr:
7314 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007315 case glslang::EOpSubgroupPartitionedOr:
7316 case glslang::EOpSubgroupPartitionedInclusiveOr:
7317 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007318 if (isBool) {
7319 opCode = spv::OpGroupNonUniformLogicalOr;
7320 } else {
7321 opCode = spv::OpGroupNonUniformBitwiseOr;
7322 }
7323 break;
7324 case glslang::EOpSubgroupXor:
7325 case glslang::EOpSubgroupInclusiveXor:
7326 case glslang::EOpSubgroupExclusiveXor:
7327 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007328 case glslang::EOpSubgroupPartitionedXor:
7329 case glslang::EOpSubgroupPartitionedInclusiveXor:
7330 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007331 if (isBool) {
7332 opCode = spv::OpGroupNonUniformLogicalXor;
7333 } else {
7334 opCode = spv::OpGroupNonUniformBitwiseXor;
7335 }
7336 break;
7337 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7338 case glslang::EOpSubgroupQuadSwapHorizontal:
7339 case glslang::EOpSubgroupQuadSwapVertical:
7340 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7341 default: assert(0 && "Unhandled subgroup operation!");
7342 }
7343
John Kessenich149afc32018-08-14 13:31:43 -06007344 // get the right Group Operation
7345 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007346 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007347 default:
7348 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007349 case glslang::EOpSubgroupBallotBitCount:
7350 case glslang::EOpSubgroupAdd:
7351 case glslang::EOpSubgroupMul:
7352 case glslang::EOpSubgroupMin:
7353 case glslang::EOpSubgroupMax:
7354 case glslang::EOpSubgroupAnd:
7355 case glslang::EOpSubgroupOr:
7356 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007357 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007358 break;
7359 case glslang::EOpSubgroupBallotInclusiveBitCount:
7360 case glslang::EOpSubgroupInclusiveAdd:
7361 case glslang::EOpSubgroupInclusiveMul:
7362 case glslang::EOpSubgroupInclusiveMin:
7363 case glslang::EOpSubgroupInclusiveMax:
7364 case glslang::EOpSubgroupInclusiveAnd:
7365 case glslang::EOpSubgroupInclusiveOr:
7366 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007367 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007368 break;
7369 case glslang::EOpSubgroupBallotExclusiveBitCount:
7370 case glslang::EOpSubgroupExclusiveAdd:
7371 case glslang::EOpSubgroupExclusiveMul:
7372 case glslang::EOpSubgroupExclusiveMin:
7373 case glslang::EOpSubgroupExclusiveMax:
7374 case glslang::EOpSubgroupExclusiveAnd:
7375 case glslang::EOpSubgroupExclusiveOr:
7376 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007377 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007378 break;
7379 case glslang::EOpSubgroupClusteredAdd:
7380 case glslang::EOpSubgroupClusteredMul:
7381 case glslang::EOpSubgroupClusteredMin:
7382 case glslang::EOpSubgroupClusteredMax:
7383 case glslang::EOpSubgroupClusteredAnd:
7384 case glslang::EOpSubgroupClusteredOr:
7385 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007386 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007387 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007388 case glslang::EOpSubgroupPartitionedAdd:
7389 case glslang::EOpSubgroupPartitionedMul:
7390 case glslang::EOpSubgroupPartitionedMin:
7391 case glslang::EOpSubgroupPartitionedMax:
7392 case glslang::EOpSubgroupPartitionedAnd:
7393 case glslang::EOpSubgroupPartitionedOr:
7394 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007395 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007396 break;
7397 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7398 case glslang::EOpSubgroupPartitionedInclusiveMul:
7399 case glslang::EOpSubgroupPartitionedInclusiveMin:
7400 case glslang::EOpSubgroupPartitionedInclusiveMax:
7401 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7402 case glslang::EOpSubgroupPartitionedInclusiveOr:
7403 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007404 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007405 break;
7406 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7407 case glslang::EOpSubgroupPartitionedExclusiveMul:
7408 case glslang::EOpSubgroupPartitionedExclusiveMin:
7409 case glslang::EOpSubgroupPartitionedExclusiveMax:
7410 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7411 case glslang::EOpSubgroupPartitionedExclusiveOr:
7412 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007413 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007414 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007415 }
7416
John Kessenich149afc32018-08-14 13:31:43 -06007417 // build the instruction
7418 std::vector<spv::IdImmediate> spvGroupOperands;
7419
7420 // Every operation begins with the Execution Scope operand.
7421 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7422 spvGroupOperands.push_back(executionScope);
7423
7424 // Next, for all operations that use a Group Operation, push that as an operand.
7425 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007426 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007427 spvGroupOperands.push_back(groupOperand);
7428 }
7429
John Kessenich66011cb2018-03-06 16:12:04 -07007430 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007431 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7432 spv::IdImmediate operand = { true, *opIt };
7433 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007434 }
7435
7436 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007437 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007438 switch (op) {
7439 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007440 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7441 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7442 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7443 }
7444 if (directionId != spv::NoResult) {
7445 spv::IdImmediate direction = { true, directionId };
7446 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007447 }
7448
7449 return builder.createOp(opCode, typeId, spvGroupOperands);
7450}
7451
John Kessenich8985fc92020-03-03 10:25:07 -07007452spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7453 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007454{
John Kessenich66011cb2018-03-06 16:12:04 -07007455 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7456 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007457
John Kessenich140f3df2015-06-26 16:58:36 -06007458 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007459 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007460 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007461 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007462 spv::Id typeId0 = 0;
7463 if (consumedOperands > 0)
7464 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007465 spv::Id typeId1 = 0;
7466 if (consumedOperands > 1)
7467 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007468 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007469
7470 switch (op) {
7471 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007472 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007473 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007474 else if (isUnsigned)
7475 libCall = spv::GLSLstd450UMin;
7476 else
7477 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007478 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007479 break;
7480 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007481 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007482 break;
7483 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007484 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007485 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007486 else if (isUnsigned)
7487 libCall = spv::GLSLstd450UMax;
7488 else
7489 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007490 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007491 break;
7492 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007493 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007494 break;
7495 case glslang::EOpDot:
7496 opCode = spv::OpDot;
7497 break;
7498 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007499 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007500 break;
7501
7502 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007503 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007504 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007505 else if (isUnsigned)
7506 libCall = spv::GLSLstd450UClamp;
7507 else
7508 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007509 builder.promoteScalar(precision, operands.front(), operands[1]);
7510 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007511 break;
7512 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007513 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7514 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007515 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007516 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007517 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007518 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007519 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007520 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007521 break;
7522 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007523 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007524 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007525 break;
7526 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007527 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007528 builder.promoteScalar(precision, operands[0], operands[2]);
7529 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007530 break;
7531
7532 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007533 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007534 break;
7535 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007536 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007537 break;
7538 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007539 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007540 break;
7541 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007542 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007543 break;
7544 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007545 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007546 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007547 case glslang::EOpBarrier:
7548 {
7549 // This is for the extended controlBarrier function, with four operands.
7550 // The unextended barrier() goes through createNoArgOperation.
7551 assert(operands.size() == 4);
7552 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7553 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7554 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007555 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7556 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007557 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7558 spv::MemorySemanticsMakeVisibleKHRMask |
7559 spv::MemorySemanticsOutputMemoryKHRMask |
7560 spv::MemorySemanticsVolatileMask)) {
7561 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7562 }
John Kessenich8985fc92020-03-03 10:25:07 -07007563 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7564 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007565 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7566 }
7567 return 0;
7568 }
7569 break;
7570 case glslang::EOpMemoryBarrier:
7571 {
7572 // This is for the extended memoryBarrier function, with three operands.
7573 // The unextended memoryBarrier() goes through createNoArgOperation.
7574 assert(operands.size() == 3);
7575 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7576 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7577 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7578 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7579 spv::MemorySemanticsMakeVisibleKHRMask |
7580 spv::MemorySemanticsOutputMemoryKHRMask |
7581 spv::MemorySemanticsVolatileMask)) {
7582 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7583 }
7584 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7585 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7586 }
7587 return 0;
7588 }
7589 break;
7590
John Kessenicha28f7a72019-08-06 07:00:58 -06007591#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007592 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007593 if (typeProxy == glslang::EbtFloat16)
7594 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007595 libCall = spv::GLSLstd450InterpolateAtSample;
7596 break;
7597 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007598 if (typeProxy == glslang::EbtFloat16)
7599 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007600 libCall = spv::GLSLstd450InterpolateAtOffset;
7601 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007602 case glslang::EOpAddCarry:
7603 opCode = spv::OpIAddCarry;
7604 typeId = builder.makeStructResultType(typeId0, typeId0);
7605 consumedOperands = 2;
7606 break;
7607 case glslang::EOpSubBorrow:
7608 opCode = spv::OpISubBorrow;
7609 typeId = builder.makeStructResultType(typeId0, typeId0);
7610 consumedOperands = 2;
7611 break;
7612 case glslang::EOpUMulExtended:
7613 opCode = spv::OpUMulExtended;
7614 typeId = builder.makeStructResultType(typeId0, typeId0);
7615 consumedOperands = 2;
7616 break;
7617 case glslang::EOpIMulExtended:
7618 opCode = spv::OpSMulExtended;
7619 typeId = builder.makeStructResultType(typeId0, typeId0);
7620 consumedOperands = 2;
7621 break;
7622 case glslang::EOpBitfieldExtract:
7623 if (isUnsigned)
7624 opCode = spv::OpBitFieldUExtract;
7625 else
7626 opCode = spv::OpBitFieldSExtract;
7627 break;
7628 case glslang::EOpBitfieldInsert:
7629 opCode = spv::OpBitFieldInsert;
7630 break;
7631
7632 case glslang::EOpFma:
7633 libCall = spv::GLSLstd450Fma;
7634 break;
7635 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007636 {
7637 libCall = spv::GLSLstd450FrexpStruct;
7638 assert(builder.isPointerType(typeId1));
7639 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007640 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007641 if (width == 16)
7642 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7643 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007644 if (builder.getNumComponents(operands[0]) == 1)
7645 frexpIntType = builder.makeIntegerType(width, true);
7646 else
John Kessenich8985fc92020-03-03 10:25:07 -07007647 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7648 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007649 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7650 consumedOperands = 1;
7651 }
John Kessenich55e7d112015-11-15 21:33:39 -07007652 break;
7653 case glslang::EOpLdexp:
7654 libCall = spv::GLSLstd450Ldexp;
7655 break;
7656
Rex Xu574ab042016-04-14 16:53:07 +08007657 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007658 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007659
John Kessenich66011cb2018-03-06 16:12:04 -07007660 case glslang::EOpSubgroupBroadcast:
7661 case glslang::EOpSubgroupBallotBitExtract:
7662 case glslang::EOpSubgroupShuffle:
7663 case glslang::EOpSubgroupShuffleXor:
7664 case glslang::EOpSubgroupShuffleUp:
7665 case glslang::EOpSubgroupShuffleDown:
7666 case glslang::EOpSubgroupClusteredAdd:
7667 case glslang::EOpSubgroupClusteredMul:
7668 case glslang::EOpSubgroupClusteredMin:
7669 case glslang::EOpSubgroupClusteredMax:
7670 case glslang::EOpSubgroupClusteredAnd:
7671 case glslang::EOpSubgroupClusteredOr:
7672 case glslang::EOpSubgroupClusteredXor:
7673 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007674 case glslang::EOpSubgroupPartitionedAdd:
7675 case glslang::EOpSubgroupPartitionedMul:
7676 case glslang::EOpSubgroupPartitionedMin:
7677 case glslang::EOpSubgroupPartitionedMax:
7678 case glslang::EOpSubgroupPartitionedAnd:
7679 case glslang::EOpSubgroupPartitionedOr:
7680 case glslang::EOpSubgroupPartitionedXor:
7681 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7682 case glslang::EOpSubgroupPartitionedInclusiveMul:
7683 case glslang::EOpSubgroupPartitionedInclusiveMin:
7684 case glslang::EOpSubgroupPartitionedInclusiveMax:
7685 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7686 case glslang::EOpSubgroupPartitionedInclusiveOr:
7687 case glslang::EOpSubgroupPartitionedInclusiveXor:
7688 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7689 case glslang::EOpSubgroupPartitionedExclusiveMul:
7690 case glslang::EOpSubgroupPartitionedExclusiveMin:
7691 case glslang::EOpSubgroupPartitionedExclusiveMax:
7692 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7693 case glslang::EOpSubgroupPartitionedExclusiveOr:
7694 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007695 return createSubgroupOperation(op, typeId, operands, typeProxy);
7696
Rex Xu9d93a232016-05-05 12:30:44 +08007697 case glslang::EOpSwizzleInvocations:
7698 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7699 libCall = spv::SwizzleInvocationsAMD;
7700 break;
7701 case glslang::EOpSwizzleInvocationsMasked:
7702 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7703 libCall = spv::SwizzleInvocationsMaskedAMD;
7704 break;
7705 case glslang::EOpWriteInvocation:
7706 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7707 libCall = spv::WriteInvocationAMD;
7708 break;
7709
7710 case glslang::EOpMin3:
7711 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7712 if (isFloat)
7713 libCall = spv::FMin3AMD;
7714 else {
7715 if (isUnsigned)
7716 libCall = spv::UMin3AMD;
7717 else
7718 libCall = spv::SMin3AMD;
7719 }
7720 break;
7721 case glslang::EOpMax3:
7722 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7723 if (isFloat)
7724 libCall = spv::FMax3AMD;
7725 else {
7726 if (isUnsigned)
7727 libCall = spv::UMax3AMD;
7728 else
7729 libCall = spv::SMax3AMD;
7730 }
7731 break;
7732 case glslang::EOpMid3:
7733 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7734 if (isFloat)
7735 libCall = spv::FMid3AMD;
7736 else {
7737 if (isUnsigned)
7738 libCall = spv::UMid3AMD;
7739 else
7740 libCall = spv::SMid3AMD;
7741 }
7742 break;
7743
7744 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007745 if (typeProxy == glslang::EbtFloat16)
7746 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007747 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7748 libCall = spv::InterpolateAtVertexAMD;
7749 break;
Chao Chen3c366992018-09-19 11:41:59 -07007750
Daniel Kochdb32b242020-03-17 20:42:47 -04007751 case glslang::EOpReportIntersection:
Chao Chenb50c02e2018-09-19 11:42:24 -07007752 typeId = builder.makeBoolType();
Daniel Kochdb32b242020-03-17 20:42:47 -04007753 opCode = spv::OpReportIntersectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007754 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04007755 case glslang::EOpTrace:
Daniel Kochdb32b242020-03-17 20:42:47 -04007756 builder.createNoResultOp(spv::OpTraceRayKHR, operands);
Ashwin Leleff1783d2018-10-22 16:41:44 -07007757 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04007758 case glslang::EOpExecuteCallable:
Daniel Kochdb32b242020-03-17 20:42:47 -04007759 builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007760 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007761
7762 case glslang::EOpRayQueryInitialize:
Torosdagli06c2eee2020-03-19 11:09:57 -04007763 builder.createNoResultOp(spv::OpRayQueryInitializeKHR, operands);
7764 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007765 case glslang::EOpRayQueryTerminate:
Torosdagli06c2eee2020-03-19 11:09:57 -04007766 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operands);
7767 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007768 case glslang::EOpRayQueryGenerateIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007769 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR, operands);
7770 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007771 case glslang::EOpRayQueryConfirmIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007772 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operands);
7773 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007774 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04007775 typeId = builder.makeBoolType();
7776 opCode = spv::OpRayQueryProceedKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007777 break;
7778 case glslang::EOpRayQueryGetIntersectionType:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007779 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007780 opCode = spv::OpRayQueryGetIntersectionTypeKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007781 break;
7782 case glslang::EOpRayQueryGetRayTMin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007783 typeId = builder.makeFloatType(32);
7784 opCode = spv::OpRayQueryGetRayTMinKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007785 break;
7786 case glslang::EOpRayQueryGetRayFlags:
Torosdagli06c2eee2020-03-19 11:09:57 -04007787 typeId = builder.makeIntType(32);
7788 opCode = spv::OpRayQueryGetRayFlagsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007789 break;
7790 case glslang::EOpRayQueryGetIntersectionT:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007791 typeId = builder.makeFloatType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007792 opCode = spv::OpRayQueryGetIntersectionTKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007793 break;
7794 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007795 typeId = builder.makeIntType(32);
7796 opCode = spv::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007797 break;
7798 case glslang::EOpRayQueryGetIntersectionInstanceId:
Torosdagli06c2eee2020-03-19 11:09:57 -04007799 typeId = builder.makeIntType(32);
7800 opCode = spv::OpRayQueryGetIntersectionInstanceIdKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007801 break;
7802 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
Torosdagli06c2eee2020-03-19 11:09:57 -04007803 typeId = builder.makeIntType(32);
7804 opCode = spv::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007805 break;
7806 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007807 typeId = builder.makeIntType(32);
7808 opCode = spv::OpRayQueryGetIntersectionGeometryIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007809 break;
7810 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007811 typeId = builder.makeIntType(32);
7812 opCode = spv::OpRayQueryGetIntersectionPrimitiveIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007813 break;
7814 case glslang::EOpRayQueryGetIntersectionBarycentrics:
Torosdagli06c2eee2020-03-19 11:09:57 -04007815 typeId = builder.makeVectorType(builder.makeFloatType(32), 2);
7816 opCode = spv::OpRayQueryGetIntersectionBarycentricsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007817 break;
7818 case glslang::EOpRayQueryGetIntersectionFrontFace:
Torosdagli06c2eee2020-03-19 11:09:57 -04007819 typeId = builder.makeBoolType();
7820 opCode = spv::OpRayQueryGetIntersectionFrontFaceKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007821 break;
7822 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
Torosdagli06c2eee2020-03-19 11:09:57 -04007823 typeId = builder.makeBoolType();
7824 opCode = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007825 break;
7826 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007827 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7828 opCode = spv::OpRayQueryGetIntersectionObjectRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007829 break;
7830 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007831 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7832 opCode = spv::OpRayQueryGetIntersectionObjectRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007833 break;
7834 case glslang::EOpRayQueryGetWorldRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007835 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7836 opCode = spv::OpRayQueryGetWorldRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007837 break;
7838 case glslang::EOpRayQueryGetWorldRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007839 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7840 opCode = spv::OpRayQueryGetWorldRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007841 break;
7842 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
Torosdagli06c2eee2020-03-19 11:09:57 -04007843 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007844 opCode = spv::OpRayQueryGetIntersectionObjectToWorldKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007845 break;
7846 case glslang::EOpRayQueryGetIntersectionWorldToObject:
Torosdagli06c2eee2020-03-19 11:09:57 -04007847 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007848 opCode = spv::OpRayQueryGetIntersectionWorldToObjectKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007849 break;
Chao Chen3c366992018-09-19 11:41:59 -07007850 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7851 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7852 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007853 case glslang::EOpCooperativeMatrixMulAdd:
7854 opCode = spv::OpCooperativeMatrixMulAddNV;
7855 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007856#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007857 default:
7858 return 0;
7859 }
7860
7861 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007862 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007863 // Use an extended instruction from the standard library.
7864 // Construct the call arguments, without modifying the original operands vector.
7865 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7866 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007867 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007868 } else if (opCode == spv::OpDot && !isFloat) {
7869 // int dot(int, int)
7870 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7871 const int componentCount = builder.getNumComponents(operands[0]);
7872 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7873 builder.setPrecision(mulOp, precision);
7874 id = builder.createCompositeExtract(mulOp, typeId, 0);
7875 for (int i = 1; i < componentCount; ++i) {
7876 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07007877 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01007878 }
John Kessenich2359bd02015-12-06 19:29:11 -07007879 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007880 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007881 case 0:
7882 // should all be handled by visitAggregate and createNoArgOperation
7883 assert(0);
7884 return 0;
7885 case 1:
7886 // should all be handled by createUnaryOperation
7887 assert(0);
7888 return 0;
7889 case 2:
7890 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7891 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007892 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007893 // anything 3 or over doesn't have l-value operands, so all should be consumed
7894 assert(consumedOperands == operands.size());
7895 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007896 break;
7897 }
7898 }
7899
John Kessenichb9197c82019-08-11 07:41:45 -06007900#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007901 // Decode the return types that were structures
7902 switch (op) {
7903 case glslang::EOpAddCarry:
7904 case glslang::EOpSubBorrow:
7905 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7906 id = builder.createCompositeExtract(id, typeId0, 0);
7907 break;
7908 case glslang::EOpUMulExtended:
7909 case glslang::EOpIMulExtended:
7910 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7911 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7912 break;
7913 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007914 {
7915 assert(operands.size() == 2);
7916 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7917 // "exp" is floating-point type (from HLSL intrinsic)
7918 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7919 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7920 builder.createStore(member1, operands[1]);
7921 } else
7922 // "exp" is integer type (from GLSL built-in function)
7923 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7924 id = builder.createCompositeExtract(id, typeId0, 0);
7925 }
John Kessenich55e7d112015-11-15 21:33:39 -07007926 break;
7927 default:
7928 break;
7929 }
John Kessenichb9197c82019-08-11 07:41:45 -06007930#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007931
John Kessenich32cfd492016-02-02 12:37:46 -07007932 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007933}
7934
Rex Xu9d93a232016-05-05 12:30:44 +08007935// Intrinsics with no arguments (or no return value, and no precision).
7936spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007937{
Jeff Bolz36831c92018-09-05 10:11:41 -05007938 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07007939 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
7940 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007941
7942 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007943 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007944 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007945 if (glslangIntermediate->usingVulkanMemoryModel()) {
7946 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7947 spv::MemorySemanticsOutputMemoryKHRMask |
7948 spv::MemorySemanticsAcquireReleaseMask);
7949 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7950 } else {
7951 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7952 }
John Kessenich82979362017-12-11 04:02:24 -07007953 } else {
7954 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7955 spv::MemorySemanticsWorkgroupMemoryMask |
7956 spv::MemorySemanticsAcquireReleaseMask);
7957 }
John Kessenich140f3df2015-06-26 16:58:36 -06007958 return 0;
7959 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007960 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7961 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007962 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007963 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007964 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7965 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007966 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007967 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007968 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7969 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007970 return 0;
7971 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007972 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7973 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007974 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007975#ifndef GLSLANG_WEB
7976 case glslang::EOpMemoryBarrierAtomicCounter:
7977 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7978 spv::MemorySemanticsAcquireReleaseMask);
7979 return 0;
7980 case glslang::EOpMemoryBarrierImage:
7981 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7982 spv::MemorySemanticsAcquireReleaseMask);
7983 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007984 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007985 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007986 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007987 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007988 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007989 case glslang::EOpDeviceMemoryBarrier:
7990 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7991 spv::MemorySemanticsImageMemoryMask |
7992 spv::MemorySemanticsAcquireReleaseMask);
7993 return 0;
7994 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7995 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7996 spv::MemorySemanticsImageMemoryMask |
7997 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007998 return 0;
7999 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07008000 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8001 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008002 return 0;
8003 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07008004 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8005 spv::MemorySemanticsWorkgroupMemoryMask |
8006 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008007 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07008008 case glslang::EOpSubgroupBarrier:
8009 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8010 spv::MemorySemanticsAcquireReleaseMask);
8011 return spv::NoResult;
8012 case glslang::EOpSubgroupMemoryBarrier:
8013 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8014 spv::MemorySemanticsAcquireReleaseMask);
8015 return spv::NoResult;
8016 case glslang::EOpSubgroupMemoryBarrierBuffer:
8017 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
8018 spv::MemorySemanticsAcquireReleaseMask);
8019 return spv::NoResult;
8020 case glslang::EOpSubgroupMemoryBarrierImage:
8021 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
8022 spv::MemorySemanticsAcquireReleaseMask);
8023 return spv::NoResult;
8024 case glslang::EOpSubgroupMemoryBarrierShared:
8025 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8026 spv::MemorySemanticsAcquireReleaseMask);
8027 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06008028
8029 case glslang::EOpEmitVertex:
8030 builder.createNoResultOp(spv::OpEmitVertex);
8031 return 0;
8032 case glslang::EOpEndPrimitive:
8033 builder.createNoResultOp(spv::OpEndPrimitive);
8034 return 0;
8035
John Kessenich66011cb2018-03-06 16:12:04 -07008036 case glslang::EOpSubgroupElect: {
8037 std::vector<spv::Id> operands;
8038 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
8039 }
Rex Xu9d93a232016-05-05 12:30:44 +08008040 case glslang::EOpTime:
8041 {
8042 std::vector<spv::Id> args; // Dummy arguments
8043 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
8044 return builder.setPrecision(id, precision);
8045 }
Daniel Kochdb32b242020-03-17 20:42:47 -04008046 case glslang::EOpIgnoreIntersection:
8047 builder.createNoResultOp(spv::OpIgnoreIntersectionKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008048 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04008049 case glslang::EOpTerminateRay:
8050 builder.createNoResultOp(spv::OpTerminateRayKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008051 return 0;
Torosdagli06c2eee2020-03-19 11:09:57 -04008052 case glslang::EOpRayQueryInitialize:
8053 builder.createNoResultOp(spv::OpRayQueryInitializeKHR);
8054 return 0;
8055 case glslang::EOpRayQueryTerminate:
8056 builder.createNoResultOp(spv::OpRayQueryTerminateKHR);
8057 return 0;
8058 case glslang::EOpRayQueryGenerateIntersection:
8059 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR);
8060 return 0;
8061 case glslang::EOpRayQueryConfirmIntersection:
8062 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR);
8063 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05008064 case glslang::EOpBeginInvocationInterlock:
8065 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
8066 return 0;
8067 case glslang::EOpEndInvocationInterlock:
8068 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
8069 return 0;
8070
Jeff Bolzba6170b2019-07-01 09:23:23 -05008071 case glslang::EOpIsHelperInvocation:
8072 {
8073 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08008074 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
8075 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
8076 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05008077 }
8078
amhagan91fb0092019-07-10 21:14:38 -04008079 case glslang::EOpReadClockSubgroupKHR: {
8080 std::vector<spv::Id> args;
8081 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
8082 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8083 builder.addCapability(spv::CapabilityShaderClockKHR);
8084 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8085 }
8086
8087 case glslang::EOpReadClockDeviceKHR: {
8088 std::vector<spv::Id> args;
8089 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
8090 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8091 builder.addCapability(spv::CapabilityShaderClockKHR);
8092 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8093 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06008094#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008095 default:
John Kessenich155d3512019-08-08 23:29:20 -06008096 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008097 }
John Kessenich155d3512019-08-08 23:29:20 -06008098
8099 logger->missingFunctionality("unknown operation with no arguments");
8100
8101 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008102}
8103
8104spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
8105{
John Kessenich2f273362015-07-18 22:34:27 -06008106 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06008107 spv::Id id;
8108 if (symbolValues.end() != iter) {
8109 id = iter->second;
8110 return id;
8111 }
8112
8113 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06008114 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
Daniel Kochdb32b242020-03-17 20:42:47 -04008115 auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06008116 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06008117 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06008118 if (forcedType.second != spv::NoType)
8119 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06008120
Rex Xuc884b4a2016-06-29 15:03:44 +08008121 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008122 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
8123 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
8124 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06008125#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008126 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06008127 if (symbol->getQualifier().hasComponent())
8128 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
8129 if (symbol->getQualifier().hasIndex())
8130 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07008131#endif
John Kessenich6c292d32016-02-15 20:58:50 -07008132 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07008133 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06008134 // atomic counters use this:
8135 if (symbol->getQualifier().hasOffset())
8136 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008137 }
8138
scygan2c864272016-05-18 18:09:17 +02008139 if (symbol->getQualifier().hasLocation())
8140 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07008141 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07008142 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07008143 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06008144 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07008145 }
John Kessenich140f3df2015-06-26 16:58:36 -06008146 if (symbol->getQualifier().hasSet())
8147 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07008148 else if (IsDescriptorResource(symbol->getType())) {
8149 // default to 0
8150 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
8151 }
John Kessenich140f3df2015-06-26 16:58:36 -06008152 if (symbol->getQualifier().hasBinding())
8153 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06008154 else if (IsDescriptorResource(symbol->getType())) {
8155 // default to 0
8156 builder.addDecoration(id, spv::DecorationBinding, 0);
8157 }
John Kessenich6c292d32016-02-15 20:58:50 -07008158 if (symbol->getQualifier().hasAttachment())
8159 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06008160 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07008161 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07008162 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008163 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07008164 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
8165 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
8166 builder.addDecoration(id, spv::DecorationXfbStride, stride);
8167 }
8168 if (symbol->getQualifier().hasXfbOffset())
8169 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008170 }
8171
John Kessenichb9197c82019-08-11 07:41:45 -06008172 // add built-in variable decoration
8173 if (builtIn != spv::BuiltInMax) {
8174 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
8175 }
8176
8177#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08008178 if (symbol->getType().isImage()) {
8179 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07008180 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
8181 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08008182 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07008183 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08008184 }
8185
John Kessenich5611c6d2018-04-05 11:25:02 -06008186 // nonuniform
8187 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
8188
chaoc0ad6a4e2016-12-19 16:29:34 -08008189 if (builtIn == spv::BuiltInSampleMask) {
8190 spv::Decoration decoration;
8191 // GL_NV_sample_mask_override_coverage extension
8192 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08008193 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08008194 else
8195 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07008196 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08008197 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07008198 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08008199 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
8200 }
8201 }
chaoc771d89f2017-01-13 01:10:53 -08008202 else if (builtIn == spv::BuiltInLayer) {
8203 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06008204 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008205 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08008206 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
8207 builder.addExtension(spv::E_SPV_NV_viewport_array2);
8208 }
John Kessenichb41bff62017-08-11 13:07:17 -06008209 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008210 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
8211 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08008212 builder.addCapability(spv::CapabilityShaderStereoViewNV);
8213 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
8214 }
8215 }
8216
chaoc6e5acae2016-12-20 13:28:52 -08008217 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008218 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08008219 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08008220 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
8221 }
Chao Chen9eada4b2018-09-19 11:39:56 -07008222 if (symbol->getQualifier().pervertexNV) {
8223 builder.addDecoration(id, spv::DecorationPerVertexNV);
8224 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
8225 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
8226 }
chaoc0ad6a4e2016-12-19 16:29:34 -08008227
John Kessenich5d610ee2018-03-07 18:05:55 -07008228 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
8229 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
8230 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
8231 symbol->getType().getQualifier().semanticName);
8232 }
8233
John Kessenich7015bd62019-08-01 03:28:08 -06008234 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07008235 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
8236 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008237 }
John Kessenichb9197c82019-08-11 07:41:45 -06008238#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008239
John Kessenich140f3df2015-06-26 16:58:36 -06008240 return id;
8241}
8242
John Kessenicha28f7a72019-08-06 07:00:58 -06008243#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008244// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
8245void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
8246{
8247 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07008248 if (qualifier.perPrimitiveNV) {
8249 // Need to add capability/extension for fragment shader.
8250 // Mesh shader already adds this by default.
8251 if (glslangIntermediate->getStage() == EShLangFragment) {
8252 builder.addCapability(spv::CapabilityMeshShadingNV);
8253 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8254 }
Chao Chen3c366992018-09-19 11:41:59 -07008255 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008256 }
Chao Chen3c366992018-09-19 11:41:59 -07008257 if (qualifier.perViewNV)
8258 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
8259 if (qualifier.perTaskNV)
8260 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
8261 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07008262 if (qualifier.perPrimitiveNV) {
8263 // Need to add capability/extension for fragment shader.
8264 // Mesh shader already adds this by default.
8265 if (glslangIntermediate->getStage() == EShLangFragment) {
8266 builder.addCapability(spv::CapabilityMeshShadingNV);
8267 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8268 }
Chao Chen3c366992018-09-19 11:41:59 -07008269 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008270 }
Chao Chen3c366992018-09-19 11:41:59 -07008271 if (qualifier.perViewNV)
8272 builder.addDecoration(id, spv::DecorationPerViewNV);
8273 if (qualifier.perTaskNV)
8274 builder.addDecoration(id, spv::DecorationPerTaskNV);
8275 }
8276}
8277#endif
8278
John Kessenich55e7d112015-11-15 21:33:39 -07008279// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008280// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008281//
8282// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8283//
8284// Recursively walk the nodes. The nodes form a tree whose leaves are
8285// regular constants, which themselves are trees that createSpvConstant()
8286// recursively walks. So, this function walks the "top" of the tree:
8287// - emit specialization constant-building instructions for specConstant
8288// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008289spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008290{
John Kessenich7cc0e282016-03-20 00:46:02 -06008291 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008292
qining4f4bb812016-04-03 23:55:17 -04008293 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008294 if (! node.getQualifier().specConstant) {
8295 // hand off to the non-spec-constant path
8296 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8297 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008298 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8299 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8300 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008301 }
8302
8303 // We now know we have a specialization constant to build
8304
Ricardo Garcia232ba0d2020-06-03 15:52:55 +02008305 // Extra capabilities may be needed.
8306 if (node.getType().contains8BitInt())
8307 builder.addCapability(spv::CapabilityInt8);
8308 if (node.getType().contains16BitFloat())
8309 builder.addCapability(spv::CapabilityFloat16);
8310 if (node.getType().contains16BitInt())
8311 builder.addCapability(spv::CapabilityInt16);
8312 if (node.getType().contains64BitInt())
8313 builder.addCapability(spv::CapabilityInt64);
8314 if (node.getType().containsDouble())
8315 builder.addCapability(spv::CapabilityFloat64);
8316
John Kessenichd94c0032016-05-30 19:29:40 -06008317 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008318 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8319 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8320 std::vector<spv::Id> dimConstId;
8321 for (int dim = 0; dim < 3; ++dim) {
8322 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8323 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008324 if (specConst) {
8325 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8326 glslangIntermediate->getLocalSizeSpecId(dim));
8327 }
qining4f4bb812016-04-03 23:55:17 -04008328 }
8329 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8330 }
8331
8332 // An AST node labelled as specialization constant should be a symbol node.
8333 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8334 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008335 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008336 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008337 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8338 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8339 // will set the builder into spec constant op instruction generating mode.
8340 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008341 result = accessChainLoad(sub_tree->getType());
8342 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008343 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008344 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008345 } else {
8346 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008347 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008348 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008349 builder.addName(result, sn->getName().c_str());
8350 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008351 }
qining4f4bb812016-04-03 23:55:17 -04008352
8353 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8354 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008355 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008356 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008357}
8358
John Kessenich140f3df2015-06-26 16:58:36 -06008359// Use 'consts' as the flattened glslang source of scalar constants to recursively
8360// build the aggregate SPIR-V constant.
8361//
8362// If there are not enough elements present in 'consts', 0 will be substituted;
8363// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8364//
John Kessenich8985fc92020-03-03 10:25:07 -07008365spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8366 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008367{
8368 // vector of constants for SPIR-V
8369 std::vector<spv::Id> spvConsts;
8370
8371 // Type is used for struct and array constants
8372 spv::Id typeId = convertGlslangToSpvType(glslangType);
8373
8374 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008375 glslang::TType elementType(glslangType, 0);
8376 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008377 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008378 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008379 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008380 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008381 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008382 } else if (glslangType.isCoopMat()) {
8383 glslang::TType componentType(glslangType.getBasicType());
8384 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008385 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008386 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8387 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008388 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008389 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008390 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8391 bool zero = nextConst >= consts.size();
8392 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008393 case glslang::EbtInt:
8394 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8395 break;
8396 case glslang::EbtUint:
8397 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8398 break;
8399 case glslang::EbtFloat:
8400 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8401 break;
8402 case glslang::EbtBool:
8403 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8404 break;
8405#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008406 case glslang::EbtInt8:
8407 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8408 break;
8409 case glslang::EbtUint8:
8410 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8411 break;
8412 case glslang::EbtInt16:
8413 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8414 break;
8415 case glslang::EbtUint16:
8416 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8417 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008418 case glslang::EbtInt64:
8419 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8420 break;
8421 case glslang::EbtUint64:
8422 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8423 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008424 case glslang::EbtDouble:
8425 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8426 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008427 case glslang::EbtFloat16:
8428 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8429 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008430#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008431 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008432 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008433 break;
8434 }
8435 ++nextConst;
8436 }
8437 } else {
8438 // we have a non-aggregate (scalar) constant
8439 bool zero = nextConst >= consts.size();
8440 spv::Id scalar = 0;
8441 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008442 case glslang::EbtInt:
8443 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8444 break;
8445 case glslang::EbtUint:
8446 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8447 break;
8448 case glslang::EbtFloat:
8449 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8450 break;
8451 case glslang::EbtBool:
8452 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8453 break;
8454#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008455 case glslang::EbtInt8:
8456 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8457 break;
8458 case glslang::EbtUint8:
8459 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8460 break;
8461 case glslang::EbtInt16:
8462 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8463 break;
8464 case glslang::EbtUint16:
8465 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8466 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008467 case glslang::EbtInt64:
8468 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8469 break;
8470 case glslang::EbtUint64:
8471 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8472 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008473 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008474 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008475 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008476 case glslang::EbtFloat16:
8477 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8478 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008479 case glslang::EbtReference:
8480 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8481 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8482 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008483#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008484 case glslang::EbtString:
8485 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8486 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008487 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008488 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008489 break;
8490 }
8491 ++nextConst;
8492 return scalar;
8493 }
8494
8495 return builder.makeCompositeConstant(typeId, spvConsts);
8496}
8497
John Kessenich7c1aa102015-10-15 13:29:11 -06008498// Return true if the node is a constant or symbol whose reading has no
8499// non-trivial observable cost or effect.
8500bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8501{
8502 // don't know what this is
8503 if (node == nullptr)
8504 return false;
8505
8506 // a constant is safe
8507 if (node->getAsConstantUnion() != nullptr)
8508 return true;
8509
8510 // not a symbol means non-trivial
8511 if (node->getAsSymbolNode() == nullptr)
8512 return false;
8513
8514 // a symbol, depends on what's being read
8515 switch (node->getType().getQualifier().storage) {
8516 case glslang::EvqTemporary:
8517 case glslang::EvqGlobal:
8518 case glslang::EvqIn:
8519 case glslang::EvqInOut:
8520 case glslang::EvqConst:
8521 case glslang::EvqConstReadOnly:
8522 case glslang::EvqUniform:
8523 return true;
8524 default:
8525 return false;
8526 }
qining25262b32016-05-06 17:25:16 -04008527}
John Kessenich7c1aa102015-10-15 13:29:11 -06008528
8529// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008530// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008531// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008532// Return true if trivial.
8533bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8534{
8535 if (node == nullptr)
8536 return false;
8537
John Kessenich84cc15f2017-05-24 16:44:47 -06008538 // count non scalars as trivial, as well as anything coming from HLSL
8539 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008540 return true;
8541
John Kessenich7c1aa102015-10-15 13:29:11 -06008542 // symbols and constants are trivial
8543 if (isTrivialLeaf(node))
8544 return true;
8545
8546 // otherwise, it needs to be a simple operation or one or two leaf nodes
8547
8548 // not a simple operation
8549 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8550 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8551 if (binaryNode == nullptr && unaryNode == nullptr)
8552 return false;
8553
8554 // not on leaf nodes
8555 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8556 return false;
8557
8558 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8559 return false;
8560 }
8561
8562 switch (node->getAsOperator()->getOp()) {
8563 case glslang::EOpLogicalNot:
8564 case glslang::EOpConvIntToBool:
8565 case glslang::EOpConvUintToBool:
8566 case glslang::EOpConvFloatToBool:
8567 case glslang::EOpConvDoubleToBool:
8568 case glslang::EOpEqual:
8569 case glslang::EOpNotEqual:
8570 case glslang::EOpLessThan:
8571 case glslang::EOpGreaterThan:
8572 case glslang::EOpLessThanEqual:
8573 case glslang::EOpGreaterThanEqual:
8574 case glslang::EOpIndexDirect:
8575 case glslang::EOpIndexDirectStruct:
8576 case glslang::EOpLogicalXor:
8577 case glslang::EOpAny:
8578 case glslang::EOpAll:
8579 return true;
8580 default:
8581 return false;
8582 }
8583}
8584
8585// Emit short-circuiting code, where 'right' is never evaluated unless
8586// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008587spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8588 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008589{
8590 spv::Id boolTypeId = builder.makeBoolType();
8591
8592 // emit left operand
8593 builder.clearAccessChain();
8594 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008595 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008596
8597 // Operands to accumulate OpPhi operands
8598 std::vector<spv::Id> phiOperands;
8599 // accumulate left operand's phi information
8600 phiOperands.push_back(leftId);
8601 phiOperands.push_back(builder.getBuildPoint()->getId());
8602
8603 // Make the two kinds of operation symmetric with a "!"
8604 // || => emit "if (! left) result = right"
8605 // && => emit "if ( left) result = right"
8606 //
8607 // TODO: this runtime "not" for || could be avoided by adding functionality
8608 // to 'builder' to have an "else" without an "then"
8609 if (op == glslang::EOpLogicalOr)
8610 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8611
8612 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008613 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008614
8615 // emit right operand as the "then" part of the "if"
8616 builder.clearAccessChain();
8617 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008618 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008619
8620 // accumulate left operand's phi information
8621 phiOperands.push_back(rightId);
8622 phiOperands.push_back(builder.getBuildPoint()->getId());
8623
8624 // finish the "if"
8625 ifBuilder.makeEndIf();
8626
8627 // phi together the two results
8628 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8629}
8630
John Kessenicha28f7a72019-08-06 07:00:58 -06008631#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008632// Return type Id of the imported set of extended instructions corresponds to the name.
8633// Import this set if it has not been imported yet.
8634spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8635{
8636 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8637 return extBuiltinMap[name];
8638 else {
Rex Xu51596642016-09-21 18:56:12 +08008639 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008640 spv::Id extBuiltins = builder.import(name);
8641 extBuiltinMap[name] = extBuiltins;
8642 return extBuiltins;
8643 }
8644}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008645#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008646
John Kessenich140f3df2015-06-26 16:58:36 -06008647}; // end anonymous namespace
8648
8649namespace glslang {
8650
John Kessenich68d78fd2015-07-12 19:28:10 -06008651void GetSpirvVersion(std::string& version)
8652{
John Kessenich9e55f632015-07-15 10:03:39 -06008653 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008654 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008655 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008656 version = buf;
8657}
8658
John Kessenicha372a3e2017-11-02 22:32:14 -06008659// For low-order part of the generator's magic number. Bump up
8660// when there is a change in the style (e.g., if SSA form changes,
8661// or a different instruction sequence to do something gets used).
8662int GetSpirvGeneratorVersion()
8663{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008664 // return 1; // start
8665 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008666 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008667 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008668 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008669 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8670 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008671 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenich3641ff72020-06-10 07:38:31 -06008672 // return 8; // switch to new dead block eliminator; use OpUnreachable
Graeme Leese060882f2020-06-22 11:03:46 +01008673 // return 9; // don't include opaque function parameters in OpEntryPoint global's operand list
8674 return 10; // Generate OpFUnordNotEqual for != comparisons
John Kessenicha372a3e2017-11-02 22:32:14 -06008675}
8676
John Kessenich140f3df2015-06-26 16:58:36 -06008677// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008678void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008679{
8680 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008681 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008682 if (out.fail())
8683 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008684 for (int i = 0; i < (int)spirv.size(); ++i) {
8685 unsigned int word = spirv[i];
8686 out.write((const char*)&word, 4);
8687 }
8688 out.close();
8689}
8690
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008691// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008692void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008693{
Shahbaz Youssefi1ef2e252020-07-03 15:42:53 -04008694#if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008695 std::ofstream out;
8696 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008697 if (out.fail())
8698 printf("ERROR: Failed to open file: %s\n", baseName);
Ben Claytonfbe9a232020-06-17 11:17:19 +01008699 out << "\t// " <<
8700 GetSpirvGeneratorVersion() <<
8701 GLSLANG_VERSION_MAJOR << "." << GLSLANG_VERSION_MINOR << "." << GLSLANG_VERSION_PATCH <<
8702 GLSLANG_VERSION_FLAVOR << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008703 if (varName != nullptr) {
8704 out << "\t #pragma once" << std::endl;
8705 out << "const uint32_t " << varName << "[] = {" << std::endl;
8706 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008707 const int WORDS_PER_LINE = 8;
8708 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8709 out << "\t";
8710 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8711 const unsigned int word = spirv[i + j];
8712 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8713 if (i + j + 1 < (int)spirv.size()) {
8714 out << ",";
8715 }
8716 }
8717 out << std::endl;
8718 }
Flavio15017db2017-02-15 14:29:33 -08008719 if (varName != nullptr) {
8720 out << "};";
johnkslangf881f082020-08-04 02:13:50 -06008721 out << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008722 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008723 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008724#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008725}
8726
John Kessenich140f3df2015-06-26 16:58:36 -06008727//
8728// Set up the glslang traversal
8729//
John Kessenich4e11b612018-08-30 16:56:59 -06008730void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008731{
Lei Zhang17535f72016-05-04 15:55:59 -04008732 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008733 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008734}
8735
John Kessenich4e11b612018-08-30 16:56:59 -06008736void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008737 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008738{
John Kessenich140f3df2015-06-26 16:58:36 -06008739 TIntermNode* root = intermediate.getTreeRoot();
8740
8741 if (root == 0)
8742 return;
8743
John Kessenich4e11b612018-08-30 16:56:59 -06008744 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008745 if (options == nullptr)
8746 options = &defaultOptions;
8747
John Kessenich4e11b612018-08-30 16:56:59 -06008748 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008749
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008750 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008751 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008752 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008753 it.dumpSpv(spirv);
8754
GregFfb03a552018-03-29 11:49:14 -06008755#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008756 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8757 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008758 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008759 if ((prelegalization || options->optimizeSize) && !options->disableOptimizer) {
8760 SpirvToolsTransform(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008761 prelegalization = false;
8762 }
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008763 else if (options->stripDebugInfo) {
8764 // Strip debug info even if optimization is disabled.
8765 SpirvToolsStripDebugInfo(intermediate, spirv, logger);
8766 }
John Kessenich717c80a2018-08-23 15:17:10 -06008767
John Kessenich4e11b612018-08-30 16:56:59 -06008768 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008769 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008770
John Kessenich717c80a2018-08-23 15:17:10 -06008771 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008772 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008773
GregFcd1f1692017-09-21 18:40:22 -06008774#endif
8775
John Kessenich4e11b612018-08-30 16:56:59 -06008776 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008777}
8778
8779}; // end namespace glslang