blob: 0b6c62b7f12ea46bed92900d441d4df68dcd73a1 [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
Sidney Just56350ca2020-11-02 11:27:40 -0800717 if (builder.getSpvVersion() < spv::Spv_1_5) {
718 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
719 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
720 }
721 else
722 builder.addCapability(spv::CapabilityShaderViewportIndex);
Rex Xu5e317ff2017-03-16 23:02:39 +0800723 }
John Kessenich92187592016-02-01 13:45:25 -0700724 return spv::BuiltInViewportIndex;
725
John Kessenich5e801132016-02-15 11:09:46 -0700726 case glslang::EbvSampleId:
727 builder.addCapability(spv::CapabilitySampleRateShading);
728 return spv::BuiltInSampleId;
729
730 case glslang::EbvSamplePosition:
731 builder.addCapability(spv::CapabilitySampleRateShading);
732 return spv::BuiltInSamplePosition;
733
734 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700735 return spv::BuiltInSampleMask;
736
John Kessenich78a45572016-07-08 14:05:15 -0600737 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700738 if (glslangIntermediate->getStage() == EShLangMeshNV) {
739 return spv::BuiltInLayer;
740 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600741 builder.addCapability(spv::CapabilityGeometry);
742 if (glslangIntermediate->getStage() == EShLangVertex ||
743 glslangIntermediate->getStage() == EShLangTessControl ||
744 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800745
Sidney Just56350ca2020-11-02 11:27:40 -0800746 if (builder.getSpvVersion() < spv::Spv_1_5) {
747 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
748 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
749 } else
750 builder.addCapability(spv::CapabilityShaderLayer);
Rex Xu5e317ff2017-03-16 23:02:39 +0800751 }
John Kessenich78a45572016-07-08 14:05:15 -0600752 return spv::BuiltInLayer;
753
John Kessenichda581a22015-10-14 14:10:30 -0600754 case glslang::EbvBaseVertex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600755 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800756 builder.addCapability(spv::CapabilityDrawParameters);
757 return spv::BuiltInBaseVertex;
758
John Kessenichda581a22015-10-14 14:10:30 -0600759 case glslang::EbvBaseInstance:
John Kessenich8317e6c2019-08-18 23:58:08 -0600760 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800761 builder.addCapability(spv::CapabilityDrawParameters);
762 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200763
John Kessenichda581a22015-10-14 14:10:30 -0600764 case glslang::EbvDrawId:
John Kessenich8317e6c2019-08-18 23:58:08 -0600765 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800766 builder.addCapability(spv::CapabilityDrawParameters);
767 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200768
769 case glslang::EbvPrimitiveId:
770 if (glslangIntermediate->getStage() == EShLangFragment)
771 builder.addCapability(spv::CapabilityGeometry);
772 return spv::BuiltInPrimitiveId;
773
Rex Xu37cdcee2017-06-29 17:46:34 +0800774 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800775 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
776 builder.addCapability(spv::CapabilityStencilExportEXT);
777 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800778
Chowa315b562020-07-02 15:50:36 +0800779 case glslang::EbvShadingRateKHR:
780 builder.addExtension(spv::E_SPV_KHR_fragment_shading_rate);
781 builder.addCapability(spv::CapabilityFragmentShadingRateKHR);
782 return spv::BuiltInShadingRateKHR;
783
784 case glslang::EbvPrimitiveShadingRateKHR:
785 builder.addExtension(spv::E_SPV_KHR_fragment_shading_rate);
786 builder.addCapability(spv::CapabilityFragmentShadingRateKHR);
787 return spv::BuiltInPrimitiveShadingRateKHR;
788
John Kessenich140f3df2015-06-26 16:58:36 -0600789 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600790 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
791 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
792 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
793 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
John Kessenich140f3df2015-06-26 16:58:36 -0600794 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
Rex Xu51596642016-09-21 18:56:12 +0800795
Rex Xu574ab042016-04-14 16:53:07 +0800796 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800797 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800798 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
799 return spv::BuiltInSubgroupSize;
800
Rex Xu574ab042016-04-14 16:53:07 +0800801 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800802 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800803 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
804 return spv::BuiltInSubgroupLocalInvocationId;
805
Rex Xu574ab042016-04-14 16:53:07 +0800806 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800807 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
808 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600809 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800810
Rex Xu574ab042016-04-14 16:53:07 +0800811 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800812 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
813 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600814 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800815
Rex Xu574ab042016-04-14 16:53:07 +0800816 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800817 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
818 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600819 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800820
Rex Xu574ab042016-04-14 16:53:07 +0800821 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800822 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
823 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600824 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800825
Rex Xu574ab042016-04-14 16:53:07 +0800826 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800827 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
828 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600829 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800830
John Kessenich66011cb2018-03-06 16:12:04 -0700831 case glslang::EbvNumSubgroups:
832 builder.addCapability(spv::CapabilityGroupNonUniform);
833 return spv::BuiltInNumSubgroups;
834
835 case glslang::EbvSubgroupID:
836 builder.addCapability(spv::CapabilityGroupNonUniform);
837 return spv::BuiltInSubgroupId;
838
839 case glslang::EbvSubgroupSize2:
840 builder.addCapability(spv::CapabilityGroupNonUniform);
841 return spv::BuiltInSubgroupSize;
842
843 case glslang::EbvSubgroupInvocation2:
844 builder.addCapability(spv::CapabilityGroupNonUniform);
845 return spv::BuiltInSubgroupLocalInvocationId;
846
847 case glslang::EbvSubgroupEqMask2:
848 builder.addCapability(spv::CapabilityGroupNonUniform);
849 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
850 return spv::BuiltInSubgroupEqMask;
851
852 case glslang::EbvSubgroupGeMask2:
853 builder.addCapability(spv::CapabilityGroupNonUniform);
854 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
855 return spv::BuiltInSubgroupGeMask;
856
857 case glslang::EbvSubgroupGtMask2:
858 builder.addCapability(spv::CapabilityGroupNonUniform);
859 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
860 return spv::BuiltInSubgroupGtMask;
861
862 case glslang::EbvSubgroupLeMask2:
863 builder.addCapability(spv::CapabilityGroupNonUniform);
864 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
865 return spv::BuiltInSubgroupLeMask;
866
867 case glslang::EbvSubgroupLtMask2:
868 builder.addCapability(spv::CapabilityGroupNonUniform);
869 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
870 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600871
Rex Xu17ff3432016-10-14 17:41:45 +0800872 case glslang::EbvBaryCoordNoPersp:
873 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
874 return spv::BuiltInBaryCoordNoPerspAMD;
875
876 case glslang::EbvBaryCoordNoPerspCentroid:
877 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
878 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
879
880 case glslang::EbvBaryCoordNoPerspSample:
881 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
882 return spv::BuiltInBaryCoordNoPerspSampleAMD;
883
884 case glslang::EbvBaryCoordSmooth:
885 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
886 return spv::BuiltInBaryCoordSmoothAMD;
887
888 case glslang::EbvBaryCoordSmoothCentroid:
889 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
890 return spv::BuiltInBaryCoordSmoothCentroidAMD;
891
892 case glslang::EbvBaryCoordSmoothSample:
893 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
894 return spv::BuiltInBaryCoordSmoothSampleAMD;
895
896 case glslang::EbvBaryCoordPullModel:
897 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
898 return spv::BuiltInBaryCoordPullModelAMD;
chaoc771d89f2017-01-13 01:10:53 -0800899
John Kessenich6c8aaac2017-02-27 01:20:51 -0700900 case glslang::EbvDeviceIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600901 builder.addIncorporatedExtension(spv::E_SPV_KHR_device_group, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700902 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700903 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700904
905 case glslang::EbvViewIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600906 builder.addIncorporatedExtension(spv::E_SPV_KHR_multiview, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700907 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700908 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700909
Daniel Koch5154db52018-11-26 10:01:58 -0500910 case glslang::EbvFragSizeEXT:
911 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
912 builder.addCapability(spv::CapabilityFragmentDensityEXT);
913 return spv::BuiltInFragSizeEXT;
914
915 case glslang::EbvFragInvocationCountEXT:
916 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
917 builder.addCapability(spv::CapabilityFragmentDensityEXT);
918 return spv::BuiltInFragInvocationCountEXT;
919
chaoc771d89f2017-01-13 01:10:53 -0800920 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800921 if (!memberDeclaration) {
922 builder.addExtension(spv::E_SPV_NV_viewport_array2);
923 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
924 }
chaoc771d89f2017-01-13 01:10:53 -0800925 return spv::BuiltInViewportMaskNV;
926 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800927 if (!memberDeclaration) {
928 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
929 builder.addCapability(spv::CapabilityShaderStereoViewNV);
930 }
chaoc771d89f2017-01-13 01:10:53 -0800931 return spv::BuiltInSecondaryPositionNV;
932 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800933 if (!memberDeclaration) {
934 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
935 builder.addCapability(spv::CapabilityShaderStereoViewNV);
936 }
chaoc771d89f2017-01-13 01:10:53 -0800937 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800938 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800939 if (!memberDeclaration) {
940 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
941 builder.addCapability(spv::CapabilityPerViewAttributesNV);
942 }
chaocdf3956c2017-02-14 14:52:34 -0800943 return spv::BuiltInPositionPerViewNV;
944 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800945 if (!memberDeclaration) {
946 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
947 builder.addCapability(spv::CapabilityPerViewAttributesNV);
948 }
chaocdf3956c2017-02-14 14:52:34 -0800949 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700950 case glslang::EbvFragFullyCoveredNV:
951 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
952 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
953 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700954 case glslang::EbvFragmentSizeNV:
955 builder.addExtension(spv::E_SPV_NV_shading_rate);
956 builder.addCapability(spv::CapabilityShadingRateNV);
957 return spv::BuiltInFragmentSizeNV;
958 case glslang::EbvInvocationsPerPixelNV:
959 builder.addExtension(spv::E_SPV_NV_shading_rate);
960 builder.addCapability(spv::CapabilityShadingRateNV);
961 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700962
Daniel Koch593a4e02019-05-27 16:46:31 -0400963 // ray tracing
Daniel Kochdb32b242020-03-17 20:42:47 -0400964 case glslang::EbvLaunchId:
965 return spv::BuiltInLaunchIdKHR;
966 case glslang::EbvLaunchSize:
967 return spv::BuiltInLaunchSizeKHR;
968 case glslang::EbvWorldRayOrigin:
969 return spv::BuiltInWorldRayOriginKHR;
970 case glslang::EbvWorldRayDirection:
971 return spv::BuiltInWorldRayDirectionKHR;
972 case glslang::EbvObjectRayOrigin:
973 return spv::BuiltInObjectRayOriginKHR;
974 case glslang::EbvObjectRayDirection:
975 return spv::BuiltInObjectRayDirectionKHR;
976 case glslang::EbvRayTmin:
977 return spv::BuiltInRayTminKHR;
978 case glslang::EbvRayTmax:
979 return spv::BuiltInRayTmaxKHR;
980 case glslang::EbvInstanceCustomIndex:
981 return spv::BuiltInInstanceCustomIndexKHR;
982 case glslang::EbvHitT:
983 return spv::BuiltInHitTKHR;
984 case glslang::EbvHitKind:
985 return spv::BuiltInHitKindKHR;
986 case glslang::EbvObjectToWorld:
987 case glslang::EbvObjectToWorld3x4:
988 return spv::BuiltInObjectToWorldKHR;
989 case glslang::EbvWorldToObject:
990 case glslang::EbvWorldToObject3x4:
991 return spv::BuiltInWorldToObjectKHR;
992 case glslang::EbvIncomingRayFlags:
993 return spv::BuiltInIncomingRayFlagsKHR;
994 case glslang::EbvGeometryIndex:
995 return spv::BuiltInRayGeometryIndexKHR;
Daniel Koch593a4e02019-05-27 16:46:31 -0400996
997 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700998 case glslang::EbvBaryCoordNV:
999 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
1000 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
1001 return spv::BuiltInBaryCoordNV;
1002 case glslang::EbvBaryCoordNoPerspNV:
1003 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
1004 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
1005 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001006
1007 // mesh shaders
1008 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001009 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001010 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001011 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001012 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -07001013 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001014 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001015 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001016 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001017 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001018 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001019 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001020 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001021 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001022 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -07001023 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch2cb2f192019-06-04 08:43:32 -04001024
1025 // sm builtins
1026 case glslang::EbvWarpsPerSM:
1027 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1028 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1029 return spv::BuiltInWarpsPerSMNV;
1030 case glslang::EbvSMCount:
1031 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1032 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1033 return spv::BuiltInSMCountNV;
1034 case glslang::EbvWarpID:
1035 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1036 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1037 return spv::BuiltInWarpIDNV;
1038 case glslang::EbvSMID:
1039 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1040 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1041 return spv::BuiltInSMIDNV;
John Kessenicha28f7a72019-08-06 07:00:58 -06001042#endif
1043
Rex Xu3e783f92017-02-22 16:44:48 +08001044 default:
1045 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -06001046 }
1047}
1048
Rex Xufc618912015-09-09 16:42:49 +08001049// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -07001050spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +08001051{
1052 assert(type.getBasicType() == glslang::EbtSampler);
1053
John Kessenichb9197c82019-08-11 07:41:45 -06001054#ifdef GLSLANG_WEB
1055 return spv::ImageFormatUnknown;
1056#endif
1057
John Kessenich5d0fa972016-02-15 11:57:00 -07001058 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -06001059 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -07001060 case glslang::ElfRg32f:
1061 case glslang::ElfRg16f:
1062 case glslang::ElfR11fG11fB10f:
1063 case glslang::ElfR16f:
1064 case glslang::ElfRgba16:
1065 case glslang::ElfRgb10A2:
1066 case glslang::ElfRg16:
1067 case glslang::ElfRg8:
1068 case glslang::ElfR16:
1069 case glslang::ElfR8:
1070 case glslang::ElfRgba16Snorm:
1071 case glslang::ElfRg16Snorm:
1072 case glslang::ElfRg8Snorm:
1073 case glslang::ElfR16Snorm:
1074 case glslang::ElfR8Snorm:
1075
1076 case glslang::ElfRg32i:
1077 case glslang::ElfRg16i:
1078 case glslang::ElfRg8i:
1079 case glslang::ElfR16i:
1080 case glslang::ElfR8i:
1081
1082 case glslang::ElfRgb10a2ui:
1083 case glslang::ElfRg32ui:
1084 case glslang::ElfRg16ui:
1085 case glslang::ElfRg8ui:
1086 case glslang::ElfR16ui:
1087 case glslang::ElfR8ui:
1088 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1089 break;
1090
1091 default:
1092 break;
1093 }
1094
1095 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001096 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001097 case glslang::ElfNone: return spv::ImageFormatUnknown;
1098 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1099 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1100 case glslang::ElfR32f: return spv::ImageFormatR32f;
1101 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1102 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1103 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1104 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1105 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1106 case glslang::ElfR16f: return spv::ImageFormatR16f;
1107 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1108 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1109 case glslang::ElfRg16: return spv::ImageFormatRg16;
1110 case glslang::ElfRg8: return spv::ImageFormatRg8;
1111 case glslang::ElfR16: return spv::ImageFormatR16;
1112 case glslang::ElfR8: return spv::ImageFormatR8;
1113 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1114 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1115 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1116 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1117 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1118 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1119 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1120 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1121 case glslang::ElfR32i: return spv::ImageFormatR32i;
1122 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1123 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1124 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1125 case glslang::ElfR16i: return spv::ImageFormatR16i;
1126 case glslang::ElfR8i: return spv::ImageFormatR8i;
1127 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1128 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1129 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1130 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1131 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1132 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1133 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1134 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1135 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1136 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001137 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001138 }
1139}
1140
John Kessenich8985fc92020-03-03 10:25:07 -07001141spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(
1142 const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001143{
John Kesseniche18fd202018-01-30 11:01:39 -07001144 if (selectionNode.getFlatten())
1145 return spv::SelectionControlFlattenMask;
1146 if (selectionNode.getDontFlatten())
1147 return spv::SelectionControlDontFlattenMask;
1148 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001149}
1150
John Kessenich8985fc92020-03-03 10:25:07 -07001151spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode)
1152 const
steve-lunargf1709e72017-05-02 20:14:50 -06001153{
John Kesseniche18fd202018-01-30 11:01:39 -07001154 if (switchNode.getFlatten())
1155 return spv::SelectionControlFlattenMask;
1156 if (switchNode.getDontFlatten())
1157 return spv::SelectionControlDontFlattenMask;
1158 return spv::SelectionControlMaskNone;
1159}
1160
John Kessenicha2858d92018-01-31 08:11:18 -07001161// return a non-0 dependency if the dependency argument must be set
1162spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001163 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001164{
1165 spv::LoopControlMask control = spv::LoopControlMaskNone;
1166
1167 if (loopNode.getDontUnroll())
1168 control = control | spv::LoopControlDontUnrollMask;
1169 if (loopNode.getUnroll())
1170 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001171 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001172 control = control | spv::LoopControlDependencyInfiniteMask;
1173 else if (loopNode.getLoopDependency() > 0) {
1174 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001175 operands.push_back((unsigned int)loopNode.getLoopDependency());
1176 }
1177 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1178 if (loopNode.getMinIterations() > 0) {
1179 control = control | spv::LoopControlMinIterationsMask;
1180 operands.push_back(loopNode.getMinIterations());
1181 }
1182 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1183 control = control | spv::LoopControlMaxIterationsMask;
1184 operands.push_back(loopNode.getMaxIterations());
1185 }
1186 if (loopNode.getIterationMultiple() > 1) {
1187 control = control | spv::LoopControlIterationMultipleMask;
1188 operands.push_back(loopNode.getIterationMultiple());
1189 }
1190 if (loopNode.getPeelCount() > 0) {
1191 control = control | spv::LoopControlPeelCountMask;
1192 operands.push_back(loopNode.getPeelCount());
1193 }
1194 if (loopNode.getPartialCount() > 0) {
1195 control = control | spv::LoopControlPartialCountMask;
1196 operands.push_back(loopNode.getPartialCount());
1197 }
John Kessenicha2858d92018-01-31 08:11:18 -07001198 }
John Kesseniche18fd202018-01-30 11:01:39 -07001199
1200 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001201}
1202
John Kessenicha5c5fb62017-05-05 05:09:58 -06001203// Translate glslang type to SPIR-V storage class.
1204spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1205{
Torosdagli06c2eee2020-03-19 11:09:57 -04001206 if (type.getBasicType() == glslang::EbtRayQuery)
Neslisah Torosdagli054b5e32020-03-26 12:24:31 -04001207 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001208 if (type.getQualifier().isPipeInput())
1209 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001210 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001211 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001212
1213 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001214 type.getQualifier().storage == glslang::EvqUniform) {
John Kessenichdeec1932019-08-13 08:00:30 -06001215 if (type.isAtomic())
John Kessenichbed4e4f2017-09-08 02:38:07 -06001216 return spv::StorageClassAtomicCounter;
1217 if (type.containsOpaque())
1218 return spv::StorageClassUniformConstant;
1219 }
1220
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001221 if (type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001222 type.getQualifier().isShaderRecord()) {
1223 return spv::StorageClassShaderRecordBufferKHR;
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001224 }
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001225
John Kessenichbed4e4f2017-09-08 02:38:07 -06001226 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001227 builder.addIncorporatedExtension(spv::E_SPV_KHR_storage_buffer_storage_class, spv::Spv_1_3);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001228 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001229 }
1230
1231 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich7015bd62019-08-01 03:28:08 -06001232 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001233 return spv::StorageClassPushConstant;
1234 if (type.getBasicType() == glslang::EbtBlock)
1235 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001236 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001237 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001238
1239 switch (type.getQualifier().storage) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001240 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1241 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1242 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenichdeec1932019-08-13 08:00:30 -06001243 case glslang::EvqShared: return spv::StorageClassWorkgroup;
John Kessenich3dd1ce52019-10-17 07:08:40 -06001244#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -04001245 case glslang::EvqPayload: return spv::StorageClassRayPayloadKHR;
1246 case glslang::EvqPayloadIn: return spv::StorageClassIncomingRayPayloadKHR;
1247 case glslang::EvqHitAttr: return spv::StorageClassHitAttributeKHR;
1248 case glslang::EvqCallableData: return spv::StorageClassCallableDataKHR;
1249 case glslang::EvqCallableDataIn: return spv::StorageClassIncomingCallableDataKHR;
Chao Chenb50c02e2018-09-19 11:42:24 -07001250#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001251 default:
1252 assert(0);
1253 break;
1254 }
1255
1256 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001257}
1258
John Kessenich5611c6d2018-04-05 11:25:02 -06001259// Add capabilities pertaining to how an array is indexed.
1260void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1261 const glslang::TType& indexType)
1262{
John Kessenichb9197c82019-08-11 07:41:45 -06001263#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06001264 if (indexType.getQualifier().isNonUniform()) {
1265 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001266 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001267 if (baseType.getBasicType() == glslang::EbtSampler) {
1268 if (baseType.getQualifier().hasAttachment())
1269 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001270 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001271 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001272 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001273 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1274 else if (baseType.isImage())
1275 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1276 else if (baseType.isTexture())
1277 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1278 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1279 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1280 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1281 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1282 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1283 }
1284 } else {
1285 // assume a dynamically uniform index
1286 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001287 if (baseType.getQualifier().hasAttachment()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001288 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001289 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001290 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001291 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001292 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001293 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001294 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001295 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001296 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001297 }
1298 }
John Kessenichb9197c82019-08-11 07:41:45 -06001299#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06001300}
1301
qining25262b32016-05-06 17:25:16 -04001302// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001303// descriptor set.
1304bool IsDescriptorResource(const glslang::TType& type)
1305{
John Kessenichf7497e22016-03-08 21:36:22 -07001306 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001307 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001308 return type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001309 ! type.getQualifier().isShaderRecord() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001310 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001311
1312 // non block...
1313 // basically samplerXXX/subpass/sampler/texture are all included
1314 // if they are the global-scope-class, not the function parameter
1315 // (or local, if they ever exist) class.
alelenv999d4fd2020-06-01 23:24:41 -07001316 if (type.getBasicType() == glslang::EbtSampler ||
1317 type.getBasicType() == glslang::EbtAccStruct)
John Kessenich6c292d32016-02-15 20:58:50 -07001318 return type.getQualifier().isUniformOrBuffer();
1319
1320 // None of the above.
1321 return false;
1322}
1323
John Kesseniche0b6cad2015-12-24 10:30:13 -07001324void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1325{
1326 if (child.layoutMatrix == glslang::ElmNone)
1327 child.layoutMatrix = parent.layoutMatrix;
1328
1329 if (parent.invariant)
1330 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001331 if (parent.flat)
1332 child.flat = true;
1333 if (parent.centroid)
1334 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001335#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001336 if (parent.nopersp)
1337 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001338 if (parent.explicitInterp)
1339 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001340 if (parent.perPrimitiveNV)
1341 child.perPrimitiveNV = true;
1342 if (parent.perViewNV)
1343 child.perViewNV = true;
1344 if (parent.perTaskNV)
1345 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001346 if (parent.patch)
1347 child.patch = true;
1348 if (parent.sample)
1349 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001350 if (parent.coherent)
1351 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001352 if (parent.devicecoherent)
1353 child.devicecoherent = true;
1354 if (parent.queuefamilycoherent)
1355 child.queuefamilycoherent = true;
1356 if (parent.workgroupcoherent)
1357 child.workgroupcoherent = true;
1358 if (parent.subgroupcoherent)
1359 child.subgroupcoherent = true;
Daniel Kochdb32b242020-03-17 20:42:47 -04001360 if (parent.shadercallcoherent)
1361 child.shadercallcoherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001362 if (parent.nonprivate)
1363 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001364 if (parent.volatil)
1365 child.volatil = true;
1366 if (parent.restrict)
1367 child.restrict = true;
1368 if (parent.readonly)
1369 child.readonly = true;
1370 if (parent.writeonly)
1371 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001372#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001373}
1374
John Kessenichf2b7f332016-09-01 17:05:23 -06001375bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001376{
John Kessenich7b9fa252016-01-21 18:56:57 -07001377 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001378 // - struct members might inherit from a struct declaration
1379 // (note that non-block structs don't explicitly inherit,
1380 // only implicitly, meaning no decoration involved)
1381 // - affect decorations on the struct members
1382 // (note smooth does not, and expecting something like volatile
1383 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001384 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001385 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001386}
1387
John Kessenich140f3df2015-06-26 16:58:36 -06001388//
1389// Implement the TGlslangToSpvTraverser class.
1390//
1391
John Kessenich8985fc92020-03-03 10:25:07 -07001392TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion,
1393 const glslang::TIntermediate* glslangIntermediate,
1394 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options) :
1395 TIntermTraverser(true, false, true),
1396 options(options),
1397 shaderEntry(nullptr), currentFunction(nullptr),
1398 sequenceDepth(0), logger(buildLogger),
1399 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
1400 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
1401 glslangIntermediate(glslangIntermediate),
Jeff Bolz04d73732019-05-31 13:06:01 -05001402 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp()),
1403 nonSemanticDebugPrintf(0)
John Kessenich140f3df2015-06-26 16:58:36 -06001404{
1405 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1406
1407 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001408 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1409 glslangIntermediate->getVersion());
1410
John Kessenich121853f2017-05-31 17:11:16 -06001411 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001412 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001413 builder.setSourceFile(glslangIntermediate->getSourceFile());
1414
1415 // Set the source shader's text. If for SPV version 1.0, include
1416 // a preamble in comments stating the OpModuleProcessed instructions.
1417 // Otherwise, emit those as actual instructions.
1418 std::string text;
1419 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1420 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001421 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001422 text.append("// OpModuleProcessed ");
1423 text.append(processes[p]);
1424 text.append("\n");
1425 } else
1426 builder.addModuleProcessed(processes[p]);
1427 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001428 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001429 text.append("#line 1\n");
1430 text.append(glslangIntermediate->getSourceText());
1431 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001432 // Pass name and text for all included files
1433 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1434 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1435 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001436 }
John Kessenich140f3df2015-06-26 16:58:36 -06001437 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001438
1439 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1440 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1441
1442 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1443 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
John Kessenich1ff0c182019-10-10 12:01:13 -06001444 builder.addIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001445 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
John Kessenich8985fc92020-03-03 10:25:07 -07001446 }
Jeff Bolz36831c92018-09-05 10:11:41 -05001447 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001448 memoryModel = spv::MemoryModelVulkanKHR;
1449 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001450 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001451 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001452 builder.setMemoryModel(addressingModel, memoryModel);
1453
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001454 if (glslangIntermediate->usingVariablePointers()) {
1455 builder.addCapability(spv::CapabilityVariablePointers);
1456 }
1457
John Kessenicheee9d532016-09-19 18:09:30 -06001458 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1459 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001460
1461 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001462 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1463 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
johnkslang01384722020-08-14 08:40:06 -06001464 builder.addSourceExtension(it->c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001465
1466 // Add the top-level modes for this shader.
1467
John Kessenich92187592016-02-01 13:45:25 -07001468 if (glslangIntermediate->getXfbMode()) {
1469 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001470 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001471 }
John Kessenich140f3df2015-06-26 16:58:36 -06001472
alelenv59216d52020-05-21 04:38:41 -07001473 if (glslangIntermediate->getLayoutPrimitiveCulling()) {
alelenv75de1962020-04-08 21:09:20 -07001474 builder.addCapability(spv::CapabilityRayTraversalPrimitiveCullingProvisionalKHR);
1475 }
1476
John Kessenich140f3df2015-06-26 16:58:36 -06001477 unsigned int mode;
1478 switch (glslangIntermediate->getStage()) {
1479 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001480 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001481 break;
1482
John Kessenicha28f7a72019-08-06 07:00:58 -06001483 case EShLangFragment:
1484 builder.addCapability(spv::CapabilityShader);
1485 if (glslangIntermediate->getPixelCenterInteger())
1486 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1487
1488 if (glslangIntermediate->getOriginUpperLeft())
1489 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1490 else
1491 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1492
1493 if (glslangIntermediate->getEarlyFragmentTests())
1494 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1495
1496 if (glslangIntermediate->getPostDepthCoverage()) {
1497 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1498 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1499 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1500 }
1501
John Kessenichb9197c82019-08-11 07:41:45 -06001502 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1503 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1504
1505#ifndef GLSLANG_WEB
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001506
John Kessenicha28f7a72019-08-06 07:00:58 -06001507 switch(glslangIntermediate->getDepth()) {
1508 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1509 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1510 default: mode = spv::ExecutionModeMax; break;
1511 }
1512 if (mode != spv::ExecutionModeMax)
1513 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001514 switch (glslangIntermediate->getInterlockOrdering()) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001515 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT;
1516 break;
1517 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT;
1518 break;
1519 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT;
1520 break;
1521 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT;
1522 break;
1523 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT;
1524 break;
1525 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT;
1526 break;
1527 default: mode = spv::ExecutionModeMax;
1528 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001529 }
1530 if (mode != spv::ExecutionModeMax) {
1531 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1532 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1533 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1534 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1535 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1536 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1537 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1538 } else {
1539 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1540 }
1541 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1542 }
John Kessenichb9197c82019-08-11 07:41:45 -06001543#endif
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001544 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001545
John Kessenicha28f7a72019-08-06 07:00:58 -06001546 case EShLangCompute:
1547 builder.addCapability(spv::CapabilityShader);
1548 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1549 glslangIntermediate->getLocalSize(1),
1550 glslangIntermediate->getLocalSize(2));
1551 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1552 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1553 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1554 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1555 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1556 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1557 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1558 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1559 }
1560 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001561#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001562 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001563 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001564 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001565
steve-lunarge7412492017-03-23 11:56:07 -06001566 glslang::TLayoutGeometry primitive;
1567
1568 if (glslangIntermediate->getStage() == EShLangTessControl) {
John Kessenich8985fc92020-03-03 10:25:07 -07001569 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1570 glslangIntermediate->getVertices());
steve-lunarge7412492017-03-23 11:56:07 -06001571 primitive = glslangIntermediate->getOutputPrimitive();
1572 } else {
1573 primitive = glslangIntermediate->getInputPrimitive();
1574 }
1575
1576 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001577 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1578 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1579 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001580 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001581 }
John Kessenich4016e382016-07-15 11:53:56 -06001582 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001583 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1584
John Kesseniche6903322015-10-13 16:29:02 -06001585 switch (glslangIntermediate->getVertexSpacing()) {
1586 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1587 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1588 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001589 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001590 }
John Kessenich4016e382016-07-15 11:53:56 -06001591 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001592 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1593
1594 switch (glslangIntermediate->getVertexOrder()) {
1595 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1596 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001597 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001598 }
John Kessenich4016e382016-07-15 11:53:56 -06001599 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001600 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1601
1602 if (glslangIntermediate->getPointMode())
1603 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001604 break;
1605
1606 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001607 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001608 switch (glslangIntermediate->getInputPrimitive()) {
1609 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1610 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1611 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001612 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001613 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001614 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001615 }
John Kessenich4016e382016-07-15 11:53:56 -06001616 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001617 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001618
John Kessenich140f3df2015-06-26 16:58:36 -06001619 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1620
1621 switch (glslangIntermediate->getOutputPrimitive()) {
1622 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1623 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1624 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001625 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001626 }
John Kessenich4016e382016-07-15 11:53:56 -06001627 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001628 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1629 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1630 break;
1631
Daniel Kochdb32b242020-03-17 20:42:47 -04001632 case EShLangRayGen:
1633 case EShLangIntersect:
1634 case EShLangAnyHit:
1635 case EShLangClosestHit:
1636 case EShLangMiss:
1637 case EShLangCallable:
1638 {
1639 auto& extensions = glslangIntermediate->getRequestedExtensions();
1640 if (extensions.find("GL_NV_ray_tracing") == extensions.end()) {
1641 builder.addCapability(spv::CapabilityRayTracingProvisionalKHR);
1642 builder.addExtension("SPV_KHR_ray_tracing");
1643 }
1644 else {
1645 builder.addCapability(spv::CapabilityRayTracingNV);
1646 builder.addExtension("SPV_NV_ray_tracing");
1647 }
Chao Chenb50c02e2018-09-19 11:42:24 -07001648 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04001649 }
Chao Chen3c366992018-09-19 11:41:59 -07001650 case EShLangTaskNV:
1651 case EShLangMeshNV:
1652 builder.addCapability(spv::CapabilityMeshShadingNV);
1653 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1654 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1655 glslangIntermediate->getLocalSize(1),
1656 glslangIntermediate->getLocalSize(2));
1657 if (glslangIntermediate->getStage() == EShLangMeshNV) {
John Kessenich8985fc92020-03-03 10:25:07 -07001658 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1659 glslangIntermediate->getVertices());
1660 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV,
1661 glslangIntermediate->getPrimitives());
Chao Chen3c366992018-09-19 11:41:59 -07001662
1663 switch (glslangIntermediate->getOutputPrimitive()) {
1664 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1665 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1666 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1667 default: mode = spv::ExecutionModeMax; break;
1668 }
1669 if (mode != spv::ExecutionModeMax)
1670 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1671 }
1672 break;
1673#endif
1674
John Kessenich140f3df2015-06-26 16:58:36 -06001675 default:
1676 break;
1677 }
John Kessenich140f3df2015-06-26 16:58:36 -06001678}
1679
John Kessenichfca82622016-11-26 13:23:20 -07001680// Finish creating SPV, after the traversal is complete.
1681void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001682{
John Kessenichf04c51b2018-08-03 15:56:12 -06001683 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001684 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001685 builder.setBuildPoint(shaderEntry->getLastBlock());
1686 builder.leaveFunction();
1687 }
1688
John Kessenich7ba63412015-12-20 17:37:07 -07001689 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001690 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1691 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001692
David Neto8c3d5b42019-10-21 14:50:31 -04001693 // Add capabilities, extensions, remove unneeded decorations, etc.,
John Kessenichf04c51b2018-08-03 15:56:12 -06001694 // based on the resulting SPIR-V.
David Neto8c3d5b42019-10-21 14:50:31 -04001695 // Note: WebGPU code generation must have the opportunity to aggressively
1696 // prune unreachable merge blocks and continue targets.
John Kessenichf04c51b2018-08-03 15:56:12 -06001697 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001698}
1699
John Kessenichfca82622016-11-26 13:23:20 -07001700// Write the SPV into 'out'.
1701void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001702{
John Kessenichfca82622016-11-26 13:23:20 -07001703 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001704}
1705
1706//
1707// Implement the traversal functions.
1708//
1709// Return true from interior nodes to have the external traversal
1710// continue on to children. Return false if children were
1711// already processed.
1712//
1713
1714//
qining25262b32016-05-06 17:25:16 -04001715// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001716// - uniform/input reads
1717// - output writes
1718// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1719// - something simple that degenerates into the last bullet
1720//
1721void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1722{
qining75d1d802016-04-06 14:42:01 -04001723 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
Roy05a5b532020-01-03 16:21:34 +08001724 if (symbol->getType().isStruct())
1725 glslangTypeToIdMap[symbol->getType().getStruct()] = symbol->getId();
1726
qining75d1d802016-04-06 14:42:01 -04001727 if (symbol->getType().getQualifier().isSpecConstant())
1728 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1729
Rex Xuf6e0fe82020-10-23 22:54:35 +08001730#ifdef ENABLE_HLSL
1731 // Skip symbol handling if it is string-typed
1732 if (symbol->getBasicType() == glslang::EbtString)
1733 return;
1734#endif
1735
John Kessenich140f3df2015-06-26 16:58:36 -06001736 // getSymbolId() will set up all the IO decorations on the first call.
1737 // Formal function parameters were mapped during makeFunctions().
1738 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001739
John Kessenich7ba63412015-12-20 17:37:07 -07001740 if (builder.isPointer(id)) {
John Kessenichc30d3352020-06-10 07:15:24 -06001741 if (!symbol->getType().getQualifier().isParamInput() &&
1742 !symbol->getType().getQualifier().isParamOutput()) {
1743 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1744 // Consider adding to the OpEntryPoint interface list.
1745 // Only looking at structures if they have at least one member.
1746 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1747 spv::StorageClass sc = builder.getStorageClass(id);
1748 // Before SPIR-V 1.4, we only want to include Input and Output.
1749 // Starting with SPIR-V 1.4, we want all globals.
John Kessenich4e13c902020-07-13 00:35:58 -06001750 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && builder.isGlobalStorage(id)) ||
John Kessenichc30d3352020-06-10 07:15:24 -06001751 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
1752 iOSet.insert(id);
1753 }
John Kessenich7c7731e2019-01-04 16:47:06 +07001754 }
John Kessenich5f77d862017-09-19 11:09:59 -06001755 }
John Kessenich9c14f772019-06-17 08:38:35 -06001756
Daniel Kochdb32b242020-03-17 20:42:47 -04001757 // If the SPIR-V type is required to be different than the AST type
1758 // (for ex SubgroupMasks or 3x4 ObjectToWorld/WorldToObject matrices),
John Kessenich9c14f772019-06-17 08:38:35 -06001759 // translate now from the SPIR-V type to the AST type, for the consuming
1760 // operation.
1761 // Note this turns it from an l-value to an r-value.
1762 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1763 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1764 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001765 }
1766
1767 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001768 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001769 // Prepare to generate code for the access
1770
1771 // L-value chains will be computed left to right. We're on the symbol now,
1772 // which is the left-most part of the access chain, so now is "clear" time,
1773 // followed by setting the base.
1774 builder.clearAccessChain();
1775
1776 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001777 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001778 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001779 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001780 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001781 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001782 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001783 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001784 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1785 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001786 builder.setAccessChainRValue(id);
1787 else
1788 builder.setAccessChainLValue(id);
1789 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001790
John Kessenichb9197c82019-08-11 07:41:45 -06001791#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001792 // Process linkage-only nodes for any special additional interface work.
1793 if (linkageOnly) {
1794 if (glslangIntermediate->getHlslFunctionality1()) {
1795 // Map implicit counter buffers to their originating buffers, which should have been
1796 // seen by now, given earlier pruning of unused counters, and preservation of order
1797 // of declaration.
1798 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1799 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1800 // Save possible originating buffers for counter buffers, keyed by
1801 // making the potential counter-buffer name.
1802 std::string keyName = symbol->getName().c_str();
1803 keyName = glslangIntermediate->addCounterBufferName(keyName);
1804 counterOriginator[keyName] = symbol;
1805 } else {
1806 // Handle a counter buffer, by finding the saved originating buffer.
1807 std::string keyName = symbol->getName().c_str();
1808 auto it = counterOriginator.find(keyName);
1809 if (it != counterOriginator.end()) {
1810 id = getSymbolId(it->second);
1811 if (id != spv::NoResult) {
1812 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001813 if (counterId != spv::NoResult) {
1814 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001815 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001816 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001817 }
1818 }
1819 }
1820 }
1821 }
1822 }
John Kessenich155d3512019-08-08 23:29:20 -06001823#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001824}
1825
1826bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1827{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001828 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Roy05a5b532020-01-03 16:21:34 +08001829 if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
1830 glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
1831 }
1832 if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
1833 glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
1834 }
John Kesseniche485c7a2017-05-31 18:50:53 -06001835
qining40887662016-04-03 22:20:42 -04001836 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1837 if (node->getType().getQualifier().isSpecConstant())
1838 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1839
John Kessenich140f3df2015-06-26 16:58:36 -06001840 // First, handle special cases
1841 switch (node->getOp()) {
1842 case glslang::EOpAssign:
1843 case glslang::EOpAddAssign:
1844 case glslang::EOpSubAssign:
1845 case glslang::EOpMulAssign:
1846 case glslang::EOpVectorTimesMatrixAssign:
1847 case glslang::EOpVectorTimesScalarAssign:
1848 case glslang::EOpMatrixTimesScalarAssign:
1849 case glslang::EOpMatrixTimesMatrixAssign:
1850 case glslang::EOpDivAssign:
1851 case glslang::EOpModAssign:
1852 case glslang::EOpAndAssign:
1853 case glslang::EOpInclusiveOrAssign:
1854 case glslang::EOpExclusiveOrAssign:
1855 case glslang::EOpLeftShiftAssign:
1856 case glslang::EOpRightShiftAssign:
1857 // A bin-op assign "a += b" means the same thing as "a = a + b"
1858 // where a is evaluated before b. For a simple assignment, GLSL
1859 // says to evaluate the left before the right. So, always, left
1860 // node then right node.
1861 {
1862 // get the left l-value, save it away
1863 builder.clearAccessChain();
1864 node->getLeft()->traverse(this);
1865 spv::Builder::AccessChain lValue = builder.getAccessChain();
1866
1867 // evaluate the right
1868 builder.clearAccessChain();
1869 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001870 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001871
1872 if (node->getOp() != glslang::EOpAssign) {
1873 // the left is also an r-value
1874 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001875 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001876
1877 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001878 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001879 TranslateNoContractionDecoration(node->getType().getQualifier()),
1880 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001881 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001882 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1883 node->getType().getBasicType());
1884
1885 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001886 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001887 }
1888
1889 // store the result
1890 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001891 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001892
1893 // assignments are expressions having an rValue after they are evaluated...
1894 builder.clearAccessChain();
1895 builder.setAccessChainRValue(rValue);
1896 }
1897 return false;
1898 case glslang::EOpIndexDirect:
1899 case glslang::EOpIndexDirectStruct:
1900 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001901 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001902 // Get the left part of the access chain.
1903 node->getLeft()->traverse(this);
1904
1905 // Add the next element in the chain
1906
David Netoa901ffe2016-06-08 14:11:40 +01001907 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001908 if (! node->getLeft()->getType().isArray() &&
1909 node->getLeft()->getType().isVector() &&
1910 node->getOp() == glslang::EOpIndexDirect) {
1911 // This is essentially a hard-coded vector swizzle of size 1,
1912 // so short circuit the access-chain stuff with a swizzle.
1913 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001914 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001915 int dummySize;
1916 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1917 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001918 glslangIntermediate->getBaseAlignmentScalar(
1919 node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001920 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001921
1922 // Load through a block reference is performed with a dot operator that
1923 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1924 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001925 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001926 !node->getLeft()->getType().isArray() &&
1927 node->getOp() == glslang::EOpIndexDirectStruct)
1928 {
1929 spv::Id left = accessChainLoad(node->getLeft()->getType());
1930 builder.clearAccessChain();
1931 builder.setAccessChainLValue(left);
1932 }
1933
David Netoa901ffe2016-06-08 14:11:40 +01001934 int spvIndex = glslangIndex;
1935 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1936 node->getOp() == glslang::EOpIndexDirectStruct)
1937 {
1938 // This may be, e.g., an anonymous block-member selection, which generally need
1939 // index remapping due to hidden members in anonymous blocks.
Roy05a5b532020-01-03 16:21:34 +08001940 int glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
1941 if (memberRemapper.find(glslangId) != memberRemapper.end()) {
1942 std::vector<int>& remapper = memberRemapper[glslangId];
1943 assert(remapper.size() > 0);
1944 spvIndex = remapper[glslangIndex];
1945 }
David Netoa901ffe2016-06-08 14:11:40 +01001946 }
John Kessenichebb50532016-05-16 19:22:05 -06001947
David Netoa901ffe2016-06-08 14:11:40 +01001948 // normal case for indexing array or structure or block
John Kessenich8985fc92020-03-03 10:25:07 -07001949 builder.accessChainPush(builder.makeIntConstant(spvIndex),
1950 TranslateCoherent(node->getLeft()->getType()),
1951 node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001952
1953 // Add capabilities here for accessing PointSize and clip/cull distance.
1954 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001955 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001956 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001957 }
1958 }
1959 return false;
1960 case glslang::EOpIndexIndirect:
1961 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001962 // Array, matrix, or vector indirection with variable index.
1963 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001964 // matrices are arrays of vectors, so will also work for a matrix.
1965 // Will use the access chain's 'component' for variable index into a vector.
1966
1967 // This adapter is building access chains left to right.
1968 // Set up the access chain to the left.
1969 node->getLeft()->traverse(this);
1970
1971 // save it so that computing the right side doesn't trash it
1972 spv::Builder::AccessChain partial = builder.getAccessChain();
1973
1974 // compute the next index in the chain
1975 builder.clearAccessChain();
1976 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001977 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001978
John Kessenich5611c6d2018-04-05 11:25:02 -06001979 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1980
John Kessenich140f3df2015-06-26 16:58:36 -06001981 // restore the saved access chain
1982 builder.setAccessChain(partial);
1983
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001984 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1985 int dummySize;
1986 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1987 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001988 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1989 dummySize));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001990 } else
John Kessenich8985fc92020-03-03 10:25:07 -07001991 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()),
1992 node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001993 }
1994 return false;
1995 case glslang::EOpVectorSwizzle:
1996 {
1997 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001998 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001999 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002000 int dummySize;
2001 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
2002 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07002003 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
2004 dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06002005 }
2006 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07002007 case glslang::EOpMatrixSwizzle:
2008 logger->missingFunctionality("matrix swizzle");
2009 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06002010 case glslang::EOpLogicalOr:
2011 case glslang::EOpLogicalAnd:
2012 {
2013
2014 // These may require short circuiting, but can sometimes be done as straight
2015 // binary operations. The right operand must be short circuited if it has
2016 // side effects, and should probably be if it is complex.
2017 if (isTrivial(node->getRight()->getAsTyped()))
2018 break; // handle below as a normal binary operation
2019 // otherwise, we need to do dynamic short circuiting on the right operand
John Kessenich8985fc92020-03-03 10:25:07 -07002020 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(),
2021 *node->getRight()->getAsTyped());
John Kessenich7c1aa102015-10-15 13:29:11 -06002022 builder.clearAccessChain();
2023 builder.setAccessChainRValue(result);
2024 }
2025 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06002026 default:
2027 break;
2028 }
2029
2030 // Assume generic binary op...
2031
John Kessenich32cfd492016-02-02 12:37:46 -07002032 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06002033 builder.clearAccessChain();
2034 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002035 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002036
John Kessenich32cfd492016-02-02 12:37:46 -07002037 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06002038 builder.clearAccessChain();
2039 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002040 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002041
John Kessenich32cfd492016-02-02 12:37:46 -07002042 // get result
John Kessenichead86222018-03-28 18:01:20 -06002043 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002044 TranslateNoContractionDecoration(node->getType().getQualifier()),
2045 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002046 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07002047 convertGlslangToSpvType(node->getType()), left, right,
2048 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002049
John Kessenich50e57562015-12-21 21:21:11 -07002050 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06002051 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002052 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07002053 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06002054 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06002055 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06002056 return false;
2057 }
John Kessenich140f3df2015-06-26 16:58:36 -06002058}
2059
John Kessenich9c14f772019-06-17 08:38:35 -06002060// Figure out what, if any, type changes are needed when accessing a specific built-in.
2061// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
2062// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
Daniel Kochdb32b242020-03-17 20:42:47 -04002063std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(glslang::TBuiltInVariable glslangBuiltIn,
John Kessenich9c14f772019-06-17 08:38:35 -06002064 const glslang::TType& glslangType)
2065{
Daniel Kochdb32b242020-03-17 20:42:47 -04002066 switch(glslangBuiltIn)
John Kessenich9c14f772019-06-17 08:38:35 -06002067 {
Daniel Kochdb32b242020-03-17 20:42:47 -04002068 case glslang::EbvSubGroupEqMask:
2069 case glslang::EbvSubGroupGeMask:
2070 case glslang::EbvSubGroupGtMask:
2071 case glslang::EbvSubGroupLeMask:
2072 case glslang::EbvSubGroupLtMask: {
John Kessenich9c14f772019-06-17 08:38:35 -06002073 // these require changing a 64-bit scaler -> a vector of 32-bit components
2074 if (glslangType.isVector())
2075 break;
2076 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
2077 builder.makeUintType(64));
2078 return ret;
2079 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002080 // There are no SPIR-V builtins defined for these and map onto original non-transposed
2081 // builtins. During visitBinary we insert a transpose
2082 case glslang::EbvWorldToObject3x4:
2083 case glslang::EbvObjectToWorld3x4: {
John Kessenichf80ef742020-07-14 01:44:35 -06002084 spv::Id mat43 = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
2085 spv::Id mat34 = builder.makeMatrixType(builder.makeFloatType(32), 3, 4);
2086 std::pair<spv::Id, spv::Id> ret(mat43, mat34);
Daniel Kochdb32b242020-03-17 20:42:47 -04002087 return ret;
2088 }
John Kessenich9c14f772019-06-17 08:38:35 -06002089 default:
2090 break;
2091 }
2092
2093 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2094 return ret;
2095}
2096
2097// For an object previously identified (see getForcedType() and forceType)
2098// as needing type translations, do the translation needed for a load, turning
2099// an L-value into in R-value.
2100spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2101{
2102 const auto forceIt = forceType.find(object);
2103 if (forceIt == forceType.end())
2104 return object;
2105
2106 spv::Id desiredTypeId = forceIt->second;
2107 spv::Id objectTypeId = builder.getTypeId(object);
2108 assert(builder.isPointerType(objectTypeId));
2109 objectTypeId = builder.getContainedTypeId(objectTypeId);
2110 if (builder.isVectorType(objectTypeId) &&
2111 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2112 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2113 // handle 32-bit v.xy* -> 64-bit
2114 builder.clearAccessChain();
2115 builder.setAccessChainLValue(object);
2116 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2117 std::vector<spv::Id> components;
2118 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2119 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2120
2121 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2122 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2123 builder.createCompositeConstruct(vecType, components));
2124 } else {
2125 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2126 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002127 } else if (builder.isMatrixType(objectTypeId)) {
2128 // There are no SPIR-V builtins defined for 3x4 variants of ObjectToWorld/WorldToObject
2129 // and we insert a transpose after loading the original non-transposed builtins
2130 builder.clearAccessChain();
2131 builder.setAccessChainLValue(object);
2132 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2133 return builder.createUnaryOp(spv::OpTranspose, desiredTypeId, object);
2134
2135 } else {
John Kessenich9c14f772019-06-17 08:38:35 -06002136 logger->missingFunctionality("forcing non 32-bit vector type");
2137 }
2138
2139 return object;
2140}
2141
John Kessenich140f3df2015-06-26 16:58:36 -06002142bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2143{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002144 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002145
qining40887662016-04-03 22:20:42 -04002146 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2147 if (node->getType().getQualifier().isSpecConstant())
2148 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2149
John Kessenichfc51d282015-08-19 13:34:18 -06002150 spv::Id result = spv::NoResult;
2151
2152 // try texturing first
2153 result = createImageTextureFunctionCall(node);
2154 if (result != spv::NoResult) {
2155 builder.clearAccessChain();
2156 builder.setAccessChainRValue(result);
2157
2158 return false; // done with this node
2159 }
2160
2161 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002162
2163 if (node->getOp() == glslang::EOpArrayLength) {
2164 // Quite special; won't want to evaluate the operand.
2165
John Kessenich5611c6d2018-04-05 11:25:02 -06002166 // Currently, the front-end does not allow .length() on an array until it is sized,
2167 // except for the last block membeor of an SSBO.
2168 // TODO: If this changes, link-time sized arrays might show up here, and need their
2169 // size extracted.
2170
John Kessenichc9a80832015-09-12 12:17:44 -06002171 // Normal .length() would have been constant folded by the front-end.
2172 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002173 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002174
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002175 spv::Id length;
2176 if (node->getOperand()->getType().isCoopMat()) {
2177 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2178
2179 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2180 assert(builder.isCooperativeMatrixType(typeId));
2181
2182 length = builder.createCooperativeMatrixLength(typeId);
2183 } else {
2184 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2185 block->traverse(this);
John Kessenich8985fc92020-03-03 10:25:07 -07002186 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()
2187 ->getConstArray()[0].getUConst();
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002188 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2189 }
John Kessenichc9a80832015-09-12 12:17:44 -06002190
John Kessenich8c869672018-11-28 07:01:37 -07002191 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2192 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2193 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002194 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2195 if (builder.isInSpecConstCodeGenMode()) {
2196 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2197 } else {
2198 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2199 }
2200 }
John Kessenich8c869672018-11-28 07:01:37 -07002201
John Kessenichc9a80832015-09-12 12:17:44 -06002202 builder.clearAccessChain();
2203 builder.setAccessChainRValue(length);
2204
2205 return false;
2206 }
2207
John Kessenichfc51d282015-08-19 13:34:18 -06002208 // Start by evaluating the operand
2209
John Kessenich8c8505c2016-07-26 12:50:38 -06002210 // Does it need a swizzle inversion? If so, evaluation is inverted;
2211 // operate first on the swizzle base, then apply the swizzle.
2212 spv::Id invertedType = spv::NoType;
John Kessenich8985fc92020-03-03 10:25:07 -07002213 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2214 invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenich8c8505c2016-07-26 12:50:38 -06002215 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2216 invertedType = getInvertedSwizzleType(*node->getOperand());
2217
John Kessenich140f3df2015-06-26 16:58:36 -06002218 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002219 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002220 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002221 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002222 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002223 operandNode = node->getOperand();
2224
2225 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002226
Rex Xufc618912015-09-09 16:42:49 +08002227 spv::Id operand = spv::NoResult;
2228
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002229 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2230
John Kessenichfb4f2332019-08-09 03:49:15 -06002231#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002232 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2233 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002234 node->getOp() == glslang::EOpAtomicCounter ||
Neslisah Torosdagli7d37a682020-03-26 10:52:33 -04002235 node->getOp() == glslang::EOpInterpolateAtCentroid ||
2236 node->getOp() == glslang::EOpRayQueryProceed ||
2237 node->getOp() == glslang::EOpRayQueryGetRayTMin ||
2238 node->getOp() == glslang::EOpRayQueryGetRayFlags ||
2239 node->getOp() == glslang::EOpRayQueryGetWorldRayOrigin ||
2240 node->getOp() == glslang::EOpRayQueryGetWorldRayDirection ||
2241 node->getOp() == glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque ||
2242 node->getOp() == glslang::EOpRayQueryTerminate ||
2243 node->getOp() == glslang::EOpRayQueryConfirmIntersection) {
Rex Xufc618912015-09-09 16:42:49 +08002244 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002245 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2246 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2247 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002248#endif
2249 {
John Kessenich32cfd492016-02-02 12:37:46 -07002250 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002251 }
John Kessenich140f3df2015-06-26 16:58:36 -06002252
John Kessenichead86222018-03-28 18:01:20 -06002253 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002254 TranslateNoContractionDecoration(node->getType().getQualifier()),
2255 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002256
2257 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002258 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002259 result = createConversion(node->getOp(), decorations, resultType(), operand,
2260 node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002261
2262 // if not, then possibly an operation
2263 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002264 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand,
2265 node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002266
2267 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002268 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002269 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002270 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002271 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002272
John Kessenich140f3df2015-06-26 16:58:36 -06002273 builder.clearAccessChain();
2274 builder.setAccessChainRValue(result);
2275
2276 return false; // done with this node
2277 }
2278
2279 // it must be a special case, check...
2280 switch (node->getOp()) {
2281 case glslang::EOpPostIncrement:
2282 case glslang::EOpPostDecrement:
2283 case glslang::EOpPreIncrement:
2284 case glslang::EOpPreDecrement:
2285 {
2286 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002287 spv::Id one = 0;
2288 if (node->getBasicType() == glslang::EbtFloat)
2289 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002290#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002291 else if (node->getBasicType() == glslang::EbtDouble)
2292 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002293 else if (node->getBasicType() == glslang::EbtFloat16)
2294 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002295 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2296 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002297 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2298 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002299 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2300 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002301#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002302 else
2303 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002304 glslang::TOperator op;
2305 if (node->getOp() == glslang::EOpPreIncrement ||
2306 node->getOp() == glslang::EOpPostIncrement)
2307 op = glslang::EOpAdd;
2308 else
2309 op = glslang::EOpSub;
2310
John Kessenichead86222018-03-28 18:01:20 -06002311 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002312 convertGlslangToSpvType(node->getType()), operand, one,
2313 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002314 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002315
2316 // The result of operation is always stored, but conditionally the
2317 // consumed result. The consumed result is always an r-value.
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02002318 builder.accessChainStore(result,
2319 TranslateNonUniformDecoration(node->getOperand()->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06002320 builder.clearAccessChain();
2321 if (node->getOp() == glslang::EOpPreIncrement ||
2322 node->getOp() == glslang::EOpPreDecrement)
2323 builder.setAccessChainRValue(result);
2324 else
2325 builder.setAccessChainRValue(operand);
2326 }
2327
2328 return false;
2329
John Kessenich155d3512019-08-08 23:29:20 -06002330#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002331 case glslang::EOpEmitStreamVertex:
2332 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2333 return false;
2334 case glslang::EOpEndStreamPrimitive:
2335 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2336 return false;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002337 case glslang::EOpRayQueryTerminate:
2338 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operand);
2339 return false;
2340 case glslang::EOpRayQueryConfirmIntersection:
2341 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operand);
2342 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002343#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002344
2345 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002346 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002347 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002348 }
John Kessenich140f3df2015-06-26 16:58:36 -06002349}
2350
Jeff Bolz53134492019-06-25 13:31:10 -05002351// Construct a composite object, recursively copying members if their types don't match
2352spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2353{
2354 for (int c = 0; c < (int)constituents.size(); ++c) {
2355 spv::Id& constituent = constituents[c];
2356 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2357 spv::Id rType = builder.getTypeId(constituent);
2358 if (lType != rType) {
2359 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2360 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2361 } else if (builder.isStructType(rType)) {
2362 std::vector<spv::Id> rTypeConstituents;
2363 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2364 for (int i = 0; i < numrTypeConstituents; ++i) {
John Kessenich8985fc92020-03-03 10:25:07 -07002365 rTypeConstituents.push_back(builder.createCompositeExtract(constituent,
2366 builder.getContainedTypeId(rType, i), i));
Jeff Bolz53134492019-06-25 13:31:10 -05002367 }
2368 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2369 } else {
2370 assert(builder.isArrayType(rType));
2371 std::vector<spv::Id> rTypeConstituents;
2372 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2373
2374 spv::Id elementRType = builder.getContainedTypeId(rType);
2375 for (int i = 0; i < numrTypeConstituents; ++i) {
2376 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2377 }
2378 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2379 }
2380 }
2381 }
2382 return builder.createCompositeConstruct(resultTypeId, constituents);
2383}
2384
John Kessenich140f3df2015-06-26 16:58:36 -06002385bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2386{
qining27e04a02016-04-14 16:40:20 -04002387 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2388 if (node->getType().getQualifier().isSpecConstant())
2389 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2390
John Kessenichfc51d282015-08-19 13:34:18 -06002391 spv::Id result = spv::NoResult;
Cody Northrop4d2298b2020-04-13 21:59:49 -06002392 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2393 std::vector<spv::Builder::AccessChain> complexLvalues; // for holding swizzling l-values too complex for
2394 // SPIR-V, for an out parameter
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02002395 std::vector<glslang::TQualifier> complexLValueQualifiers;
Cody Northrop4d2298b2020-04-13 21:59:49 -06002396 std::vector<spv::Id> temporaryLvalues; // temporaries to pass, as proxies for complexLValues
John Kessenichbbbd9a22020-03-03 07:21:37 -07002397
John Kessenich8985fc92020-03-03 10:25:07 -07002398 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2399 invertedType :
2400 convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002401
2402 // try texturing
2403 result = createImageTextureFunctionCall(node);
2404 if (result != spv::NoResult) {
2405 builder.clearAccessChain();
2406 builder.setAccessChainRValue(result);
2407
2408 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002409 }
2410#ifndef GLSLANG_WEB
2411 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002412 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002413 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002414 // "imageStore" is a special case, which has no result
2415 return false;
2416 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002417#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002418
John Kessenich140f3df2015-06-26 16:58:36 -06002419 glslang::TOperator binOp = glslang::EOpNull;
2420 bool reduceComparison = true;
2421 bool isMatrix = false;
2422 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002423 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002424
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002425 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2426
John Kessenich140f3df2015-06-26 16:58:36 -06002427 assert(node->getOp());
2428
John Kessenichf6640762016-08-01 19:44:00 -06002429 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002430
2431 switch (node->getOp()) {
2432 case glslang::EOpSequence:
2433 {
2434 if (preVisit)
2435 ++sequenceDepth;
2436 else
2437 --sequenceDepth;
2438
2439 if (sequenceDepth == 1) {
2440 // If this is the parent node of all the functions, we want to see them
2441 // early, so all call points have actual SPIR-V functions to reference.
2442 // In all cases, still let the traverser visit the children for us.
2443 makeFunctions(node->getAsAggregate()->getSequence());
2444
John Kessenich6fccb3c2016-09-19 16:01:41 -06002445 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002446 // anything else gets there, so visit out of order, doing them all now.
2447 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2448
John Kessenich6a60c2f2016-12-08 21:01:59 -07002449 // 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 -06002450 // so do them manually.
2451 visitFunctions(node->getAsAggregate()->getSequence());
2452
2453 return false;
2454 }
2455
2456 return true;
2457 }
2458 case glslang::EOpLinkerObjects:
2459 {
2460 if (visit == glslang::EvPreVisit)
2461 linkageOnly = true;
2462 else
2463 linkageOnly = false;
2464
2465 return true;
2466 }
2467 case glslang::EOpComma:
2468 {
2469 // processing from left to right naturally leaves the right-most
2470 // lying around in the access chain
2471 glslang::TIntermSequence& glslangOperands = node->getSequence();
2472 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2473 glslangOperands[i]->traverse(this);
2474
2475 return false;
2476 }
2477 case glslang::EOpFunction:
2478 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002479 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002480 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002481 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002482 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002483 } else {
2484 handleFunctionEntry(node);
2485 }
2486 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002487 if (inEntryPoint)
2488 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002489 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002490 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002491 }
2492
2493 return true;
2494 case glslang::EOpParameters:
2495 // Parameters will have been consumed by EOpFunction processing, but not
2496 // the body, so we still visited the function node's children, making this
2497 // child redundant.
2498 return false;
2499 case glslang::EOpFunctionCall:
2500 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002501 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002502 if (node->isUserDefined())
2503 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07002504 if (result) {
2505 builder.clearAccessChain();
2506 builder.setAccessChainRValue(result);
2507 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002508 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002509
2510 return false;
2511 }
2512 case glslang::EOpConstructMat2x2:
2513 case glslang::EOpConstructMat2x3:
2514 case glslang::EOpConstructMat2x4:
2515 case glslang::EOpConstructMat3x2:
2516 case glslang::EOpConstructMat3x3:
2517 case glslang::EOpConstructMat3x4:
2518 case glslang::EOpConstructMat4x2:
2519 case glslang::EOpConstructMat4x3:
2520 case glslang::EOpConstructMat4x4:
2521 case glslang::EOpConstructDMat2x2:
2522 case glslang::EOpConstructDMat2x3:
2523 case glslang::EOpConstructDMat2x4:
2524 case glslang::EOpConstructDMat3x2:
2525 case glslang::EOpConstructDMat3x3:
2526 case glslang::EOpConstructDMat3x4:
2527 case glslang::EOpConstructDMat4x2:
2528 case glslang::EOpConstructDMat4x3:
2529 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002530 case glslang::EOpConstructIMat2x2:
2531 case glslang::EOpConstructIMat2x3:
2532 case glslang::EOpConstructIMat2x4:
2533 case glslang::EOpConstructIMat3x2:
2534 case glslang::EOpConstructIMat3x3:
2535 case glslang::EOpConstructIMat3x4:
2536 case glslang::EOpConstructIMat4x2:
2537 case glslang::EOpConstructIMat4x3:
2538 case glslang::EOpConstructIMat4x4:
2539 case glslang::EOpConstructUMat2x2:
2540 case glslang::EOpConstructUMat2x3:
2541 case glslang::EOpConstructUMat2x4:
2542 case glslang::EOpConstructUMat3x2:
2543 case glslang::EOpConstructUMat3x3:
2544 case glslang::EOpConstructUMat3x4:
2545 case glslang::EOpConstructUMat4x2:
2546 case glslang::EOpConstructUMat4x3:
2547 case glslang::EOpConstructUMat4x4:
2548 case glslang::EOpConstructBMat2x2:
2549 case glslang::EOpConstructBMat2x3:
2550 case glslang::EOpConstructBMat2x4:
2551 case glslang::EOpConstructBMat3x2:
2552 case glslang::EOpConstructBMat3x3:
2553 case glslang::EOpConstructBMat3x4:
2554 case glslang::EOpConstructBMat4x2:
2555 case glslang::EOpConstructBMat4x3:
2556 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002557 case glslang::EOpConstructF16Mat2x2:
2558 case glslang::EOpConstructF16Mat2x3:
2559 case glslang::EOpConstructF16Mat2x4:
2560 case glslang::EOpConstructF16Mat3x2:
2561 case glslang::EOpConstructF16Mat3x3:
2562 case glslang::EOpConstructF16Mat3x4:
2563 case glslang::EOpConstructF16Mat4x2:
2564 case glslang::EOpConstructF16Mat4x3:
2565 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002566 isMatrix = true;
2567 // fall through
2568 case glslang::EOpConstructFloat:
2569 case glslang::EOpConstructVec2:
2570 case glslang::EOpConstructVec3:
2571 case glslang::EOpConstructVec4:
2572 case glslang::EOpConstructDouble:
2573 case glslang::EOpConstructDVec2:
2574 case glslang::EOpConstructDVec3:
2575 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002576 case glslang::EOpConstructFloat16:
2577 case glslang::EOpConstructF16Vec2:
2578 case glslang::EOpConstructF16Vec3:
2579 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002580 case glslang::EOpConstructBool:
2581 case glslang::EOpConstructBVec2:
2582 case glslang::EOpConstructBVec3:
2583 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002584 case glslang::EOpConstructInt8:
2585 case glslang::EOpConstructI8Vec2:
2586 case glslang::EOpConstructI8Vec3:
2587 case glslang::EOpConstructI8Vec4:
2588 case glslang::EOpConstructUint8:
2589 case glslang::EOpConstructU8Vec2:
2590 case glslang::EOpConstructU8Vec3:
2591 case glslang::EOpConstructU8Vec4:
2592 case glslang::EOpConstructInt16:
2593 case glslang::EOpConstructI16Vec2:
2594 case glslang::EOpConstructI16Vec3:
2595 case glslang::EOpConstructI16Vec4:
2596 case glslang::EOpConstructUint16:
2597 case glslang::EOpConstructU16Vec2:
2598 case glslang::EOpConstructU16Vec3:
2599 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002600 case glslang::EOpConstructInt:
2601 case glslang::EOpConstructIVec2:
2602 case glslang::EOpConstructIVec3:
2603 case glslang::EOpConstructIVec4:
2604 case glslang::EOpConstructUint:
2605 case glslang::EOpConstructUVec2:
2606 case glslang::EOpConstructUVec3:
2607 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002608 case glslang::EOpConstructInt64:
2609 case glslang::EOpConstructI64Vec2:
2610 case glslang::EOpConstructI64Vec3:
2611 case glslang::EOpConstructI64Vec4:
2612 case glslang::EOpConstructUint64:
2613 case glslang::EOpConstructU64Vec2:
2614 case glslang::EOpConstructU64Vec3:
2615 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002616 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002617 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002618 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002619 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002620 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002621 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002622 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002623 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002624 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002625 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002626 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002627 else if (node->getOp() == glslang::EOpConstructStruct ||
2628 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2629 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002630 std::vector<spv::Id> constituents;
2631 for (int c = 0; c < (int)arguments.size(); ++c)
2632 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002633 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002634 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002635 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002636 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002637 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002638
Bas Nieuwenhuizenc9ffeec2020-09-03 03:09:39 +02002639 if (node->getType().getQualifier().isNonUniform()) {
2640 builder.addDecoration(constructed, spv::DecorationNonUniformEXT);
2641 }
2642
John Kessenich140f3df2015-06-26 16:58:36 -06002643 builder.clearAccessChain();
2644 builder.setAccessChainRValue(constructed);
2645
2646 return false;
2647 }
2648
2649 // These six are component-wise compares with component-wise results.
2650 // Forward on to createBinaryOperation(), requesting a vector result.
2651 case glslang::EOpLessThan:
2652 case glslang::EOpGreaterThan:
2653 case glslang::EOpLessThanEqual:
2654 case glslang::EOpGreaterThanEqual:
2655 case glslang::EOpVectorEqual:
2656 case glslang::EOpVectorNotEqual:
2657 {
2658 // Map the operation to a binary
2659 binOp = node->getOp();
2660 reduceComparison = false;
2661 switch (node->getOp()) {
2662 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2663 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2664 default: binOp = node->getOp(); break;
2665 }
2666
2667 break;
2668 }
2669 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002670 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002671 binOp = glslang::EOpMul;
2672 break;
2673 case glslang::EOpOuterProduct:
2674 // two vectors multiplied to make a matrix
2675 binOp = glslang::EOpOuterProduct;
2676 break;
2677 case glslang::EOpDot:
2678 {
qining25262b32016-05-06 17:25:16 -04002679 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002680 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002681 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002682 binOp = glslang::EOpMul;
2683 break;
2684 }
2685 case glslang::EOpMod:
2686 // when an aggregate, this is the floating-point mod built-in function,
2687 // which can be emitted by the one in createBinaryOperation()
2688 binOp = glslang::EOpMod;
2689 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002690
John Kessenich140f3df2015-06-26 16:58:36 -06002691 case glslang::EOpEmitVertex:
2692 case glslang::EOpEndPrimitive:
2693 case glslang::EOpBarrier:
2694 case glslang::EOpMemoryBarrier:
2695 case glslang::EOpMemoryBarrierAtomicCounter:
2696 case glslang::EOpMemoryBarrierBuffer:
2697 case glslang::EOpMemoryBarrierImage:
2698 case glslang::EOpMemoryBarrierShared:
2699 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002700 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002701 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002702 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002703 case glslang::EOpWorkgroupMemoryBarrier:
2704 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002705 case glslang::EOpSubgroupBarrier:
2706 case glslang::EOpSubgroupMemoryBarrier:
2707 case glslang::EOpSubgroupMemoryBarrierBuffer:
2708 case glslang::EOpSubgroupMemoryBarrierImage:
2709 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002710 noReturnValue = true;
2711 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2712 break;
2713
John Kessenich426394d2015-07-23 10:22:48 -06002714 case glslang::EOpAtomicAdd:
2715 case glslang::EOpAtomicMin:
2716 case glslang::EOpAtomicMax:
2717 case glslang::EOpAtomicAnd:
2718 case glslang::EOpAtomicOr:
2719 case glslang::EOpAtomicXor:
2720 case glslang::EOpAtomicExchange:
2721 case glslang::EOpAtomicCompSwap:
2722 atomic = true;
2723 break;
2724
John Kesseniche5eee8f2019-10-18 01:03:11 -06002725#ifndef GLSLANG_WEB
2726 case glslang::EOpAtomicStore:
2727 noReturnValue = true;
2728 // fallthrough
2729 case glslang::EOpAtomicLoad:
2730 atomic = true;
2731 break;
2732
John Kessenich0d0c6d32017-07-23 16:08:26 -06002733 case glslang::EOpAtomicCounterAdd:
2734 case glslang::EOpAtomicCounterSubtract:
2735 case glslang::EOpAtomicCounterMin:
2736 case glslang::EOpAtomicCounterMax:
2737 case glslang::EOpAtomicCounterAnd:
2738 case glslang::EOpAtomicCounterOr:
2739 case glslang::EOpAtomicCounterXor:
2740 case glslang::EOpAtomicCounterExchange:
2741 case glslang::EOpAtomicCounterCompSwap:
2742 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2743 builder.addCapability(spv::CapabilityAtomicStorageOps);
2744 atomic = true;
2745 break;
2746
Ian Romanickb3bd4022019-01-21 08:57:25 -08002747 case glslang::EOpAbsDifference:
2748 case glslang::EOpAddSaturate:
2749 case glslang::EOpSubSaturate:
2750 case glslang::EOpAverage:
2751 case glslang::EOpAverageRounded:
2752 case glslang::EOpMul32x16:
2753 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2754 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2755 binOp = node->getOp();
2756 break;
2757
Daniel Kochdb32b242020-03-17 20:42:47 -04002758 case glslang::EOpIgnoreIntersection:
2759 case glslang::EOpTerminateRay:
2760 case glslang::EOpTrace:
2761 case glslang::EOpExecuteCallable:
Chao Chen3c366992018-09-19 11:41:59 -07002762 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2763 noReturnValue = true;
2764 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04002765 case glslang::EOpRayQueryInitialize:
2766 case glslang::EOpRayQueryTerminate:
2767 case glslang::EOpRayQueryGenerateIntersection:
2768 case glslang::EOpRayQueryConfirmIntersection:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002769 builder.addExtension("SPV_KHR_ray_query");
2770 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
Torosdagli06c2eee2020-03-19 11:09:57 -04002771 noReturnValue = true;
2772 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002773 case glslang::EOpRayQueryProceed:
2774 case glslang::EOpRayQueryGetIntersectionType:
2775 case glslang::EOpRayQueryGetRayTMin:
2776 case glslang::EOpRayQueryGetRayFlags:
2777 case glslang::EOpRayQueryGetIntersectionT:
2778 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2779 case glslang::EOpRayQueryGetIntersectionInstanceId:
2780 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2781 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2782 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2783 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2784 case glslang::EOpRayQueryGetIntersectionFrontFace:
2785 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
2786 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2787 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2788 case glslang::EOpRayQueryGetWorldRayDirection:
2789 case glslang::EOpRayQueryGetWorldRayOrigin:
2790 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2791 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2792 builder.addExtension("SPV_KHR_ray_query");
2793 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
2794 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002795 case glslang::EOpCooperativeMatrixLoad:
2796 case glslang::EOpCooperativeMatrixStore:
2797 noReturnValue = true;
2798 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002799 case glslang::EOpBeginInvocationInterlock:
2800 case glslang::EOpEndInvocationInterlock:
2801 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2802 noReturnValue = true;
2803 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002804#endif
Chao Chen3c366992018-09-19 11:41:59 -07002805
Jeff Bolz04d73732019-05-31 13:06:01 -05002806 case glslang::EOpDebugPrintf:
2807 noReturnValue = true;
2808 break;
2809
John Kessenich140f3df2015-06-26 16:58:36 -06002810 default:
2811 break;
2812 }
2813
2814 //
2815 // See if it maps to a regular operation.
2816 //
John Kessenich140f3df2015-06-26 16:58:36 -06002817 if (binOp != glslang::EOpNull) {
2818 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2819 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2820 assert(left && right);
2821
2822 builder.clearAccessChain();
2823 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002824 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002825
2826 builder.clearAccessChain();
2827 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002828 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002829
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002830 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002831 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002832 TranslateNoContractionDecoration(node->getType().getQualifier()),
2833 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002834 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002835 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002836 left->getType().getBasicType(), reduceComparison);
2837
2838 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002839 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002840 builder.clearAccessChain();
2841 builder.setAccessChainRValue(result);
2842
2843 return false;
2844 }
2845
John Kessenich426394d2015-07-23 10:22:48 -06002846 //
2847 // Create the list of operands.
2848 //
John Kessenich140f3df2015-06-26 16:58:36 -06002849 glslang::TIntermSequence& glslangOperands = node->getSequence();
2850 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002851 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002852 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002853 // special case l-value operands; there are just a few
2854 bool lvalue = false;
2855 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002856 case glslang::EOpModf:
2857 if (arg == 1)
2858 lvalue = true;
2859 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002860
Torosdagli06c2eee2020-03-19 11:09:57 -04002861 case glslang::EOpRayQueryInitialize:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002862 case glslang::EOpRayQueryTerminate:
2863 case glslang::EOpRayQueryConfirmIntersection:
2864 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04002865 case glslang::EOpRayQueryGenerateIntersection:
2866 case glslang::EOpRayQueryGetIntersectionType:
2867 case glslang::EOpRayQueryGetIntersectionT:
2868 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2869 case glslang::EOpRayQueryGetIntersectionInstanceId:
2870 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2871 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2872 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2873 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2874 case glslang::EOpRayQueryGetIntersectionFrontFace:
2875 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2876 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2877 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2878 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2879 if (arg == 0)
2880 lvalue = true;
2881 break;
2882
John Kesseniche5eee8f2019-10-18 01:03:11 -06002883 case glslang::EOpAtomicAdd:
2884 case glslang::EOpAtomicMin:
2885 case glslang::EOpAtomicMax:
2886 case glslang::EOpAtomicAnd:
2887 case glslang::EOpAtomicOr:
2888 case glslang::EOpAtomicXor:
2889 case glslang::EOpAtomicExchange:
2890 case glslang::EOpAtomicCompSwap:
2891 if (arg == 0)
2892 lvalue = true;
2893 break;
2894
John Kessenicha28f7a72019-08-06 07:00:58 -06002895#ifndef GLSLANG_WEB
2896 case glslang::EOpFrexp:
2897 if (arg == 1)
2898 lvalue = true;
2899 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002900 case glslang::EOpInterpolateAtSample:
2901 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002902 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002903 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002904 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002905
2906 // Does it need a swizzle inversion? If so, evaluation is inverted;
2907 // operate first on the swizzle base, then apply the swizzle.
John Kessenichbbbd9a22020-03-03 07:21:37 -07002908 // That is, we transform
2909 //
2910 // interpolate(v.zy) -> interpolate(v).zy
2911 //
John Kessenichecba76f2017-01-06 00:34:48 -07002912 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002913 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
John Kessenich8985fc92020-03-03 10:25:07 -07002914 invertedType = convertGlslangToSpvType(
2915 glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
John Kessenich8c8505c2016-07-26 12:50:38 -06002916 }
Rex Xu7a26c172015-12-08 17:12:09 +08002917 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002918 case glslang::EOpAtomicLoad:
2919 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002920 case glslang::EOpAtomicCounterAdd:
2921 case glslang::EOpAtomicCounterSubtract:
2922 case glslang::EOpAtomicCounterMin:
2923 case glslang::EOpAtomicCounterMax:
2924 case glslang::EOpAtomicCounterAnd:
2925 case glslang::EOpAtomicCounterOr:
2926 case glslang::EOpAtomicCounterXor:
2927 case glslang::EOpAtomicCounterExchange:
2928 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002929 if (arg == 0)
2930 lvalue = true;
2931 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002932 case glslang::EOpAddCarry:
2933 case glslang::EOpSubBorrow:
2934 if (arg == 2)
2935 lvalue = true;
2936 break;
2937 case glslang::EOpUMulExtended:
2938 case glslang::EOpIMulExtended:
2939 if (arg >= 2)
2940 lvalue = true;
2941 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002942 case glslang::EOpCooperativeMatrixLoad:
2943 if (arg == 0 || arg == 1)
2944 lvalue = true;
2945 break;
2946 case glslang::EOpCooperativeMatrixStore:
2947 if (arg == 1)
2948 lvalue = true;
2949 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002950#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002951 default:
2952 break;
2953 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002954 builder.clearAccessChain();
2955 if (invertedType != spv::NoType && arg == 0)
2956 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2957 else
2958 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002959
John Kessenichb9197c82019-08-11 07:41:45 -06002960#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002961 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2962 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2963
2964 if (arg == 1) {
2965 // fold "element" parameter into the access chain
2966 spv::Builder::AccessChain save = builder.getAccessChain();
2967 builder.clearAccessChain();
2968 glslangOperands[2]->traverse(this);
2969
2970 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2971
2972 builder.setAccessChain(save);
2973
2974 // Point to the first element of the array.
John Kessenich8985fc92020-03-03 10:25:07 -07002975 builder.accessChainPush(elementId,
2976 TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
2977 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002978
2979 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2980 unsigned int alignment = builder.getAccessChain().alignment;
2981
2982 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2983 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2984 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2985 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2986 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
John Kessenich8985fc92020-03-03 10:25:07 -07002987 if (builder.getStorageClass(builder.getAccessChain().base) ==
2988 spv::StorageClassPhysicalStorageBufferEXT) {
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002989 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2990 }
2991
2992 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2993
2994 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2995 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2996 }
2997
John Kessenich8985fc92020-03-03 10:25:07 -07002998 if (memoryAccess &
2999 (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
3000 memoryAccessOperands.push_back(spv::IdImmediate(true,
3001 builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003002 }
3003 } else if (arg == 2) {
3004 continue;
3005 }
3006 }
John Kessenichb9197c82019-08-11 07:41:45 -06003007#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003008
John Kessenichbbbd9a22020-03-03 07:21:37 -07003009 // for l-values, pass the address, for r-values, pass the value
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003010 if (lvalue) {
John Kessenichbbbd9a22020-03-03 07:21:37 -07003011 if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
3012 // SPIR-V cannot represent an l-value containing a swizzle that doesn't
3013 // reduce to a simple access chain. So, we need a temporary vector to
3014 // receive the result, and must later swizzle that into the original
3015 // l-value.
Cody Northrop4d2298b2020-04-13 21:59:49 -06003016 complexLvalues.push_back(builder.getAccessChain());
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02003017 complexLValueQualifiers.push_back(glslangOperands[arg]->getAsTyped()->getType().getQualifier());
John Kessenich435dd802020-06-30 01:27:08 -06003018 temporaryLvalues.push_back(builder.createVariable(
3019 spv::NoPrecision, spv::StorageClassFunction,
Cody Northrop4d2298b2020-04-13 21:59:49 -06003020 builder.accessChainGetInferredType(), "swizzleTemp"));
3021 operands.push_back(temporaryLvalues.back());
John Kessenichbbbd9a22020-03-03 07:21:37 -07003022 } else {
3023 operands.push_back(builder.accessChainGetLValue());
3024 }
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003025 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
3026 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
3027 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003028 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Torosdagli06c2eee2020-03-19 11:09:57 -04003029 glslang::TOperator glslangOp = node->getOp();
3030 if (arg == 1 &&
3031 (glslangOp == glslang::EOpRayQueryGetIntersectionType ||
3032 glslangOp == glslang::EOpRayQueryGetIntersectionT ||
3033 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceCustomIndex ||
3034 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceId ||
3035 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset ||
3036 glslangOp == glslang::EOpRayQueryGetIntersectionGeometryIndex ||
3037 glslangOp == glslang::EOpRayQueryGetIntersectionPrimitiveIndex ||
3038 glslangOp == glslang::EOpRayQueryGetIntersectionBarycentrics ||
3039 glslangOp == glslang::EOpRayQueryGetIntersectionFrontFace ||
3040 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayDirection ||
3041 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayOrigin ||
3042 glslangOp == glslang::EOpRayQueryGetIntersectionObjectToWorld ||
3043 glslangOp == glslang::EOpRayQueryGetIntersectionWorldToObject
3044 )) {
3045 bool cond = glslangOperands[arg]->getAsConstantUnion()->getConstArray()[0].getBConst();
3046 operands.push_back(builder.makeIntConstant(cond ? 1 : 0));
3047 }
3048 else {
3049 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
3050 }
3051
John Kesseniche485c7a2017-05-31 18:50:53 -06003052 }
John Kessenich140f3df2015-06-26 16:58:36 -06003053 }
John Kessenich426394d2015-07-23 10:22:48 -06003054
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003055 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06003056#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003057 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
3058 std::vector<spv::IdImmediate> idImmOps;
3059
3060 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3061 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3062 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3063 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3064 // get the pointee type
3065 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
3066 assert(builder.isCooperativeMatrixType(typeId));
3067 // do the op
3068 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
3069 // store the result to the pointer (out param 'm')
3070 builder.createStore(result, operands[0]);
3071 result = 0;
3072 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
3073 std::vector<spv::IdImmediate> idImmOps;
3074
3075 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3076 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
3077 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3078 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3079 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3080
3081 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
3082 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06003083 } else
3084#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06003085 if (atomic) {
3086 // Handle all atomics
John Kessenich8985fc92020-03-03 10:25:07 -07003087 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
3088 lvalueCoherentFlags);
Jeff Bolz04d73732019-05-31 13:06:01 -05003089 } else if (node->getOp() == glslang::EOpDebugPrintf) {
3090 if (!nonSemanticDebugPrintf) {
3091 nonSemanticDebugPrintf = builder.import("NonSemantic.DebugPrintf");
3092 }
3093 result = builder.createBuiltinCall(builder.makeVoidType(), nonSemanticDebugPrintf, spv::NonSemanticDebugPrintfDebugPrintf, operands);
3094 builder.addExtension(spv::E_SPV_KHR_non_semantic_info);
John Kesseniche5eee8f2019-10-18 01:03:11 -06003095 } else {
John Kessenich426394d2015-07-23 10:22:48 -06003096 // Pass through to generic operations.
3097 switch (glslangOperands.size()) {
3098 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06003099 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06003100 break;
3101 case 1:
John Kessenichead86222018-03-28 18:01:20 -06003102 {
3103 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06003104 TranslateNoContractionDecoration(node->getType().getQualifier()),
3105 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06003106 result = createUnaryOperation(
3107 node->getOp(), decorations,
3108 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003109 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06003110 }
John Kessenich426394d2015-07-23 10:22:48 -06003111 break;
3112 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06003113 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06003114 break;
3115 }
Cody Northrop4d2298b2020-04-13 21:59:49 -06003116
John Kessenichbbbd9a22020-03-03 07:21:37 -07003117 if (invertedType != spv::NoResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003118 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
Cody Northrop4d2298b2020-04-13 21:59:49 -06003119
3120 for (unsigned int i = 0; i < temporaryLvalues.size(); ++i) {
3121 builder.setAccessChain(complexLvalues[i]);
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02003122 builder.accessChainStore(builder.createLoad(temporaryLvalues[i], spv::NoPrecision), TranslateNonUniformDecoration(complexLValueQualifiers[i]));
John Kessenichbbbd9a22020-03-03 07:21:37 -07003123 }
John Kessenich140f3df2015-06-26 16:58:36 -06003124 }
3125
3126 if (noReturnValue)
3127 return false;
3128
3129 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04003130 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07003131 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06003132 } else {
3133 builder.clearAccessChain();
3134 builder.setAccessChainRValue(result);
3135 return false;
3136 }
3137}
3138
John Kessenich433e9ff2017-01-26 20:31:11 -07003139// This path handles both if-then-else and ?:
3140// The if-then-else has a node type of void, while
3141// ?: has either a void or a non-void node type
3142//
3143// Leaving the result, when not void:
3144// GLSL only has r-values as the result of a :?, but
3145// if we have an l-value, that can be more efficient if it will
3146// become the base of a complex r-value expression, because the
3147// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06003148bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
3149{
John Kessenich0c1e71a2019-01-10 18:23:06 +07003150 // see if OpSelect can handle it
3151 const auto isOpSelectable = [&]() {
3152 if (node->getBasicType() == glslang::EbtVoid)
3153 return false;
3154 // OpSelect can do all other types starting with SPV 1.4
3155 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
3156 // pre-1.4, only scalars and vectors can be handled
3157 if ((!node->getType().isScalar() && !node->getType().isVector()))
3158 return false;
3159 }
3160 return true;
3161 };
3162
John Kessenich4bee5312018-02-20 21:29:05 -07003163 // See if it simple and safe, or required, to execute both sides.
3164 // Crucially, side effects must be either semantically required or avoided,
3165 // and there are performance trade-offs.
3166 // Return true if required or a good idea (and safe) to execute both sides,
3167 // false otherwise.
3168 const auto bothSidesPolicy = [&]() -> bool {
3169 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07003170 if (node->getTrueBlock() == nullptr ||
3171 node->getFalseBlock() == nullptr)
3172 return false;
3173
John Kessenich4bee5312018-02-20 21:29:05 -07003174 // required? (unless we write additional code to look for side effects
3175 // and make performance trade-offs if none are present)
3176 if (!node->getShortCircuit())
3177 return true;
3178
3179 // if not required to execute both, decide based on performance/practicality...
3180
John Kessenich0c1e71a2019-01-10 18:23:06 +07003181 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07003182 return false;
3183
John Kessenich433e9ff2017-01-26 20:31:11 -07003184 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
3185 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
3186
3187 // return true if a single operand to ? : is okay for OpSelect
3188 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003189 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07003190 };
3191
3192 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
3193 operandOkay(node->getFalseBlock()->getAsTyped());
3194 };
3195
John Kessenich4bee5312018-02-20 21:29:05 -07003196 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
3197 // emit the condition before doing anything with selection
3198 node->getCondition()->traverse(this);
3199 spv::Id condition = accessChainLoad(node->getCondition()->getType());
3200
3201 // Find a way of executing both sides and selecting the right result.
3202 const auto executeBothSides = [&]() -> void {
3203 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07003204 node->getTrueBlock()->traverse(this);
3205 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3206 node->getFalseBlock()->traverse(this);
3207 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3208
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003209 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003210
John Kessenich4bee5312018-02-20 21:29:05 -07003211 // done if void
3212 if (node->getBasicType() == glslang::EbtVoid)
3213 return;
John Kesseniche434ad92017-03-30 10:09:28 -06003214
John Kessenich4bee5312018-02-20 21:29:05 -07003215 // emit code to select between trueValue and falseValue
3216
3217 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07003218 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07003219 // Emit OpSelect for this selection.
3220
3221 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07003222 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
3223 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07003224 condition = builder.smearScalar(spv::NoPrecision, condition,
3225 builder.makeVectorType(builder.makeBoolType(),
3226 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07003227 }
John Kessenich4bee5312018-02-20 21:29:05 -07003228
3229 // OpSelect
3230 result = builder.createTriOp(spv::OpSelect,
3231 convertGlslangToSpvType(node->getType()), condition,
3232 trueValue, falseValue);
3233
3234 builder.clearAccessChain();
3235 builder.setAccessChainRValue(result);
3236 } else {
3237 // We need control flow to select the result.
3238 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
John Kessenich435dd802020-06-30 01:27:08 -06003239 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()),
3240 spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich4bee5312018-02-20 21:29:05 -07003241
3242 // Selection control:
3243 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3244
3245 // make an "if" based on the value created by the condition
3246 spv::Builder::If ifBuilder(condition, control, builder);
3247
3248 // emit the "then" statement
3249 builder.createStore(trueValue, result);
3250 ifBuilder.makeBeginElse();
3251 // emit the "else" statement
3252 builder.createStore(falseValue, result);
3253
3254 // finish off the control flow
3255 ifBuilder.makeEndIf();
3256
3257 builder.clearAccessChain();
3258 builder.setAccessChainLValue(result);
3259 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003260 };
3261
John Kessenich4bee5312018-02-20 21:29:05 -07003262 // Execute the one side needed, as per the condition
3263 const auto executeOneSide = [&]() {
3264 // Always emit control flow.
John Kessenich435dd802020-06-30 01:27:08 -06003265 if (node->getBasicType() != glslang::EbtVoid) {
3266 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()), spv::StorageClassFunction,
3267 convertGlslangToSpvType(node->getType()));
3268 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003269
John Kessenich4bee5312018-02-20 21:29:05 -07003270 // Selection control:
3271 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3272
3273 // make an "if" based on the value created by the condition
3274 spv::Builder::If ifBuilder(condition, control, builder);
3275
3276 // emit the "then" statement
3277 if (node->getTrueBlock() != nullptr) {
3278 node->getTrueBlock()->traverse(this);
3279 if (result != spv::NoResult)
3280 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3281 }
3282
3283 if (node->getFalseBlock() != nullptr) {
3284 ifBuilder.makeBeginElse();
3285 // emit the "else" statement
3286 node->getFalseBlock()->traverse(this);
3287 if (result != spv::NoResult)
3288 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3289 }
3290
3291 // finish off the control flow
3292 ifBuilder.makeEndIf();
3293
3294 if (result != spv::NoResult) {
3295 builder.clearAccessChain();
3296 builder.setAccessChainLValue(result);
3297 }
3298 };
3299
3300 // Try for OpSelect (or a requirement to execute both sides)
3301 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003302 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3303 if (node->getType().getQualifier().isSpecConstant())
3304 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003305 executeBothSides();
3306 } else
3307 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003308
3309 return false;
3310}
3311
3312bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3313{
3314 // emit and get the condition before doing anything with switch
3315 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003316 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003317
Rex Xu57e65922017-07-04 23:23:40 +08003318 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003319 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003320
John Kessenich140f3df2015-06-26 16:58:36 -06003321 // browse the children to sort out code segments
3322 int defaultSegment = -1;
3323 std::vector<TIntermNode*> codeSegments;
3324 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3325 std::vector<int> caseValues;
3326 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3327 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3328 TIntermNode* child = *c;
3329 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003330 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003331 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003332 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich8985fc92020-03-03 10:25:07 -07003333 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()
3334 ->getConstArray()[0].getIConst());
John Kessenich140f3df2015-06-26 16:58:36 -06003335 } else
3336 codeSegments.push_back(child);
3337 }
3338
qining25262b32016-05-06 17:25:16 -04003339 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003340 // statements between the last case and the end of the switch statement
3341 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3342 (int)codeSegments.size() == defaultSegment)
3343 codeSegments.push_back(nullptr);
3344
3345 // make the switch statement
3346 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
John Kessenich8985fc92020-03-03 10:25:07 -07003347 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment,
3348 segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003349
3350 // emit all the code in the segments
3351 breakForLoop.push(false);
3352 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3353 builder.nextSwitchSegment(segmentBlocks, s);
3354 if (codeSegments[s])
3355 codeSegments[s]->traverse(this);
3356 else
3357 builder.addSwitchBreak();
3358 }
3359 breakForLoop.pop();
3360
3361 builder.endSwitch(segmentBlocks);
3362
3363 return false;
3364}
3365
3366void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3367{
3368 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003369 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003370
3371 builder.clearAccessChain();
3372 builder.setAccessChainRValue(constant);
3373}
3374
3375bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3376{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003377 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003378 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003379
3380 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003381 std::vector<unsigned int> operands;
3382 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003383
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003384 // Spec requires back edges to target header blocks, and every header block
3385 // must dominate its merge block. Make a header block first to ensure these
3386 // conditions are met. By definition, it will contain OpLoopMerge, followed
3387 // by a block-ending branch. But we don't want to put any other body/test
3388 // instructions in it, since the body/test may have arbitrary instructions,
3389 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003390 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003391 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003392 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003393 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003394 spv::Block& test = builder.makeNewBlock();
3395 builder.createBranch(&test);
3396
3397 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003398 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003399 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003400 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3401
3402 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003403 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003404 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003405 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003406 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003407 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003408
3409 builder.setBuildPoint(&blocks.continue_target);
3410 if (node->getTerminal())
3411 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003412 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003413 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003414 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003415 builder.createBranch(&blocks.body);
3416
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003417 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003418 builder.setBuildPoint(&blocks.body);
3419 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003420 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003421 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003422 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003423
3424 builder.setBuildPoint(&blocks.continue_target);
3425 if (node->getTerminal())
3426 node->getTerminal()->traverse(this);
3427 if (node->getTest()) {
3428 node->getTest()->traverse(this);
3429 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003430 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003431 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003432 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003433 // TODO: unless there was a break/return/discard instruction
3434 // somewhere in the body, this is an infinite loop, so we should
3435 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003436 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003437 }
John Kessenich140f3df2015-06-26 16:58:36 -06003438 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003439 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003440 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003441 return false;
3442}
3443
3444bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3445{
3446 if (node->getExpression())
3447 node->getExpression()->traverse(this);
3448
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003449 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003450
John Kessenich140f3df2015-06-26 16:58:36 -06003451 switch (node->getFlowOp()) {
3452 case glslang::EOpKill:
3453 builder.makeDiscard();
3454 break;
3455 case glslang::EOpBreak:
3456 if (breakForLoop.top())
3457 builder.createLoopExit();
3458 else
3459 builder.addSwitchBreak();
3460 break;
3461 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003462 builder.createLoopContinue();
3463 break;
3464 case glslang::EOpReturn:
John Kessenich435dd802020-06-30 01:27:08 -06003465 if (node->getExpression() != nullptr) {
John Kesseniched33e052016-10-06 12:59:51 -06003466 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3467 spv::Id returnId = accessChainLoad(glslangReturnType);
John Kessenich435dd802020-06-30 01:27:08 -06003468 if (builder.getTypeId(returnId) != currentFunction->getReturnType() ||
3469 TranslatePrecisionDecoration(glslangReturnType) != currentFunction->getReturnPrecision()) {
John Kesseniched33e052016-10-06 12:59:51 -06003470 builder.clearAccessChain();
John Kessenich435dd802020-06-30 01:27:08 -06003471 spv::Id copyId = builder.createVariable(currentFunction->getReturnPrecision(),
3472 spv::StorageClassFunction, currentFunction->getReturnType());
John Kesseniched33e052016-10-06 12:59:51 -06003473 builder.setAccessChainLValue(copyId);
3474 multiTypeStore(glslangReturnType, returnId);
John Kessenich435dd802020-06-30 01:27:08 -06003475 returnId = builder.createLoad(copyId, currentFunction->getReturnPrecision());
John Kesseniched33e052016-10-06 12:59:51 -06003476 }
3477 builder.makeReturn(false, returnId);
3478 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003479 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003480
3481 builder.clearAccessChain();
3482 break;
3483
John Kessenichb9197c82019-08-11 07:41:45 -06003484#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003485 case glslang::EOpDemote:
3486 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3487 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3488 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3489 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003490#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003491
John Kessenich140f3df2015-06-26 16:58:36 -06003492 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003493 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003494 break;
3495 }
3496
3497 return false;
3498}
3499
John Kessenich9c14f772019-06-17 08:38:35 -06003500spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003501{
qining25262b32016-05-06 17:25:16 -04003502 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003503 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003504 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003505 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003506 spv::Id result = createSpvConstant(*node);
3507 if (result != spv::NoResult)
3508 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003509 }
3510
3511 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003512 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003513 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3514 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003515
John Kessenichb9197c82019-08-11 07:41:45 -06003516 const bool contains16BitType = node->getType().contains16BitFloat() ||
3517 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003518 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003519 switch (storageClass) {
3520 case spv::StorageClassInput:
3521 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003522 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003523 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003524 break;
John Kessenich18310872018-05-14 22:08:53 -06003525 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003526 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003527 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3528 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003529 else
3530 builder.addCapability(spv::CapabilityStorageUniform16);
3531 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003532#ifndef GLSLANG_WEB
3533 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003534 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003535 builder.addCapability(spv::CapabilityStoragePushConstant16);
3536 break;
John Kessenich18310872018-05-14 22:08:53 -06003537 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003538 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003539 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003540 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3541 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003542#endif
John Kessenich18310872018-05-14 22:08:53 -06003543 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003544 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003545 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003546 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003547 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003548 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003549 }
3550 }
Rex Xuf89ad982017-04-07 23:22:33 +08003551
John Kessenichb9197c82019-08-11 07:41:45 -06003552 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003553 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003554 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003555 builder.addCapability(spv::CapabilityStoragePushConstant8);
3556 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003557 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003558 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003559 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003560 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003561 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003562 } else {
3563 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003564 }
3565 }
3566
John Kessenich140f3df2015-06-26 16:58:36 -06003567 const char* name = node->getName().c_str();
3568 if (glslang::IsAnonymous(name))
3569 name = "";
3570
Alejandro Piñeiroff6dcca2020-06-04 09:39:31 +02003571 spv::Id initializer = spv::NoResult;
3572
3573 if (node->getType().getQualifier().storage == glslang::EvqUniform &&
3574 !node->getConstArray().empty()) {
3575 int nextConst = 0;
3576 initializer = createSpvConstantFromConstUnionArray(node->getType(),
3577 node->getConstArray(),
3578 nextConst,
3579 false /* specConst */);
3580 }
3581
John Kessenich435dd802020-06-30 01:27:08 -06003582 return builder.createVariable(spv::NoPrecision, storageClass, spvType, name, initializer);
John Kessenich140f3df2015-06-26 16:58:36 -06003583}
3584
3585// Return type Id of the sampled type.
3586spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3587{
3588 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003589 case glslang::EbtInt: return builder.makeIntType(32);
3590 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003591 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003592#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003593 case glslang::EbtFloat16:
3594 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3595 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3596 return builder.makeFloatType(16);
3597#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003598 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003599 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003600 return builder.makeFloatType(32);
3601 }
3602}
3603
John Kessenich8c8505c2016-07-26 12:50:38 -06003604// If node is a swizzle operation, return the type that should be used if
3605// the swizzle base is first consumed by another operation, before the swizzle
3606// is applied.
3607spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3608{
John Kessenichecba76f2017-01-06 00:34:48 -07003609 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003610 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3611 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3612 else
3613 return spv::NoType;
3614}
3615
3616// When inverting a swizzle with a parent op, this function
3617// will apply the swizzle operation to a completed parent operation.
John Kessenich8985fc92020-03-03 10:25:07 -07003618spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
3619 spv::Id parentResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003620{
3621 std::vector<unsigned> swizzle;
3622 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3623 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3624}
3625
John Kessenich8c8505c2016-07-26 12:50:38 -06003626// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3627void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3628{
3629 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3630 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3631 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3632}
3633
John Kessenich3ac051e2015-12-20 11:29:16 -07003634// Convert from a glslang type to an SPV type, by calling into a
3635// recursive version of this function. This establishes the inherited
3636// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003637spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003638{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003639 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003640}
3641
3642// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003643// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003644// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003645spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003646 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3647 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003648{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003649 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003650
3651 switch (type.getBasicType()) {
3652 case glslang::EbtVoid:
3653 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003654 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003655 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003656 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003657 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3658 // a 32-bit int where non-0 means true.
3659 if (explicitLayout != glslang::ElpNone)
3660 spvType = builder.makeUintType(32);
3661 else
3662 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003663 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003664 case glslang::EbtInt:
3665 spvType = builder.makeIntType(32);
3666 break;
3667 case glslang::EbtUint:
3668 spvType = builder.makeUintType(32);
3669 break;
3670 case glslang::EbtFloat:
3671 spvType = builder.makeFloatType(32);
3672 break;
3673#ifndef GLSLANG_WEB
3674 case glslang::EbtDouble:
3675 spvType = builder.makeFloatType(64);
3676 break;
3677 case glslang::EbtFloat16:
3678 spvType = builder.makeFloatType(16);
3679 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003680 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003681 spvType = builder.makeIntType(8);
3682 break;
3683 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003684 spvType = builder.makeUintType(8);
3685 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003686 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003687 spvType = builder.makeIntType(16);
3688 break;
3689 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003690 spvType = builder.makeUintType(16);
3691 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003692 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003693 spvType = builder.makeIntType(64);
3694 break;
3695 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003696 spvType = builder.makeUintType(64);
3697 break;
John Kessenich426394d2015-07-23 10:22:48 -06003698 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003699 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003700 spvType = builder.makeUintType(32);
3701 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04003702 case glslang::EbtAccStruct:
3703 spvType = builder.makeAccelerationStructureType();
Chao Chenb50c02e2018-09-19 11:42:24 -07003704 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04003705 case glslang::EbtRayQuery:
3706 spvType = builder.makeRayQueryType();
3707 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003708 case glslang::EbtReference:
3709 {
3710 // Make the forward pointer, then recurse to convert the structure type, then
3711 // patch up the forward pointer with a real pointer type.
3712 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3713 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3714 forwardPointers[type.getReferentType()] = forwardId;
3715 }
3716 spvType = forwardPointers[type.getReferentType()];
3717 if (!forwardReferenceOnly) {
3718 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3719 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3720 forwardPointers[type.getReferentType()],
3721 referentType);
3722 }
3723 }
3724 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003725#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003726 case glslang::EbtSampler:
3727 {
3728 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003729 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003730 spvType = builder.makeSamplerType();
3731 } else {
3732 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003733 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3734 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3735 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3736 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003737 // already has both image and sampler, make the combined type
3738 spvType = builder.makeSampledImageType(spvType);
3739 }
John Kessenich55e7d112015-11-15 21:33:39 -07003740 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003741 }
John Kessenich140f3df2015-06-26 16:58:36 -06003742 break;
3743 case glslang::EbtStruct:
3744 case glslang::EbtBlock:
3745 {
3746 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003747 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003748
3749 // Try to share structs for different layouts, but not yet for other
3750 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003751 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003752 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003753 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003754 break;
3755
3756 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003757 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003758 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003759 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003760 }
3761 break;
Jeff Bolz04d73732019-05-31 13:06:01 -05003762 case glslang::EbtString:
3763 // no type used for OpString
3764 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003765 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003766 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003767 break;
3768 }
3769
3770 if (type.isMatrix())
3771 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3772 else {
3773 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3774 if (type.getVectorSize() > 1)
3775 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3776 }
3777
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003778 if (type.isCoopMat()) {
3779 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3780 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3781 if (type.getBasicType() == glslang::EbtFloat16)
3782 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003783 if (type.getBasicType() == glslang::EbtUint8 ||
3784 type.getBasicType() == glslang::EbtInt8) {
3785 builder.addCapability(spv::CapabilityInt8);
3786 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003787
3788 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3789 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3790 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3791
3792 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3793 }
3794
John Kessenich140f3df2015-06-26 16:58:36 -06003795 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003796 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3797
John Kessenichc9a80832015-09-12 12:17:44 -06003798 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003799 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003800 // We need to decorate array strides for types needing explicit layout, except blocks.
3801 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003802 // Use a dummy glslang type for querying internal strides of
3803 // arrays of arrays, but using just a one-dimensional array.
3804 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003805 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3806 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003807
3808 // Will compute the higher-order strides here, rather than making a whole
3809 // pile of types and doing repetitive recursion on their contents.
3810 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3811 }
John Kessenichf8842e52016-01-04 19:22:56 -07003812
3813 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003814 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003815 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003816 if (stride > 0)
3817 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003818 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003819 }
3820 } else {
3821 // single-dimensional array, and don't yet have stride
3822
John Kessenichf8842e52016-01-04 19:22:56 -07003823 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003824 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3825 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003826 }
John Kessenich31ed4832015-09-09 17:51:38 -06003827
John Kessenichead86222018-03-28 18:01:20 -06003828 // Do the outer dimension, which might not be known for a runtime-sized array.
3829 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3830 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003831 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003832 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003833#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003834 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003835 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003836 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3837 }
John Kessenichb9197c82019-08-11 07:41:45 -06003838#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003839 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003840 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003841 if (stride > 0)
3842 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003843 }
3844
3845 return spvType;
3846}
3847
John Kessenich0e737842017-03-24 18:38:16 -06003848// TODO: this functionality should exist at a higher level, in creating the AST
3849//
3850// Identify interface members that don't have their required extension turned on.
3851//
3852bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3853{
John Kessenicha28f7a72019-08-06 07:00:58 -06003854#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003855 auto& extensions = glslangIntermediate->getRequestedExtensions();
3856
Rex Xubcf291a2017-03-29 23:01:36 +08003857 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3858 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3859 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003860 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3861 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3862 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003863
3864 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3865 if (member.getFieldName() == "gl_ViewportMask" &&
3866 extensions.find("GL_NV_viewport_array2") == extensions.end())
3867 return true;
3868 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3869 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3870 return true;
3871 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3872 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3873 return true;
3874 }
3875#endif
John Kessenich0e737842017-03-24 18:38:16 -06003876
3877 return false;
3878};
3879
John Kessenich6090df02016-06-30 21:18:02 -06003880// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3881// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3882// Mutually recursive with convertGlslangToSpvType().
3883spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3884 const glslang::TTypeList* glslangMembers,
3885 glslang::TLayoutPacking explicitLayout,
3886 const glslang::TQualifier& qualifier)
3887{
3888 // Create a vector of struct types for SPIR-V to consume
3889 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07003890 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
3891 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003892 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003893 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3894 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3895 if (glslangMember.hiddenMember()) {
3896 ++memberDelta;
3897 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003898 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06003899 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003900 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003901 if (filterMember(glslangMember)) {
3902 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08003903 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003904 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003905 }
Roy05a5b532020-01-03 16:21:34 +08003906 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003907 }
John Kessenich6090df02016-06-30 21:18:02 -06003908 // modify just this child's view of the qualifier
3909 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3910 InheritQualifiers(memberQualifier, qualifier);
3911
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003912 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003913 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003914 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003915
3916 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003917 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3918 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003919
3920 // Make forward pointers for any pointer members, and create a list of members to
3921 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003922 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003923 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3924 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3925 }
3926 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003927 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3928 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003929 } else {
3930 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003931 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3932 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003933 }
John Kessenich6090df02016-06-30 21:18:02 -06003934 }
3935 }
3936
3937 // Make the SPIR-V type
3938 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003939 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003940 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3941
3942 // Decorate it
3943 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3944
John Kessenichd72f4882019-01-16 14:55:37 +07003945 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003946 auto it = deferredForwardPointers[i];
3947 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3948 }
3949
John Kessenich6090df02016-06-30 21:18:02 -06003950 return spvType;
3951}
3952
3953void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3954 const glslang::TTypeList* glslangMembers,
3955 glslang::TLayoutPacking explicitLayout,
3956 const glslang::TQualifier& qualifier,
3957 spv::Id spvType)
3958{
3959 // Name and decorate the non-hidden members
3960 int offset = -1;
3961 int locationOffset = 0; // for use within the members of this struct
3962 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3963 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3964 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003965 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08003966 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06003967 if (filterMember(glslangMember))
3968 continue;
3969 }
John Kessenich6090df02016-06-30 21:18:02 -06003970
3971 // modify just this child's view of the qualifier
3972 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3973 InheritQualifiers(memberQualifier, qualifier);
3974
3975 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003976 if (member < 0)
3977 continue;
3978
3979 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3980 builder.addMemberDecoration(spvType, member,
3981 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3982 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3983 // Add interpolation and auxiliary storage decorations only to
3984 // top-level members of Input and Output storage classes
3985 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3986 type.getQualifier().storage == glslang::EvqVaryingOut) {
3987 if (type.getBasicType() == glslang::EbtBlock ||
3988 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3989 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3990 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003991#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003992 addMeshNVDecoration(spvType, member, memberQualifier);
3993#endif
John Kessenich6090df02016-06-30 21:18:02 -06003994 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003995 }
3996 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003997
John Kessenichb9197c82019-08-11 07:41:45 -06003998#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003999 if (type.getBasicType() == glslang::EbtBlock &&
4000 qualifier.storage == glslang::EvqBuffer) {
4001 // Add memory decorations only to top-level members of shader storage block
4002 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05004003 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07004004 for (unsigned int i = 0; i < memory.size(); ++i)
4005 builder.addMemberDecoration(spvType, member, memory[i]);
4006 }
John Kessenichf8d1d742019-10-21 06:55:11 -06004007
John Kessenichb9197c82019-08-11 07:41:45 -06004008#endif
John Kessenich6090df02016-06-30 21:18:02 -06004009
John Kessenich5d610ee2018-03-07 18:05:55 -07004010 // Location assignment was already completed correctly by the front end,
4011 // just track whether a member needs to be decorated.
4012 // Ignore member locations if the container is an array, as that's
4013 // ill-specified and decisions have been made to not allow this.
4014 if (! type.isArray() && memberQualifier.hasLocation())
4015 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06004016
John Kessenich5d610ee2018-03-07 18:05:55 -07004017 if (qualifier.hasLocation()) // track for upcoming inheritance
4018 locationOffset += glslangIntermediate->computeTypeLocationSize(
4019 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06004020
John Kessenich5d610ee2018-03-07 18:05:55 -07004021 // component, XFB, others
4022 if (glslangMember.getQualifier().hasComponent())
4023 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
4024 glslangMember.getQualifier().layoutComponent);
4025 if (glslangMember.getQualifier().hasXfbOffset())
4026 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
4027 glslangMember.getQualifier().layoutXfbOffset);
4028 else if (explicitLayout != glslang::ElpNone) {
4029 // figure out what to do with offset, which is accumulating
4030 int nextOffset;
4031 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
4032 if (offset >= 0)
4033 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
4034 offset = nextOffset;
4035 }
John Kessenich6090df02016-06-30 21:18:02 -06004036
John Kessenich5d610ee2018-03-07 18:05:55 -07004037 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
4038 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
4039 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06004040
John Kessenich5d610ee2018-03-07 18:05:55 -07004041 // built-in variable decorations
4042 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
4043 if (builtIn != spv::BuiltInMax)
4044 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08004045
John Kessenichb9197c82019-08-11 07:41:45 -06004046#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06004047 // nonuniform
4048 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
4049
John Kessenichead86222018-03-28 18:01:20 -06004050 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
4051 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
4052 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
4053 memberQualifier.semanticName);
4054 }
4055
John Kessenich5d610ee2018-03-07 18:05:55 -07004056 if (builtIn == spv::BuiltInLayer) {
4057 // SPV_NV_viewport_array2 extension
4058 if (glslangMember.getQualifier().layoutViewportRelative){
4059 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
4060 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4061 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08004062 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004063 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
4064 builder.addMemberDecoration(spvType, member,
4065 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
4066 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
4067 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4068 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08004069 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004070 }
4071 if (glslangMember.getQualifier().layoutPassthrough) {
4072 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
4073 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
4074 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4075 }
chaoc771d89f2017-01-13 01:10:53 -08004076#endif
John Kessenich6090df02016-06-30 21:18:02 -06004077 }
4078
4079 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07004080 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
4081 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06004082}
4083
John Kessenich6c292d32016-02-15 20:58:50 -07004084// Turn the expression forming the array size into an id.
4085// This is not quite trivial, because of specialization constants.
4086// Sometimes, a raw constant is turned into an Id, and sometimes
4087// a specialization constant expression is.
4088spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
4089{
4090 // First, see if this is sized with a node, meaning a specialization constant:
4091 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
4092 if (specNode != nullptr) {
4093 builder.clearAccessChain();
4094 specNode->traverse(this);
4095 return accessChainLoad(specNode->getAsTyped()->getType());
4096 }
qining25262b32016-05-06 17:25:16 -04004097
John Kessenich6c292d32016-02-15 20:58:50 -07004098 // Otherwise, need a compile-time (front end) size, get it:
4099 int size = arraySizes.getDimSize(dim);
4100 assert(size > 0);
4101 return builder.makeUintConstant(size);
4102}
4103
John Kessenich103bef92016-02-08 21:38:15 -07004104// Wrap the builder's accessChainLoad to:
4105// - localize handling of RelaxedPrecision
4106// - use the SPIR-V inferred type instead of another conversion of the glslang type
4107// (avoids unnecessary work and possible type punning for structures)
4108// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07004109spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
4110{
John Kessenich103bef92016-02-08 21:38:15 -07004111 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004112
4113 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4114 coherentFlags |= TranslateCoherent(type);
4115
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004116 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004117 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004118
John Kessenich5611c6d2018-04-05 11:25:02 -06004119 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
John Kessenich8985fc92020-03-03 10:25:07 -07004120 TranslateNonUniformDecoration(type.getQualifier()),
4121 nominalTypeId,
4122 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
4123 TranslateMemoryScope(coherentFlags),
4124 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07004125
4126 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08004127 if (type.getBasicType() == glslang::EbtBool) {
4128 if (builder.isScalarType(nominalTypeId)) {
4129 // Conversion for bool
4130 spv::Id boolType = builder.makeBoolType();
4131 if (nominalTypeId != boolType)
4132 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
4133 } else if (builder.isVectorType(nominalTypeId)) {
4134 // Conversion for bvec
4135 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4136 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
4137 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07004138 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
4139 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004140 }
4141 }
John Kessenich103bef92016-02-08 21:38:15 -07004142
4143 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07004144}
4145
Rex Xu27253232016-02-23 17:51:09 +08004146// Wrap the builder's accessChainStore to:
4147// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06004148//
4149// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08004150void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
4151{
4152 // Need to convert to abstract types when necessary
4153 if (type.getBasicType() == glslang::EbtBool) {
4154 spv::Id nominalTypeId = builder.accessChainGetInferredType();
4155
4156 if (builder.isScalarType(nominalTypeId)) {
4157 // Conversion for bool
4158 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06004159 if (nominalTypeId != boolType) {
4160 // keep these outside arguments, for determinant order-of-evaluation
4161 spv::Id one = builder.makeUintConstant(1);
4162 spv::Id zero = builder.makeUintConstant(0);
4163 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
4164 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06004165 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08004166 } else if (builder.isVectorType(nominalTypeId)) {
4167 // Conversion for bvec
4168 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4169 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06004170 if (nominalTypeId != bvecType) {
4171 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06004172 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
4173 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
4174 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06004175 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06004176 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
4177 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004178 }
4179 }
4180
Jeff Bolz36831c92018-09-05 10:11:41 -05004181 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4182 coherentFlags |= TranslateCoherent(type);
4183
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004184 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004185 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004186
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02004187 builder.accessChainStore(rvalue, TranslateNonUniformDecoration(type.getQualifier()),
John Kessenich8985fc92020-03-03 10:25:07 -07004188 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
4189 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004190 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08004191}
4192
John Kessenich4bf71552016-09-02 11:20:21 -06004193// For storing when types match at the glslang level, but not might match at the
4194// SPIR-V level.
4195//
4196// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004197// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004198// as in a member-decorated way.
4199//
4200// NOTE: This function can handle any store request; if it's not special it
4201// simplifies to a simple OpStore.
4202//
4203// Implicitly uses the existing builder.accessChain as the storage target.
4204void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4205{
John Kessenichb3e24e42016-09-11 12:33:43 -06004206 // we only do the complex path here if it's an aggregate
4207 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004208 accessChainStore(type, rValue);
4209 return;
4210 }
4211
John Kessenichb3e24e42016-09-11 12:33:43 -06004212 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004213 spv::Id rType = builder.getTypeId(rValue);
4214 spv::Id lValue = builder.accessChainGetLValue();
4215 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4216 if (lType == rType) {
4217 accessChainStore(type, rValue);
4218 return;
4219 }
4220
John Kessenichb3e24e42016-09-11 12:33:43 -06004221 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004222 // where the two types were the same type in GLSL. This requires member
4223 // by member copy, recursively.
4224
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004225 // SPIR-V 1.4 added an instruction to do help do this.
4226 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4227 // However, bool in uniform space is changed to int, so
4228 // OpCopyLogical does not work for that.
4229 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4230 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4231 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4232 if (lBool == rBool) {
4233 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4234 accessChainStore(type, logicalCopy);
4235 return;
4236 }
4237 }
4238
John Kessenichb3e24e42016-09-11 12:33:43 -06004239 // If an array, copy element by element.
4240 if (type.isArray()) {
4241 glslang::TType glslangElementType(type, 0);
4242 spv::Id elementRType = builder.getContainedTypeId(rType);
4243 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4244 // get the source member
4245 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004246
John Kessenichb3e24e42016-09-11 12:33:43 -06004247 // set up the target storage
4248 builder.clearAccessChain();
4249 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004250 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4251 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004252
John Kessenichb3e24e42016-09-11 12:33:43 -06004253 // store the member
4254 multiTypeStore(glslangElementType, elementRValue);
4255 }
4256 } else {
4257 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004258
John Kessenichb3e24e42016-09-11 12:33:43 -06004259 // loop over structure members
4260 const glslang::TTypeList& members = *type.getStruct();
4261 for (int m = 0; m < (int)members.size(); ++m) {
4262 const glslang::TType& glslangMemberType = *members[m].type;
4263
4264 // get the source member
4265 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4266 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4267
4268 // set up the target storage
4269 builder.clearAccessChain();
4270 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004271 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4272 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004273
4274 // store the member
4275 multiTypeStore(glslangMemberType, memberRValue);
4276 }
John Kessenich4bf71552016-09-02 11:20:21 -06004277 }
4278}
4279
John Kessenichf85e8062015-12-19 13:57:10 -07004280// Decide whether or not this type should be
4281// decorated with offsets and strides, and if so
4282// whether std140 or std430 rules should be applied.
4283glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004284{
John Kessenichf85e8062015-12-19 13:57:10 -07004285 // has to be a block
4286 if (type.getBasicType() != glslang::EbtBlock)
4287 return glslang::ElpNone;
4288
Chao Chen3c366992018-09-19 11:41:59 -07004289 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004290 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004291 type.getQualifier().storage != glslang::EvqBuffer &&
4292 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004293 return glslang::ElpNone;
4294
4295 // return the layout to use
4296 switch (type.getQualifier().layoutPacking) {
4297 case glslang::ElpStd140:
4298 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004299 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004300 return type.getQualifier().layoutPacking;
4301 default:
4302 return glslang::ElpNone;
4303 }
John Kessenich31ed4832015-09-09 17:51:38 -06004304}
4305
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004306// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004307int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4308 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004309{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004310 int size;
John Kessenich49987892015-12-29 17:11:44 -07004311 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004312 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4313 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004314
4315 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004316}
4317
John Kessenich49987892015-12-29 17:11:44 -07004318// 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 -07004319// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004320int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4321 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004322{
John Kessenich49987892015-12-29 17:11:44 -07004323 glslang::TType elementType;
4324 elementType.shallowCopy(matrixType);
4325 elementType.clearArraySizes();
4326
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004327 int size;
John Kessenich49987892015-12-29 17:11:44 -07004328 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004329 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4330 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004331
4332 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004333}
4334
John Kessenich5e4b1242015-08-06 22:53:06 -06004335// Given a member type of a struct, realign the current offset for it, and compute
4336// the next (not yet aligned) offset for the next member, which will get aligned
4337// on the next call.
4338// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4339// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4340// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004341void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4342 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004343{
4344 // this will get a positive value when deemed necessary
4345 nextOffset = -1;
4346
John Kessenich5e4b1242015-08-06 22:53:06 -06004347 // override anything in currentOffset with user-set offset
4348 if (memberType.getQualifier().hasOffset())
4349 currentOffset = memberType.getQualifier().layoutOffset;
4350
4351 // It could be that current linker usage in glslang updated all the layoutOffset,
4352 // in which case the following code does not matter. But, that's not quite right
4353 // once cross-compilation unit GLSL validation is done, as the original user
4354 // settings are needed in layoutOffset, and then the following will come into play.
4355
John Kessenichf85e8062015-12-19 13:57:10 -07004356 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004357 if (! memberType.getQualifier().hasOffset())
4358 currentOffset = -1;
4359
4360 return;
4361 }
4362
John Kessenichf85e8062015-12-19 13:57:10 -07004363 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004364 if (currentOffset < 0)
4365 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004366
John Kessenich5e4b1242015-08-06 22:53:06 -06004367 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4368 // but possibly not yet correctly aligned.
4369
4370 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004371 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004372 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4373 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004374
4375 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004376 // TODO: make this consistent in early phases of code:
4377 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4378 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4379 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004380 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004381 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004382 int dummySize;
4383 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4384 if (componentAlignment <= 4)
4385 memberAlignment = componentAlignment;
4386 }
4387
4388 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004389 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004390
4391 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004392 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4393 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004394 glslang::RoundToPow2(currentOffset, 16);
4395
John Kessenich5e4b1242015-08-06 22:53:06 -06004396 nextOffset = currentOffset + memberSize;
4397}
4398
David Netoa901ffe2016-06-08 14:11:40 +01004399void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004400{
David Netoa901ffe2016-06-08 14:11:40 +01004401 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4402 switch (glslangBuiltIn)
4403 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004404 case glslang::EbvPointSize:
4405#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004406 case glslang::EbvClipDistance:
4407 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004408 case glslang::EbvViewportMaskNV:
4409 case glslang::EbvSecondaryPositionNV:
4410 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004411 case glslang::EbvPositionPerViewNV:
4412 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004413 case glslang::EbvTaskCountNV:
4414 case glslang::EbvPrimitiveCountNV:
4415 case glslang::EbvPrimitiveIndicesNV:
4416 case glslang::EbvClipDistancePerViewNV:
4417 case glslang::EbvCullDistancePerViewNV:
4418 case glslang::EbvLayerPerViewNV:
4419 case glslang::EbvMeshViewCountNV:
4420 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004421#endif
David Netoa901ffe2016-06-08 14:11:40 +01004422 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4423 // Alternately, we could just call this for any glslang built-in, since the
4424 // capability already guards against duplicates.
4425 TranslateBuiltInDecoration(glslangBuiltIn, false);
4426 break;
4427 default:
4428 // Capabilities were already generated when the struct was declared.
4429 break;
4430 }
John Kessenichebb50532016-05-16 19:22:05 -06004431}
4432
John Kessenich6fccb3c2016-09-19 16:01:41 -06004433bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004434{
John Kessenicheee9d532016-09-19 18:09:30 -06004435 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004436}
4437
John Kessenichd41993d2017-09-10 15:21:05 -06004438// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004439// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4440// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004441bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004442{
John Kessenich6a14f782017-12-04 02:48:10 -07004443 assert(qualifier == glslang::EvqIn ||
4444 qualifier == glslang::EvqOut ||
4445 qualifier == glslang::EvqInOut ||
rdbd8edfd82020-06-02 08:30:07 +02004446 qualifier == glslang::EvqUniform ||
John Kessenich6a14f782017-12-04 02:48:10 -07004447 qualifier == glslang::EvqConstReadOnly);
rdbd8edfd82020-06-02 08:30:07 +02004448 return qualifier != glslang::EvqConstReadOnly &&
4449 qualifier != glslang::EvqUniform;
John Kessenichd41993d2017-09-10 15:21:05 -06004450}
4451
4452// Is parameter pass-by-original?
4453bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4454 bool implicitThisParam)
4455{
4456 if (implicitThisParam) // implicit this
4457 return true;
4458 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004459 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004460 return paramType.containsOpaque() || // sampler, etc.
4461 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4462}
4463
John Kessenich140f3df2015-06-26 16:58:36 -06004464// Make all the functions, skeletally, without actually visiting their bodies.
4465void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4466{
John Kessenich8985fc92020-03-03 10:25:07 -07004467 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4468 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004469 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4470 if (paramPrecision != spv::NoPrecision)
4471 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004472 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004473 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004474 // Original and non-writable params pass the pointer directly and
4475 // use restrict/aliased, others are stored to a pointer in Function
4476 // memory and use RestrictPointer/AliasedPointer.
4477 if (originalParam(type.getQualifier().storage, type, false) ||
4478 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004479 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4480 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004481 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004482 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4483 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004484 }
4485 }
John Kessenichfad62972017-07-18 02:35:46 -06004486 };
4487
John Kessenich140f3df2015-06-26 16:58:36 -06004488 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4489 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004490 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004491 continue;
4492
4493 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004494 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004495 //
qining25262b32016-05-06 17:25:16 -04004496 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004497 // function. What it is an address of varies:
4498 //
John Kessenich4bf71552016-09-02 11:20:21 -06004499 // - "in" parameters not marked as "const" can be written to without modifying the calling
4500 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004501 //
4502 // - "const in" parameters can just be the r-value, as no writes need occur.
4503 //
John Kessenich4bf71552016-09-02 11:20:21 -06004504 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4505 // 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 -06004506
4507 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004508 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004509 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4510
John Kessenich155d3512019-08-08 23:29:20 -06004511#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004512 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4513 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004514#else
4515 bool implicitThis = false;
4516#endif
John Kessenich37789792017-03-21 23:56:40 -06004517
John Kessenichfad62972017-07-18 02:35:46 -06004518 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004519 for (int p = 0; p < (int)parameters.size(); ++p) {
4520 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4521 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004522 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004523 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004524 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004525 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4526 else
John Kessenich4bf71552016-09-02 11:20:21 -06004527 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004528 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004529 paramTypes.push_back(typeId);
4530 }
4531
4532 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004533 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4534 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004535 glslFunction->getName().c_str(), paramTypes,
4536 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004537 if (implicitThis)
4538 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004539
4540 // Track function to emit/call later
4541 functionMap[glslFunction->getName().c_str()] = function;
4542
4543 // Set the parameter id's
4544 for (int p = 0; p < (int)parameters.size(); ++p) {
4545 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4546 // give a name too
4547 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004548
4549 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004550 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004551 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004552 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004553 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004554 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004555 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004556 }
4557 }
4558}
4559
4560// Process all the initializers, while skipping the functions and link objects
4561void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4562{
4563 builder.setBuildPoint(shaderEntry->getLastBlock());
4564 for (int i = 0; i < (int)initializers.size(); ++i) {
4565 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004566 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4567 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004568
4569 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004570 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004571 initializer->traverse(this);
4572 }
4573 }
4574}
4575
4576// Process all the functions, while skipping initializers.
4577void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4578{
4579 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4580 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004581 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004582 node->traverse(this);
4583 }
4584}
4585
4586void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4587{
qining25262b32016-05-06 17:25:16 -04004588 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004589 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004590 currentFunction = functionMap[node->getName().c_str()];
4591 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004592 builder.setBuildPoint(functionBlock);
4593}
4594
John Kessenich8985fc92020-03-03 10:25:07 -07004595void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4596 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004597{
Rex Xufc618912015-09-09 16:42:49 +08004598 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004599
4600 glslang::TSampler sampler = {};
4601 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004602#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004603 bool f16ShadowCompare = false;
4604#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004605 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004606 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4607 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004608#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004609 f16ShadowCompare = sampler.shadow &&
4610 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004611#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004612 }
4613
John Kessenich140f3df2015-06-26 16:58:36 -06004614 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4615 builder.clearAccessChain();
4616 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004617
John Kessenicha28f7a72019-08-06 07:00:58 -06004618#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004619 // Special case l-value operands
4620 bool lvalue = false;
4621 switch (node.getOp()) {
4622 case glslang::EOpImageAtomicAdd:
4623 case glslang::EOpImageAtomicMin:
4624 case glslang::EOpImageAtomicMax:
4625 case glslang::EOpImageAtomicAnd:
4626 case glslang::EOpImageAtomicOr:
4627 case glslang::EOpImageAtomicXor:
4628 case glslang::EOpImageAtomicExchange:
4629 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004630 case glslang::EOpImageAtomicLoad:
4631 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004632 if (i == 0)
4633 lvalue = true;
4634 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004635 case glslang::EOpSparseImageLoad:
4636 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4637 lvalue = true;
4638 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004639 case glslang::EOpSparseTexture:
4640 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4641 lvalue = true;
4642 break;
4643 case glslang::EOpSparseTextureClamp:
4644 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4645 lvalue = true;
4646 break;
4647 case glslang::EOpSparseTextureLod:
4648 case glslang::EOpSparseTextureOffset:
4649 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4650 lvalue = true;
4651 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004652 case glslang::EOpSparseTextureFetch:
4653 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4654 lvalue = true;
4655 break;
4656 case glslang::EOpSparseTextureFetchOffset:
4657 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4658 lvalue = true;
4659 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004660 case glslang::EOpSparseTextureLodOffset:
4661 case glslang::EOpSparseTextureGrad:
4662 case glslang::EOpSparseTextureOffsetClamp:
4663 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4664 lvalue = true;
4665 break;
4666 case glslang::EOpSparseTextureGradOffset:
4667 case glslang::EOpSparseTextureGradClamp:
4668 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4669 lvalue = true;
4670 break;
4671 case glslang::EOpSparseTextureGradOffsetClamp:
4672 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4673 lvalue = true;
4674 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004675 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004676 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4677 lvalue = true;
4678 break;
4679 case glslang::EOpSparseTextureGatherOffset:
4680 case glslang::EOpSparseTextureGatherOffsets:
4681 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4682 lvalue = true;
4683 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004684 case glslang::EOpSparseTextureGatherLod:
4685 if (i == 3)
4686 lvalue = true;
4687 break;
4688 case glslang::EOpSparseTextureGatherLodOffset:
4689 case glslang::EOpSparseTextureGatherLodOffsets:
4690 if (i == 4)
4691 lvalue = true;
4692 break;
Rex Xu129799a2017-07-05 17:23:28 +08004693 case glslang::EOpSparseImageLoadLod:
4694 if (i == 3)
4695 lvalue = true;
4696 break;
Chao Chen3a137962018-09-19 11:41:27 -07004697 case glslang::EOpImageSampleFootprintNV:
4698 if (i == 4)
4699 lvalue = true;
4700 break;
4701 case glslang::EOpImageSampleFootprintClampNV:
4702 case glslang::EOpImageSampleFootprintLodNV:
4703 if (i == 5)
4704 lvalue = true;
4705 break;
4706 case glslang::EOpImageSampleFootprintGradNV:
4707 if (i == 6)
4708 lvalue = true;
4709 break;
4710 case glslang::EOpImageSampleFootprintGradClampNV:
4711 if (i == 7)
4712 lvalue = true;
4713 break;
Rex Xufc618912015-09-09 16:42:49 +08004714 default:
4715 break;
4716 }
4717
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004718 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004719 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004720 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4721 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4722 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004723#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004724 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004725 }
4726}
4727
John Kessenichfc51d282015-08-19 13:34:18 -06004728void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004729{
John Kessenichfc51d282015-08-19 13:34:18 -06004730 builder.clearAccessChain();
4731 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004732 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004733}
John Kessenich140f3df2015-06-26 16:58:36 -06004734
John Kessenichfc51d282015-08-19 13:34:18 -06004735spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4736{
John Kesseniche485c7a2017-05-31 18:50:53 -06004737 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004738 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004739
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004740 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004741
John Kessenichfc51d282015-08-19 13:34:18 -06004742 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004743
John Kessenichf43c7392019-03-31 10:51:57 -06004744 const glslang::TType &imageType = node->getAsAggregate()
4745 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4746 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004747 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004748#ifdef GLSLANG_WEB
4749 const bool f16ShadowCompare = false;
4750#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004751 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004752 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4753 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004754#endif
4755
John Kessenichf43c7392019-03-31 10:51:57 -06004756 const auto signExtensionMask = [&]() {
4757 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4758 if (sampler.type == glslang::EbtUint)
4759 return spv::ImageOperandsZeroExtendMask;
4760 else if (sampler.type == glslang::EbtInt)
4761 return spv::ImageOperandsSignExtendMask;
4762 }
4763 return spv::ImageOperandsMaskNone;
4764 };
4765
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004766 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4767
John Kessenichfc51d282015-08-19 13:34:18 -06004768 std::vector<spv::Id> arguments;
4769 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004770 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004771 else
4772 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenich12c155f2020-06-30 07:52:05 -06004773 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
John Kessenichfc51d282015-08-19 13:34:18 -06004774
4775 spv::Builder::TextureParameters params = { };
4776 params.sampler = arguments[0];
4777
Rex Xu04db3f52015-09-16 11:44:02 +08004778 glslang::TCrackedTextureOp cracked;
4779 node->crackTexture(sampler, cracked);
4780
amhagan05506bb2017-06-13 16:53:02 -04004781 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004782
Bas Nieuwenhuizen58064312020-09-03 03:04:13 +02004783 if (builder.isSampledImage(params.sampler) &&
4784 ((cracked.query && node->getOp() != glslang::EOpTextureQueryLod) || cracked.fragMask || cracked.fetch)) {
4785 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4786 if (imageType.getQualifier().isNonUniform()) {
4787 builder.addDecoration(params.sampler, spv::DecorationNonUniformEXT);
4788 }
4789 }
John Kessenichfc51d282015-08-19 13:34:18 -06004790 // Check for queries
4791 if (cracked.query) {
4792 switch (node->getOp()) {
4793 case glslang::EOpImageQuerySize:
4794 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004795 if (arguments.size() > 1) {
4796 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004797 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004798 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004799 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004800#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004801 case glslang::EOpImageQuerySamples:
4802 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004803 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004804 case glslang::EOpTextureQueryLod:
4805 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004806 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004807 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004808 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004809 case glslang::EOpSparseTexelsResident:
4810 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004811#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004812 default:
4813 assert(0);
4814 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004815 }
John Kessenich140f3df2015-06-26 16:58:36 -06004816 }
4817
LoopDawg4425f242018-02-18 11:40:01 -07004818 int components = node->getType().getVectorSize();
4819
4820 if (node->getOp() == glslang::EOpTextureFetch) {
4821 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4822 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4823 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4824 // here around e.g. which ones return scalars or other types.
4825 components = 4;
4826 }
4827
4828 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4829
4830 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4831
Rex Xufc618912015-09-09 16:42:49 +08004832 // Check for image functions other than queries
4833 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004834 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004835 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004836 spv::IdImmediate image = { true, *(opIt++) };
4837 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004838
4839 // Handle subpass operations
4840 // TODO: GLSL should change to have the "MS" only on the type rather than the
4841 // built-in function.
4842 if (cracked.subpass) {
4843 // add on the (0,0) coordinate
4844 spv::Id zero = builder.makeIntConstant(0);
4845 std::vector<spv::Id> comps;
4846 comps.push_back(zero);
4847 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004848 spv::IdImmediate coord = { true,
4849 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4850 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004851 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4852 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004853 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004854 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4855 }
4856 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004857 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004858 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004859 spv::IdImmediate imageOperand = { true, *(opIt++) };
4860 operands.push_back(imageOperand);
4861 }
John Kessenich6c292d32016-02-15 20:58:50 -07004862 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004863 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4864 builder.setPrecision(result, precision);
4865 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004866 }
4867
John Kessenich149afc32018-08-14 13:31:43 -06004868 spv::IdImmediate coord = { true, *(opIt++) };
4869 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004870 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004871 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004872 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004873 mask = mask | spv::ImageOperandsSampleMask;
4874 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004875 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004876 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4877 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004878 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004879 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004880 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4881 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004882 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004883 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004884 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4885 operands.push_back(imageOperands);
4886 }
4887 if (mask & spv::ImageOperandsSampleMask) {
4888 spv::IdImmediate imageOperand = { true, *opIt++ };
4889 operands.push_back(imageOperand);
4890 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004891 if (mask & spv::ImageOperandsLodMask) {
4892 spv::IdImmediate imageOperand = { true, *opIt++ };
4893 operands.push_back(imageOperand);
4894 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004895 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004896 spv::IdImmediate imageOperand = { true,
4897 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004898 operands.push_back(imageOperand);
4899 }
4900
John Kessenich149afc32018-08-14 13:31:43 -06004901 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004902 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004903
John Kessenich149afc32018-08-14 13:31:43 -06004904 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004905 builder.setPrecision(result[0], precision);
4906
4907 // If needed, add a conversion constructor to the proper size.
4908 if (components != node->getType().getVectorSize())
4909 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4910
4911 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004912 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004913
Jeff Bolz36831c92018-09-05 10:11:41 -05004914 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004915 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004916 spv::IdImmediate texel = { true, *(opIt + 1) };
4917 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004918 } else {
4919 spv::IdImmediate texel = { true, *opIt };
4920 operands.push_back(texel);
4921 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004922
4923 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004924 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004925 mask = mask | spv::ImageOperandsSampleMask;
4926 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004927 if (cracked.lod) {
4928 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4929 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4930 mask = mask | spv::ImageOperandsLodMask;
4931 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004932 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4933 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004934 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004935 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004936 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4937 operands.push_back(imageOperands);
4938 }
4939 if (mask & spv::ImageOperandsSampleMask) {
4940 spv::IdImmediate imageOperand = { true, *opIt++ };
4941 operands.push_back(imageOperand);
4942 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004943 if (mask & spv::ImageOperandsLodMask) {
4944 spv::IdImmediate imageOperand = { true, *opIt++ };
4945 operands.push_back(imageOperand);
4946 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004947 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004948 spv::IdImmediate imageOperand = { true,
4949 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004950 operands.push_back(imageOperand);
4951 }
4952
John Kessenich56bab042015-09-16 10:54:31 -06004953 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004954 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004955 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004956 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004957 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4958 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004959 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004960 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004961 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4962
Jeff Bolz36831c92018-09-05 10:11:41 -05004963 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004964 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004965 mask = mask | spv::ImageOperandsSampleMask;
4966 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004967 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004968 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4969 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4970
Jeff Bolz36831c92018-09-05 10:11:41 -05004971 mask = mask | spv::ImageOperandsLodMask;
4972 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004973 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4974 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004975 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004976 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004977 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004978 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004979 }
4980 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004981 spv::IdImmediate imageOperand = { true, *opIt++ };
4982 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004983 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004984 if (mask & spv::ImageOperandsLodMask) {
4985 spv::IdImmediate imageOperand = { true, *opIt++ };
4986 operands.push_back(imageOperand);
4987 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004988 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07004989 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
4990 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004991 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004992 }
4993
4994 // Create the return type that was a special structure
4995 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004996 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004997 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4998 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4999
5000 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
5001
5002 // Decode the return type
5003 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
5004 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07005005 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08005006 // Process image atomic operations
5007
5008 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
5009 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06005010 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005011 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06005012 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06005013
Jeff Bolz36831c92018-09-05 10:11:41 -05005014 spv::Id resultTypeId;
5015 // imageAtomicStore has a void return type so base the pointer type on
5016 // the type of the value operand.
5017 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08005018 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05005019 } else {
5020 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
5021 }
John Kessenich56bab042015-09-16 10:54:31 -06005022 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Jeff Bolz39ffdaf2020-03-09 10:48:12 -05005023 if (imageType.getQualifier().nonUniform) {
5024 builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
5025 }
Rex Xufc618912015-09-09 16:42:49 +08005026
5027 std::vector<spv::Id> operands;
5028 operands.push_back(pointer);
5029 for (; opIt != arguments.end(); ++opIt)
5030 operands.push_back(*opIt);
5031
John Kessenich8985fc92020-03-03 10:25:07 -07005032 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
5033 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08005034 }
5035 }
5036
John Kessenicha28f7a72019-08-06 07:00:58 -06005037#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04005038 // Check for fragment mask functions other than queries
5039 if (cracked.fragMask) {
5040 assert(sampler.ms);
5041
5042 auto opIt = arguments.begin();
5043 std::vector<spv::Id> operands;
5044
amhagan05506bb2017-06-13 16:53:02 -04005045 operands.push_back(params.sampler);
5046 ++opIt;
5047
5048 if (sampler.isSubpass()) {
5049 // add on the (0,0) coordinate
5050 spv::Id zero = builder.makeIntConstant(0);
5051 std::vector<spv::Id> comps;
5052 comps.push_back(zero);
5053 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07005054 operands.push_back(builder.makeCompositeConstant(
5055 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04005056 }
5057
5058 for (; opIt != arguments.end(); ++opIt)
5059 operands.push_back(*opIt);
5060
5061 spv::Op fragMaskOp = spv::OpNop;
5062 if (node->getOp() == glslang::EOpFragmentMaskFetch)
5063 fragMaskOp = spv::OpFragmentMaskFetchAMD;
5064 else if (node->getOp() == glslang::EOpFragmentFetch)
5065 fragMaskOp = spv::OpFragmentFetchAMD;
5066
5067 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
5068 builder.addCapability(spv::CapabilityFragmentMaskAMD);
5069 return builder.createOp(fragMaskOp, resultType(), operands);
5070 }
5071#endif
5072
Rex Xufc618912015-09-09 16:42:49 +08005073 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08005074 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07005075 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005076 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08005077
John Kessenichfc51d282015-08-19 13:34:18 -06005078 // check for bias argument
5079 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08005080 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005081 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08005082 if (cracked.gather)
5083 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08005084
5085 if (f16ShadowCompare)
5086 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005087 if (cracked.offset)
5088 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08005089 else if (cracked.offsets)
5090 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005091 if (cracked.grad)
5092 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08005093 if (cracked.lodClamp)
5094 ++nonBiasArgCount;
5095 if (sparse)
5096 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07005097 if (imageFootprint)
5098 //Following three extra arguments
5099 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5100 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06005101 if ((int)arguments.size() > nonBiasArgCount)
5102 bias = true;
5103 }
5104
John Kessenicha28f7a72019-08-06 07:00:58 -06005105#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08005106 if (cracked.gather) {
5107 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
5108 if (bias || cracked.lod ||
5109 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
5110 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08005111 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08005112 }
5113 }
5114#endif
5115
John Kessenichfc51d282015-08-19 13:34:18 -06005116 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07005117
John Kessenichfc51d282015-08-19 13:34:18 -06005118 params.coords = arguments[1];
5119 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07005120 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07005121
5122 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08005123 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005124 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08005125 ++extraArgs;
5126 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07005127 params.Dref = arguments[2];
5128 ++extraArgs;
5129 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06005130 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06005131 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06005132 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06005133 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06005134 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005135 dRefComp = builder.getNumComponents(params.coords) - 1;
5136 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07005137 params.Dref = builder.createCompositeExtract(params.coords,
5138 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06005139 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005140
5141 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06005142 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005143 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06005144 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06005145 } else if (glslangIntermediate->getStage() != EShLangFragment &&
5146 !(glslangIntermediate->getStage() == EShLangCompute &&
5147 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07005148 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
5149 noImplicitLod = true;
5150 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005151
5152 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005153 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005154 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08005155 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005156 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005157
5158 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06005159 if (cracked.grad) {
5160 params.gradX = arguments[2 + extraArgs];
5161 params.gradY = arguments[3 + extraArgs];
5162 extraArgs += 2;
5163 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005164
5165 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07005166 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06005167 params.offset = arguments[2 + extraArgs];
5168 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005169 } else if (cracked.offsets) {
5170 params.offsets = arguments[2 + extraArgs];
5171 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005172 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005173
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005174#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005175 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005176 if (cracked.lodClamp) {
5177 params.lodClamp = arguments[2 + extraArgs];
5178 ++extraArgs;
5179 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005180 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005181 if (sparse) {
5182 params.texelOut = arguments[2 + extraArgs];
5183 ++extraArgs;
5184 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005185 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005186 if (cracked.gather && ! sampler.shadow) {
5187 // default component is 0, if missing, otherwise an argument
5188 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005189 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005190 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005191 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005192 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005193 }
Chao Chen3a137962018-09-19 11:41:27 -07005194 spv::Id resultStruct = spv::NoResult;
5195 if (imageFootprint) {
5196 //Following three extra arguments
5197 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5198 params.granularity = arguments[2 + extraArgs];
5199 params.coarse = arguments[3 + extraArgs];
5200 resultStruct = arguments[4 + extraArgs];
5201 extraArgs += 3;
5202 }
5203#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005204 // bias
5205 if (bias) {
5206 params.bias = arguments[2 + extraArgs];
5207 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005208 }
John Kessenichfc51d282015-08-19 13:34:18 -06005209
John Kessenicha28f7a72019-08-06 07:00:58 -06005210#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005211 if (imageFootprint) {
5212 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5213 builder.addCapability(spv::CapabilityImageFootprintNV);
5214
5215
5216 //resultStructType(OpenGL type) contains 5 elements:
5217 //struct gl_TextureFootprint2DNV {
5218 // uvec2 anchor;
5219 // uvec2 offset;
5220 // uvec2 mask;
5221 // uint lod;
5222 // uint granularity;
5223 //};
5224 //or
5225 //struct gl_TextureFootprint3DNV {
5226 // uvec3 anchor;
5227 // uvec3 offset;
5228 // uvec2 mask;
5229 // uint lod;
5230 // uint granularity;
5231 //};
5232 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5233 assert(builder.isStructType(resultStructType));
5234
5235 //resType (SPIR-V type) contains 6 elements:
5236 //Member 0 must be a Boolean type scalar(LOD),
5237 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5238 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5239 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5240 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5241 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5242 std::vector<spv::Id> members;
5243 members.push_back(resultType());
5244 for (int i = 0; i < 5; i++) {
5245 members.push_back(builder.getContainedTypeId(resultStructType, i));
5246 }
5247 spv::Id resType = builder.makeStructType(members, "ResType");
5248
5249 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005250 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5251 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005252
5253 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5254 for (int i = 0; i < 5; i++) {
5255 builder.clearAccessChain();
5256 builder.setAccessChainLValue(resultStruct);
5257
5258 //Accessing to a struct we created, no coherent flag is set
5259 spv::Builder::AccessChain::CoherentFlags flags;
5260 flags.clear();
5261
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005262 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005263 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02005264 i+1), TranslateNonUniformDecoration(imageType.getQualifier()));
Chao Chen3a137962018-09-19 11:41:27 -07005265 }
5266 return builder.createCompositeExtract(res, resultType(), 0);
5267 }
5268#endif
5269
John Kessenich65336482016-06-16 14:06:26 -06005270 // projective component (might not to move)
5271 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5272 // are divided by the last component of P."
5273 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5274 // unused components will appear after all used components."
5275 if (cracked.proj) {
5276 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5277 int projTargetComp;
5278 switch (sampler.dim) {
5279 case glslang::Esd1D: projTargetComp = 1; break;
5280 case glslang::Esd2D: projTargetComp = 2; break;
5281 case glslang::EsdRect: projTargetComp = 2; break;
5282 default: projTargetComp = projSourceComp; break;
5283 }
5284 // copy the projective coordinate if we have to
5285 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005286 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005287 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005288 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005289 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005290 }
5291 }
5292
John Kessenichf8d1d742019-10-21 06:55:11 -06005293#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005294 // nonprivate
5295 if (imageType.getQualifier().nonprivate) {
5296 params.nonprivate = true;
5297 }
5298
5299 // volatile
5300 if (imageType.getQualifier().volatil) {
5301 params.volatil = true;
5302 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005303#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005304
St0fFa1184dd2018-04-09 21:08:14 +02005305 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005306 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5307 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005308 );
LoopDawg4425f242018-02-18 11:40:01 -07005309
5310 if (components != node->getType().getVectorSize())
5311 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5312
5313 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005314}
5315
5316spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5317{
5318 // Grab the function's pointer from the previously created function
5319 spv::Function* function = functionMap[node->getName().c_str()];
5320 if (! function)
5321 return 0;
5322
5323 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5324 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5325
5326 // See comments in makeFunctions() for details about the semantics for parameter passing.
5327 //
5328 // These imply we need a four step process:
5329 // 1. Evaluate the arguments
5330 // 2. Allocate and make copies of in, out, and inout arguments
5331 // 3. Make the call
5332 // 4. Copy back the results
5333
John Kessenichd3ed90b2018-05-04 11:43:03 -06005334 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005335 std::vector<spv::Builder::AccessChain> lValues;
5336 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005337 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005338 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005339 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005340 // build l-value
5341 builder.clearAccessChain();
5342 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005343 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005344 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005345 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005346 // save l-value
5347 lValues.push_back(builder.getAccessChain());
5348 } else {
5349 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005350 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005351 }
5352 }
5353
5354 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5355 // copy the original into that space.
5356 //
5357 // Also, build up the list of actual arguments to pass in for the call
5358 int lValueCount = 0;
5359 int rValueCount = 0;
5360 std::vector<spv::Id> spvArgs;
5361 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5362 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005363 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005364 builder.setAccessChain(lValues[lValueCount]);
5365 arg = builder.accessChainGetLValue();
5366 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005367 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005368 // need space to hold the copy
John Kessenich435dd802020-06-30 01:27:08 -06005369 arg = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction,
John Kessenich8985fc92020-03-03 10:25:07 -07005370 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005371 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5372 // need to copy the input into output space
5373 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005374 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005375 builder.clearAccessChain();
5376 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005377 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005378 }
5379 ++lValueCount;
5380 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005381 // process r-value, which involves a copy for a type mismatch
John Kessenich4df10332020-06-26 08:37:06 -06005382 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a]) ||
John Kessenich435dd802020-06-30 01:27:08 -06005383 TranslatePrecisionDecoration(*argTypes[a]) != function->getParamPrecision(a))
John Kessenich4df10332020-06-26 08:37:06 -06005384 {
John Kessenich435dd802020-06-30 01:27:08 -06005385 spv::Id argCopy = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction, function->getParamType(a), "arg");
John Kessenichd3ed90b2018-05-04 11:43:03 -06005386 builder.clearAccessChain();
5387 builder.setAccessChainLValue(argCopy);
5388 multiTypeStore(*argTypes[a], rValues[rValueCount]);
John Kessenich435dd802020-06-30 01:27:08 -06005389 arg = builder.createLoad(argCopy, function->getParamPrecision(a));
John Kessenichd3ed90b2018-05-04 11:43:03 -06005390 } else
5391 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005392 ++rValueCount;
5393 }
5394 spvArgs.push_back(arg);
5395 }
5396
5397 // 3. Make the call.
5398 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005399 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005400
5401 // 4. Copy back out an "out" arguments.
5402 lValueCount = 0;
5403 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005404 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005405 ++lValueCount;
5406 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005407 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
John Kessenich435dd802020-06-30 01:27:08 -06005408 spv::Id copy = builder.createLoad(spvArgs[a], spv::NoPrecision);
John Kessenich140f3df2015-06-26 16:58:36 -06005409 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005410 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005411 }
5412 ++lValueCount;
5413 }
5414 }
5415
5416 return result;
5417}
5418
5419// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005420spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005421 spv::Id typeId, spv::Id left, spv::Id right,
5422 glslang::TBasicType typeProxy, bool reduceComparison)
5423{
John Kessenich66011cb2018-03-06 16:12:04 -07005424 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5425 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005426 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005427
5428 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005429 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005430 bool comparison = false;
5431
5432 switch (op) {
5433 case glslang::EOpAdd:
5434 case glslang::EOpAddAssign:
5435 if (isFloat)
5436 binOp = spv::OpFAdd;
5437 else
5438 binOp = spv::OpIAdd;
5439 break;
5440 case glslang::EOpSub:
5441 case glslang::EOpSubAssign:
5442 if (isFloat)
5443 binOp = spv::OpFSub;
5444 else
5445 binOp = spv::OpISub;
5446 break;
5447 case glslang::EOpMul:
5448 case glslang::EOpMulAssign:
5449 if (isFloat)
5450 binOp = spv::OpFMul;
5451 else
5452 binOp = spv::OpIMul;
5453 break;
5454 case glslang::EOpVectorTimesScalar:
5455 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005456 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005457 if (builder.isVector(right))
5458 std::swap(left, right);
5459 assert(builder.isScalar(right));
5460 needMatchingVectors = false;
5461 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005462 } else if (isFloat)
5463 binOp = spv::OpFMul;
5464 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005465 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005466 break;
5467 case glslang::EOpVectorTimesMatrix:
5468 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005469 binOp = spv::OpVectorTimesMatrix;
5470 break;
5471 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005472 binOp = spv::OpMatrixTimesVector;
5473 break;
5474 case glslang::EOpMatrixTimesScalar:
5475 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005476 binOp = spv::OpMatrixTimesScalar;
5477 break;
5478 case glslang::EOpMatrixTimesMatrix:
5479 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005480 binOp = spv::OpMatrixTimesMatrix;
5481 break;
5482 case glslang::EOpOuterProduct:
5483 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005484 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005485 break;
5486
5487 case glslang::EOpDiv:
5488 case glslang::EOpDivAssign:
5489 if (isFloat)
5490 binOp = spv::OpFDiv;
5491 else if (isUnsigned)
5492 binOp = spv::OpUDiv;
5493 else
5494 binOp = spv::OpSDiv;
5495 break;
5496 case glslang::EOpMod:
5497 case glslang::EOpModAssign:
5498 if (isFloat)
5499 binOp = spv::OpFMod;
5500 else if (isUnsigned)
5501 binOp = spv::OpUMod;
5502 else
5503 binOp = spv::OpSMod;
5504 break;
5505 case glslang::EOpRightShift:
5506 case glslang::EOpRightShiftAssign:
5507 if (isUnsigned)
5508 binOp = spv::OpShiftRightLogical;
5509 else
5510 binOp = spv::OpShiftRightArithmetic;
5511 break;
5512 case glslang::EOpLeftShift:
5513 case glslang::EOpLeftShiftAssign:
5514 binOp = spv::OpShiftLeftLogical;
5515 break;
5516 case glslang::EOpAnd:
5517 case glslang::EOpAndAssign:
5518 binOp = spv::OpBitwiseAnd;
5519 break;
5520 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005521 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005522 binOp = spv::OpLogicalAnd;
5523 break;
5524 case glslang::EOpInclusiveOr:
5525 case glslang::EOpInclusiveOrAssign:
5526 binOp = spv::OpBitwiseOr;
5527 break;
5528 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005529 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005530 binOp = spv::OpLogicalOr;
5531 break;
5532 case glslang::EOpExclusiveOr:
5533 case glslang::EOpExclusiveOrAssign:
5534 binOp = spv::OpBitwiseXor;
5535 break;
5536 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005537 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005538 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005539 break;
5540
Ian Romanickb3bd4022019-01-21 08:57:25 -08005541 case glslang::EOpAbsDifference:
5542 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5543 break;
5544
5545 case glslang::EOpAddSaturate:
5546 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5547 break;
5548
5549 case glslang::EOpSubSaturate:
5550 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5551 break;
5552
5553 case glslang::EOpAverage:
5554 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5555 break;
5556
5557 case glslang::EOpAverageRounded:
5558 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5559 break;
5560
5561 case glslang::EOpMul32x16:
5562 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5563 break;
5564
John Kessenich140f3df2015-06-26 16:58:36 -06005565 case glslang::EOpLessThan:
5566 case glslang::EOpGreaterThan:
5567 case glslang::EOpLessThanEqual:
5568 case glslang::EOpGreaterThanEqual:
5569 case glslang::EOpEqual:
5570 case glslang::EOpNotEqual:
5571 case glslang::EOpVectorEqual:
5572 case glslang::EOpVectorNotEqual:
5573 comparison = true;
5574 break;
5575 default:
5576 break;
5577 }
5578
John Kessenich7c1aa102015-10-15 13:29:11 -06005579 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005580 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005581 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005582 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5583 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005584 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005585
5586 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005587 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005588 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005589
qining25262b32016-05-06 17:25:16 -04005590 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005591 decorations.addNoContraction(builder, result);
5592 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005593 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005594 }
5595
5596 if (! comparison)
5597 return 0;
5598
John Kessenich7c1aa102015-10-15 13:29:11 -06005599 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005600
John Kessenich4583b612016-08-07 19:14:22 -06005601 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005602 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5603 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005604 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005605 return result;
5606 }
John Kessenich140f3df2015-06-26 16:58:36 -06005607
5608 switch (op) {
5609 case glslang::EOpLessThan:
5610 if (isFloat)
5611 binOp = spv::OpFOrdLessThan;
5612 else if (isUnsigned)
5613 binOp = spv::OpULessThan;
5614 else
5615 binOp = spv::OpSLessThan;
5616 break;
5617 case glslang::EOpGreaterThan:
5618 if (isFloat)
5619 binOp = spv::OpFOrdGreaterThan;
5620 else if (isUnsigned)
5621 binOp = spv::OpUGreaterThan;
5622 else
5623 binOp = spv::OpSGreaterThan;
5624 break;
5625 case glslang::EOpLessThanEqual:
5626 if (isFloat)
5627 binOp = spv::OpFOrdLessThanEqual;
5628 else if (isUnsigned)
5629 binOp = spv::OpULessThanEqual;
5630 else
5631 binOp = spv::OpSLessThanEqual;
5632 break;
5633 case glslang::EOpGreaterThanEqual:
5634 if (isFloat)
5635 binOp = spv::OpFOrdGreaterThanEqual;
5636 else if (isUnsigned)
5637 binOp = spv::OpUGreaterThanEqual;
5638 else
5639 binOp = spv::OpSGreaterThanEqual;
5640 break;
5641 case glslang::EOpEqual:
5642 case glslang::EOpVectorEqual:
5643 if (isFloat)
5644 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005645 else if (isBool)
5646 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005647 else
5648 binOp = spv::OpIEqual;
5649 break;
5650 case glslang::EOpNotEqual:
5651 case glslang::EOpVectorNotEqual:
5652 if (isFloat)
Graeme Leese65ce5662020-06-05 13:32:51 +01005653 binOp = spv::OpFUnordNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005654 else if (isBool)
5655 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005656 else
5657 binOp = spv::OpINotEqual;
5658 break;
5659 default:
5660 break;
5661 }
5662
qining25262b32016-05-06 17:25:16 -04005663 if (binOp != spv::OpNop) {
5664 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005665 decorations.addNoContraction(builder, result);
5666 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005667 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005668 }
John Kessenich140f3df2015-06-26 16:58:36 -06005669
5670 return 0;
5671}
5672
John Kessenich04bb8a02015-12-12 12:28:14 -07005673//
5674// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5675// These can be any of:
5676//
5677// matrix * scalar
5678// scalar * matrix
5679// matrix * matrix linear algebraic
5680// matrix * vector
5681// vector * matrix
5682// matrix * matrix componentwise
5683// matrix op matrix op in {+, -, /}
5684// matrix op scalar op in {+, -, /}
5685// scalar op matrix op in {+, -, /}
5686//
John Kessenichead86222018-03-28 18:01:20 -06005687spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5688 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005689{
5690 bool firstClass = true;
5691
5692 // First, handle first-class matrix operations (* and matrix/scalar)
5693 switch (op) {
5694 case spv::OpFDiv:
5695 if (builder.isMatrix(left) && builder.isScalar(right)) {
5696 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005697 spv::Id resultType = builder.getTypeId(right);
5698 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005699 op = spv::OpMatrixTimesScalar;
5700 } else
5701 firstClass = false;
5702 break;
5703 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005704 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005705 std::swap(left, right);
5706 assert(builder.isScalar(right));
5707 break;
5708 case spv::OpVectorTimesMatrix:
5709 assert(builder.isVector(left));
5710 assert(builder.isMatrix(right));
5711 break;
5712 case spv::OpMatrixTimesVector:
5713 assert(builder.isMatrix(left));
5714 assert(builder.isVector(right));
5715 break;
5716 case spv::OpMatrixTimesMatrix:
5717 assert(builder.isMatrix(left));
5718 assert(builder.isMatrix(right));
5719 break;
5720 default:
5721 firstClass = false;
5722 break;
5723 }
5724
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005725 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5726 firstClass = true;
5727
qining25262b32016-05-06 17:25:16 -04005728 if (firstClass) {
5729 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005730 decorations.addNoContraction(builder, result);
5731 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005732 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005733 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005734
LoopDawg592860c2016-06-09 08:57:35 -06005735 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005736 // The result type of all of them is the same type as the (a) matrix operand.
5737 // The algorithm is to:
5738 // - break the matrix(es) into vectors
5739 // - smear any scalar to a vector
5740 // - do vector operations
5741 // - make a matrix out the vector results
5742 switch (op) {
5743 case spv::OpFAdd:
5744 case spv::OpFSub:
5745 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005746 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005747 case spv::OpFMul:
5748 {
5749 // one time set up...
5750 bool leftMat = builder.isMatrix(left);
5751 bool rightMat = builder.isMatrix(right);
5752 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5753 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5754 spv::Id scalarType = builder.getScalarTypeId(typeId);
5755 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5756 std::vector<spv::Id> results;
5757 spv::Id smearVec = spv::NoResult;
5758 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005759 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005760 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005761 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005762
5763 // do each vector op
5764 for (unsigned int c = 0; c < numCols; ++c) {
5765 std::vector<unsigned int> indexes;
5766 indexes.push_back(c);
5767 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5768 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005769 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005770 decorations.addNoContraction(builder, result);
5771 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005772 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005773 }
5774
5775 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005776 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005777 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005778 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005779 }
5780 default:
5781 assert(0);
5782 return spv::NoResult;
5783 }
5784}
5785
John Kessenichead86222018-03-28 18:01:20 -06005786spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005787 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005788{
5789 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005790 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005791 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005792 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5793 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005794
5795 switch (op) {
5796 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005797 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005798 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005799 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005800 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005801 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005802 unaryOp = spv::OpSNegate;
5803 break;
5804
5805 case glslang::EOpLogicalNot:
5806 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005807 unaryOp = spv::OpLogicalNot;
5808 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005809 case glslang::EOpBitwiseNot:
5810 unaryOp = spv::OpNot;
5811 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005812
John Kessenich140f3df2015-06-26 16:58:36 -06005813 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005814 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005815 break;
5816 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005817 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005818 break;
5819 case glslang::EOpTranspose:
5820 unaryOp = spv::OpTranspose;
5821 break;
5822
5823 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005824 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005825 break;
5826 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005827 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005828 break;
5829 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005830 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005831 break;
5832 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005833 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005834 break;
5835 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005836 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005837 break;
5838 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005839 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005840 break;
5841 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005842 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005843 break;
5844 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005845 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005846 break;
5847
5848 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005849 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005850 break;
5851 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005852 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005853 break;
5854 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005855 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005856 break;
5857 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005858 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005859 break;
5860 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005861 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005862 break;
5863 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005864 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005865 break;
5866
5867 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005868 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005869 break;
5870 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005871 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005872 break;
5873
5874 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005875 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005876 break;
5877 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005878 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005879 break;
5880 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005881 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005882 break;
5883 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005884 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005885 break;
5886 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005887 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005888 break;
5889 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005890 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005891 break;
5892
5893 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005894 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005895 break;
5896 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005897 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005898 break;
5899 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005900 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005901 break;
5902 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005903 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005904 break;
5905 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005906 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005907 break;
5908 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005909 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005910 break;
5911
5912 case glslang::EOpIsNan:
5913 unaryOp = spv::OpIsNan;
5914 break;
5915 case glslang::EOpIsInf:
5916 unaryOp = spv::OpIsInf;
5917 break;
LoopDawg592860c2016-06-09 08:57:35 -06005918 case glslang::EOpIsFinite:
5919 unaryOp = spv::OpIsFinite;
5920 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005921
Rex Xucbc426e2015-12-15 16:03:10 +08005922 case glslang::EOpFloatBitsToInt:
5923 case glslang::EOpFloatBitsToUint:
5924 case glslang::EOpIntBitsToFloat:
5925 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005926 case glslang::EOpDoubleBitsToInt64:
5927 case glslang::EOpDoubleBitsToUint64:
5928 case glslang::EOpInt64BitsToDouble:
5929 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005930 case glslang::EOpFloat16BitsToInt16:
5931 case glslang::EOpFloat16BitsToUint16:
5932 case glslang::EOpInt16BitsToFloat16:
5933 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005934 unaryOp = spv::OpBitcast;
5935 break;
5936
John Kessenich140f3df2015-06-26 16:58:36 -06005937 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005938 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005939 break;
5940 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005941 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005942 break;
5943 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005944 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005945 break;
5946 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005947 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005948 break;
5949 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005950 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005951 break;
5952 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005953 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005954 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005955#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005956 case glslang::EOpPackSnorm4x8:
5957 libCall = spv::GLSLstd450PackSnorm4x8;
5958 break;
5959 case glslang::EOpUnpackSnorm4x8:
5960 libCall = spv::GLSLstd450UnpackSnorm4x8;
5961 break;
5962 case glslang::EOpPackUnorm4x8:
5963 libCall = spv::GLSLstd450PackUnorm4x8;
5964 break;
5965 case glslang::EOpUnpackUnorm4x8:
5966 libCall = spv::GLSLstd450UnpackUnorm4x8;
5967 break;
5968 case glslang::EOpPackDouble2x32:
5969 libCall = spv::GLSLstd450PackDouble2x32;
5970 break;
5971 case glslang::EOpUnpackDouble2x32:
5972 libCall = spv::GLSLstd450UnpackDouble2x32;
5973 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005974#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005975
Rex Xu8ff43de2016-04-22 16:51:45 +08005976 case glslang::EOpPackInt2x32:
5977 case glslang::EOpUnpackInt2x32:
5978 case glslang::EOpPackUint2x32:
5979 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005980 case glslang::EOpPack16:
5981 case glslang::EOpPack32:
5982 case glslang::EOpPack64:
5983 case glslang::EOpUnpack32:
5984 case glslang::EOpUnpack16:
5985 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005986 case glslang::EOpPackInt2x16:
5987 case glslang::EOpUnpackInt2x16:
5988 case glslang::EOpPackUint2x16:
5989 case glslang::EOpUnpackUint2x16:
5990 case glslang::EOpPackInt4x16:
5991 case glslang::EOpUnpackInt4x16:
5992 case glslang::EOpPackUint4x16:
5993 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005994 case glslang::EOpPackFloat2x16:
5995 case glslang::EOpUnpackFloat2x16:
5996 unaryOp = spv::OpBitcast;
5997 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005998
John Kessenich140f3df2015-06-26 16:58:36 -06005999 case glslang::EOpDPdx:
6000 unaryOp = spv::OpDPdx;
6001 break;
6002 case glslang::EOpDPdy:
6003 unaryOp = spv::OpDPdy;
6004 break;
6005 case glslang::EOpFwidth:
6006 unaryOp = spv::OpFwidth;
6007 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006008
John Kessenich140f3df2015-06-26 16:58:36 -06006009 case glslang::EOpAny:
6010 unaryOp = spv::OpAny;
6011 break;
6012 case glslang::EOpAll:
6013 unaryOp = spv::OpAll;
6014 break;
6015
6016 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06006017 if (isFloat)
6018 libCall = spv::GLSLstd450FAbs;
6019 else
6020 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06006021 break;
6022 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06006023 if (isFloat)
6024 libCall = spv::GLSLstd450FSign;
6025 else
6026 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06006027 break;
6028
John Kessenicha28f7a72019-08-06 07:00:58 -06006029#ifndef GLSLANG_WEB
6030 case glslang::EOpDPdxFine:
6031 unaryOp = spv::OpDPdxFine;
6032 break;
6033 case glslang::EOpDPdyFine:
6034 unaryOp = spv::OpDPdyFine;
6035 break;
6036 case glslang::EOpFwidthFine:
6037 unaryOp = spv::OpFwidthFine;
6038 break;
6039 case glslang::EOpDPdxCoarse:
6040 unaryOp = spv::OpDPdxCoarse;
6041 break;
6042 case glslang::EOpDPdyCoarse:
6043 unaryOp = spv::OpDPdyCoarse;
6044 break;
6045 case glslang::EOpFwidthCoarse:
6046 unaryOp = spv::OpFwidthCoarse;
6047 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04006048 case glslang::EOpRayQueryProceed:
6049 unaryOp = spv::OpRayQueryProceedKHR;
6050 break;
6051 case glslang::EOpRayQueryGetRayTMin:
6052 unaryOp = spv::OpRayQueryGetRayTMinKHR;
6053 break;
6054 case glslang::EOpRayQueryGetRayFlags:
6055 unaryOp = spv::OpRayQueryGetRayFlagsKHR;
6056 break;
6057 case glslang::EOpRayQueryGetWorldRayOrigin:
6058 unaryOp = spv::OpRayQueryGetWorldRayOriginKHR;
6059 break;
6060 case glslang::EOpRayQueryGetWorldRayDirection:
6061 unaryOp = spv::OpRayQueryGetWorldRayDirectionKHR;
6062 break;
6063 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
6064 unaryOp = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
6065 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006066 case glslang::EOpInterpolateAtCentroid:
6067 if (typeProxy == glslang::EbtFloat16)
6068 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6069 libCall = spv::GLSLstd450InterpolateAtCentroid;
6070 break;
John Kessenichfc51d282015-08-19 13:34:18 -06006071 case glslang::EOpAtomicCounterIncrement:
6072 case glslang::EOpAtomicCounterDecrement:
6073 case glslang::EOpAtomicCounter:
6074 {
6075 // Handle all of the atomics in one place, in createAtomicOperation()
6076 std::vector<spv::Id> operands;
6077 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006078 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06006079 }
6080
John Kessenichfc51d282015-08-19 13:34:18 -06006081 case glslang::EOpBitFieldReverse:
6082 unaryOp = spv::OpBitReverse;
6083 break;
6084 case glslang::EOpBitCount:
6085 unaryOp = spv::OpBitCount;
6086 break;
6087 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006088 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006089 break;
6090 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006091 if (isUnsigned)
6092 libCall = spv::GLSLstd450FindUMsb;
6093 else
6094 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006095 break;
6096
Ian Romanickb3bd4022019-01-21 08:57:25 -08006097 case glslang::EOpCountLeadingZeros:
6098 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6099 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6100 unaryOp = spv::OpUCountLeadingZerosINTEL;
6101 break;
6102
6103 case glslang::EOpCountTrailingZeros:
6104 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6105 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6106 unaryOp = spv::OpUCountTrailingZerosINTEL;
6107 break;
6108
Rex Xu574ab042016-04-14 16:53:07 +08006109 case glslang::EOpBallot:
6110 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006111 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006112 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08006113 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08006114 case glslang::EOpMinInvocations:
6115 case glslang::EOpMaxInvocations:
6116 case glslang::EOpAddInvocations:
6117 case glslang::EOpMinInvocationsNonUniform:
6118 case glslang::EOpMaxInvocationsNonUniform:
6119 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006120 case glslang::EOpMinInvocationsInclusiveScan:
6121 case glslang::EOpMaxInvocationsInclusiveScan:
6122 case glslang::EOpAddInvocationsInclusiveScan:
6123 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6124 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6125 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6126 case glslang::EOpMinInvocationsExclusiveScan:
6127 case glslang::EOpMaxInvocationsExclusiveScan:
6128 case glslang::EOpAddInvocationsExclusiveScan:
6129 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6130 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6131 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08006132 {
6133 std::vector<spv::Id> operands;
6134 operands.push_back(operand);
6135 return createInvocationsOperation(op, typeId, operands, typeProxy);
6136 }
John Kessenich66011cb2018-03-06 16:12:04 -07006137 case glslang::EOpSubgroupAll:
6138 case glslang::EOpSubgroupAny:
6139 case glslang::EOpSubgroupAllEqual:
6140 case glslang::EOpSubgroupBroadcastFirst:
6141 case glslang::EOpSubgroupBallot:
6142 case glslang::EOpSubgroupInverseBallot:
6143 case glslang::EOpSubgroupBallotBitCount:
6144 case glslang::EOpSubgroupBallotInclusiveBitCount:
6145 case glslang::EOpSubgroupBallotExclusiveBitCount:
6146 case glslang::EOpSubgroupBallotFindLSB:
6147 case glslang::EOpSubgroupBallotFindMSB:
6148 case glslang::EOpSubgroupAdd:
6149 case glslang::EOpSubgroupMul:
6150 case glslang::EOpSubgroupMin:
6151 case glslang::EOpSubgroupMax:
6152 case glslang::EOpSubgroupAnd:
6153 case glslang::EOpSubgroupOr:
6154 case glslang::EOpSubgroupXor:
6155 case glslang::EOpSubgroupInclusiveAdd:
6156 case glslang::EOpSubgroupInclusiveMul:
6157 case glslang::EOpSubgroupInclusiveMin:
6158 case glslang::EOpSubgroupInclusiveMax:
6159 case glslang::EOpSubgroupInclusiveAnd:
6160 case glslang::EOpSubgroupInclusiveOr:
6161 case glslang::EOpSubgroupInclusiveXor:
6162 case glslang::EOpSubgroupExclusiveAdd:
6163 case glslang::EOpSubgroupExclusiveMul:
6164 case glslang::EOpSubgroupExclusiveMin:
6165 case glslang::EOpSubgroupExclusiveMax:
6166 case glslang::EOpSubgroupExclusiveAnd:
6167 case glslang::EOpSubgroupExclusiveOr:
6168 case glslang::EOpSubgroupExclusiveXor:
6169 case glslang::EOpSubgroupQuadSwapHorizontal:
6170 case glslang::EOpSubgroupQuadSwapVertical:
6171 case glslang::EOpSubgroupQuadSwapDiagonal: {
6172 std::vector<spv::Id> operands;
6173 operands.push_back(operand);
6174 return createSubgroupOperation(op, typeId, operands, typeProxy);
6175 }
Rex Xu9d93a232016-05-05 12:30:44 +08006176 case glslang::EOpMbcnt:
6177 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6178 libCall = spv::MbcntAMD;
6179 break;
6180
6181 case glslang::EOpCubeFaceIndex:
6182 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6183 libCall = spv::CubeFaceIndexAMD;
6184 break;
6185
6186 case glslang::EOpCubeFaceCoord:
6187 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6188 libCall = spv::CubeFaceCoordAMD;
6189 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006190 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006191 unaryOp = spv::OpGroupNonUniformPartitionNV;
6192 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006193 case glslang::EOpConstructReference:
6194 unaryOp = spv::OpBitcast;
6195 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006196#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006197
6198 case glslang::EOpCopyObject:
6199 unaryOp = spv::OpCopyObject;
6200 break;
6201
John Kessenich140f3df2015-06-26 16:58:36 -06006202 default:
6203 return 0;
6204 }
6205
6206 spv::Id id;
6207 if (libCall >= 0) {
6208 std::vector<spv::Id> args;
6209 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006210 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006211 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006212 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006213 }
John Kessenich140f3df2015-06-26 16:58:36 -06006214
John Kessenichb9197c82019-08-11 07:41:45 -06006215 decorations.addNoContraction(builder, id);
6216 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006217 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006218}
6219
John Kessenich7a53f762016-01-20 11:19:27 -07006220// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006221spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6222 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006223{
6224 // Handle unary operations vector by vector.
6225 // The result type is the same type as the original type.
6226 // The algorithm is to:
6227 // - break the matrix into vectors
6228 // - apply the operation to each vector
6229 // - make a matrix out the vector results
6230
6231 // get the types sorted out
6232 int numCols = builder.getNumColumns(operand);
6233 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006234 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6235 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006236 std::vector<spv::Id> results;
6237
6238 // do each vector op
6239 for (int c = 0; c < numCols; ++c) {
6240 std::vector<unsigned int> indexes;
6241 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006242 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6243 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006244 decorations.addNoContraction(builder, destVec);
6245 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006246 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006247 }
6248
6249 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006250 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006251 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006252 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006253}
6254
John Kessenichad7645f2018-06-04 19:11:25 -06006255// For converting integers where both the bitwidth and the signedness could
6256// change, but only do the width change here. The caller is still responsible
6257// for the signedness conversion.
6258spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006259{
John Kessenichad7645f2018-06-04 19:11:25 -06006260 // Get the result type width, based on the type to convert to.
6261 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006262 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006263 case glslang::EOpConvInt16ToUint8:
6264 case glslang::EOpConvIntToUint8:
6265 case glslang::EOpConvInt64ToUint8:
6266 case glslang::EOpConvUint16ToInt8:
6267 case glslang::EOpConvUintToInt8:
6268 case glslang::EOpConvUint64ToInt8:
6269 width = 8;
6270 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006271 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006272 case glslang::EOpConvIntToUint16:
6273 case glslang::EOpConvInt64ToUint16:
6274 case glslang::EOpConvUint8ToInt16:
6275 case glslang::EOpConvUintToInt16:
6276 case glslang::EOpConvUint64ToInt16:
6277 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006278 break;
6279 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006280 case glslang::EOpConvInt16ToUint:
6281 case glslang::EOpConvInt64ToUint:
6282 case glslang::EOpConvUint8ToInt:
6283 case glslang::EOpConvUint16ToInt:
6284 case glslang::EOpConvUint64ToInt:
6285 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006286 break;
6287 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006288 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006289 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006290 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006291 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006292 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006293 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006294 break;
6295
6296 default:
6297 assert(false && "Default missing");
6298 break;
6299 }
6300
John Kessenichad7645f2018-06-04 19:11:25 -06006301 // Get the conversion operation and result type,
6302 // based on the target width, but the source type.
6303 spv::Id type = spv::NoType;
6304 spv::Op convOp = spv::OpNop;
6305 switch(op) {
6306 case glslang::EOpConvInt8ToUint16:
6307 case glslang::EOpConvInt8ToUint:
6308 case glslang::EOpConvInt8ToUint64:
6309 case glslang::EOpConvInt16ToUint8:
6310 case glslang::EOpConvInt16ToUint:
6311 case glslang::EOpConvInt16ToUint64:
6312 case glslang::EOpConvIntToUint8:
6313 case glslang::EOpConvIntToUint16:
6314 case glslang::EOpConvIntToUint64:
6315 case glslang::EOpConvInt64ToUint8:
6316 case glslang::EOpConvInt64ToUint16:
6317 case glslang::EOpConvInt64ToUint:
6318 convOp = spv::OpSConvert;
6319 type = builder.makeIntType(width);
6320 break;
6321 default:
6322 convOp = spv::OpUConvert;
6323 type = builder.makeUintType(width);
6324 break;
6325 }
6326
John Kessenich66011cb2018-03-06 16:12:04 -07006327 if (vectorSize > 0)
6328 type = builder.makeVectorType(type, vectorSize);
6329
John Kessenichad7645f2018-06-04 19:11:25 -06006330 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006331}
6332
John Kessenichead86222018-03-28 18:01:20 -06006333spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6334 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006335{
6336 spv::Op convOp = spv::OpNop;
6337 spv::Id zero = 0;
6338 spv::Id one = 0;
6339
6340 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6341
6342 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006343 case glslang::EOpConvIntToBool:
6344 case glslang::EOpConvUintToBool:
6345 zero = builder.makeUintConstant(0);
6346 zero = makeSmearedConstant(zero, vectorSize);
6347 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006348 case glslang::EOpConvFloatToBool:
6349 zero = builder.makeFloatConstant(0.0F);
6350 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006351 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006352 case glslang::EOpConvBoolToFloat:
6353 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006354 zero = builder.makeFloatConstant(0.0F);
6355 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006356 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006357
John Kessenich140f3df2015-06-26 16:58:36 -06006358 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006359 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006360#ifndef GLSLANG_WEB
6361 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006362 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006363 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006364 } else
6365#endif
6366 {
6367 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006368 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006369 }
Rex Xucabbb782017-03-24 13:41:14 +08006370
John Kessenich140f3df2015-06-26 16:58:36 -06006371 convOp = spv::OpSelect;
6372 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006373
John Kessenich140f3df2015-06-26 16:58:36 -06006374 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006375 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006376#ifndef GLSLANG_WEB
6377 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006378 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006379 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006380 } else
6381#endif
6382 {
6383 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006384 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006385 }
Rex Xucabbb782017-03-24 13:41:14 +08006386
John Kessenich140f3df2015-06-26 16:58:36 -06006387 convOp = spv::OpSelect;
6388 break;
6389
John Kessenich66011cb2018-03-06 16:12:04 -07006390 case glslang::EOpConvInt8ToFloat16:
6391 case glslang::EOpConvInt8ToFloat:
6392 case glslang::EOpConvInt8ToDouble:
6393 case glslang::EOpConvInt16ToFloat16:
6394 case glslang::EOpConvInt16ToFloat:
6395 case glslang::EOpConvInt16ToDouble:
6396 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006397 case glslang::EOpConvIntToFloat:
6398 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006399 case glslang::EOpConvInt64ToFloat:
6400 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006401 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006402 convOp = spv::OpConvertSToF;
6403 break;
6404
John Kessenich66011cb2018-03-06 16:12:04 -07006405 case glslang::EOpConvUint8ToFloat16:
6406 case glslang::EOpConvUint8ToFloat:
6407 case glslang::EOpConvUint8ToDouble:
6408 case glslang::EOpConvUint16ToFloat16:
6409 case glslang::EOpConvUint16ToFloat:
6410 case glslang::EOpConvUint16ToDouble:
6411 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006412 case glslang::EOpConvUintToFloat:
6413 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006414 case glslang::EOpConvUint64ToFloat:
6415 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006416 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006417 convOp = spv::OpConvertUToF;
6418 break;
6419
John Kessenich66011cb2018-03-06 16:12:04 -07006420 case glslang::EOpConvFloat16ToInt8:
6421 case glslang::EOpConvFloatToInt8:
6422 case glslang::EOpConvDoubleToInt8:
6423 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006424 case glslang::EOpConvFloatToInt16:
6425 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006426 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006427 case glslang::EOpConvFloatToInt:
6428 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006429 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006430 case glslang::EOpConvFloatToInt64:
6431 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006432 convOp = spv::OpConvertFToS;
6433 break;
6434
John Kessenich66011cb2018-03-06 16:12:04 -07006435 case glslang::EOpConvUint8ToInt8:
6436 case glslang::EOpConvInt8ToUint8:
6437 case glslang::EOpConvUint16ToInt16:
6438 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006439 case glslang::EOpConvUintToInt:
6440 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006441 case glslang::EOpConvUint64ToInt64:
6442 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006443 if (builder.isInSpecConstCodeGenMode()) {
6444 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006445#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006446 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6447 zero = builder.makeUint8Constant(0);
6448 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006449 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006450 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6451 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006452 } else
6453#endif
6454 {
Rex Xucabbb782017-03-24 13:41:14 +08006455 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006456 }
qining189b2032016-04-12 23:16:20 -04006457 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006458 // Use OpIAdd, instead of OpBitcast to do the conversion when
6459 // generating for OpSpecConstantOp instruction.
6460 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6461 }
6462 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006463 convOp = spv::OpBitcast;
6464 break;
6465
John Kessenich66011cb2018-03-06 16:12:04 -07006466 case glslang::EOpConvFloat16ToUint8:
6467 case glslang::EOpConvFloatToUint8:
6468 case glslang::EOpConvDoubleToUint8:
6469 case glslang::EOpConvFloat16ToUint16:
6470 case glslang::EOpConvFloatToUint16:
6471 case glslang::EOpConvDoubleToUint16:
6472 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006473 case glslang::EOpConvFloatToUint:
6474 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006475 case glslang::EOpConvFloatToUint64:
6476 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006477 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006478 convOp = spv::OpConvertFToU;
6479 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006480
John Kessenich39697cd2019-08-08 10:35:51 -06006481#ifndef GLSLANG_WEB
6482 case glslang::EOpConvInt8ToBool:
6483 case glslang::EOpConvUint8ToBool:
6484 zero = builder.makeUint8Constant(0);
6485 zero = makeSmearedConstant(zero, vectorSize);
6486 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6487 case glslang::EOpConvInt16ToBool:
6488 case glslang::EOpConvUint16ToBool:
6489 zero = builder.makeUint16Constant(0);
6490 zero = makeSmearedConstant(zero, vectorSize);
6491 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6492 case glslang::EOpConvInt64ToBool:
6493 case glslang::EOpConvUint64ToBool:
6494 zero = builder.makeUint64Constant(0);
6495 zero = makeSmearedConstant(zero, vectorSize);
6496 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6497 case glslang::EOpConvDoubleToBool:
6498 zero = builder.makeDoubleConstant(0.0);
6499 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006500 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006501 case glslang::EOpConvFloat16ToBool:
6502 zero = builder.makeFloat16Constant(0.0F);
6503 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006504 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006505 case glslang::EOpConvBoolToDouble:
6506 convOp = spv::OpSelect;
6507 zero = builder.makeDoubleConstant(0.0);
6508 one = builder.makeDoubleConstant(1.0);
6509 break;
6510 case glslang::EOpConvBoolToFloat16:
6511 convOp = spv::OpSelect;
6512 zero = builder.makeFloat16Constant(0.0F);
6513 one = builder.makeFloat16Constant(1.0F);
6514 break;
6515 case glslang::EOpConvBoolToInt8:
6516 zero = builder.makeInt8Constant(0);
6517 one = builder.makeInt8Constant(1);
6518 convOp = spv::OpSelect;
6519 break;
6520 case glslang::EOpConvBoolToUint8:
6521 zero = builder.makeUint8Constant(0);
6522 one = builder.makeUint8Constant(1);
6523 convOp = spv::OpSelect;
6524 break;
6525 case glslang::EOpConvBoolToInt16:
6526 zero = builder.makeInt16Constant(0);
6527 one = builder.makeInt16Constant(1);
6528 convOp = spv::OpSelect;
6529 break;
6530 case glslang::EOpConvBoolToUint16:
6531 zero = builder.makeUint16Constant(0);
6532 one = builder.makeUint16Constant(1);
6533 convOp = spv::OpSelect;
6534 break;
6535 case glslang::EOpConvDoubleToFloat:
6536 case glslang::EOpConvFloatToDouble:
6537 case glslang::EOpConvDoubleToFloat16:
6538 case glslang::EOpConvFloat16ToDouble:
6539 case glslang::EOpConvFloatToFloat16:
6540 case glslang::EOpConvFloat16ToFloat:
6541 convOp = spv::OpFConvert;
6542 if (builder.isMatrixType(destType))
6543 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6544 break;
6545
John Kessenich66011cb2018-03-06 16:12:04 -07006546 case glslang::EOpConvInt8ToInt16:
6547 case glslang::EOpConvInt8ToInt:
6548 case glslang::EOpConvInt8ToInt64:
6549 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006550 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006551 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006552 case glslang::EOpConvIntToInt8:
6553 case glslang::EOpConvIntToInt16:
6554 case glslang::EOpConvIntToInt64:
6555 case glslang::EOpConvInt64ToInt8:
6556 case glslang::EOpConvInt64ToInt16:
6557 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006558 convOp = spv::OpSConvert;
6559 break;
6560
John Kessenich66011cb2018-03-06 16:12:04 -07006561 case glslang::EOpConvUint8ToUint16:
6562 case glslang::EOpConvUint8ToUint:
6563 case glslang::EOpConvUint8ToUint64:
6564 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006565 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006566 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006567 case glslang::EOpConvUintToUint8:
6568 case glslang::EOpConvUintToUint16:
6569 case glslang::EOpConvUintToUint64:
6570 case glslang::EOpConvUint64ToUint8:
6571 case glslang::EOpConvUint64ToUint16:
6572 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006573 convOp = spv::OpUConvert;
6574 break;
6575
John Kessenich66011cb2018-03-06 16:12:04 -07006576 case glslang::EOpConvInt8ToUint16:
6577 case glslang::EOpConvInt8ToUint:
6578 case glslang::EOpConvInt8ToUint64:
6579 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006580 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006581 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006582 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006583 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006584 case glslang::EOpConvIntToUint64:
6585 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006586 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006587 case glslang::EOpConvInt64ToUint:
6588 case glslang::EOpConvUint8ToInt16:
6589 case glslang::EOpConvUint8ToInt:
6590 case glslang::EOpConvUint8ToInt64:
6591 case glslang::EOpConvUint16ToInt8:
6592 case glslang::EOpConvUint16ToInt:
6593 case glslang::EOpConvUint16ToInt64:
6594 case glslang::EOpConvUintToInt8:
6595 case glslang::EOpConvUintToInt16:
6596 case glslang::EOpConvUintToInt64:
6597 case glslang::EOpConvUint64ToInt8:
6598 case glslang::EOpConvUint64ToInt16:
6599 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006600 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006601 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006602
6603 if (builder.isInSpecConstCodeGenMode()) {
6604 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006605 switch(op) {
6606 case glslang::EOpConvInt16ToUint8:
6607 case glslang::EOpConvIntToUint8:
6608 case glslang::EOpConvInt64ToUint8:
6609 case glslang::EOpConvUint16ToInt8:
6610 case glslang::EOpConvUintToInt8:
6611 case glslang::EOpConvUint64ToInt8:
6612 zero = builder.makeUint8Constant(0);
6613 break;
6614 case glslang::EOpConvInt8ToUint16:
6615 case glslang::EOpConvIntToUint16:
6616 case glslang::EOpConvInt64ToUint16:
6617 case glslang::EOpConvUint8ToInt16:
6618 case glslang::EOpConvUintToInt16:
6619 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006620 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006621 break;
6622 case glslang::EOpConvInt8ToUint:
6623 case glslang::EOpConvInt16ToUint:
6624 case glslang::EOpConvInt64ToUint:
6625 case glslang::EOpConvUint8ToInt:
6626 case glslang::EOpConvUint16ToInt:
6627 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006628 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006629 break;
6630 case glslang::EOpConvInt8ToUint64:
6631 case glslang::EOpConvInt16ToUint64:
6632 case glslang::EOpConvIntToUint64:
6633 case glslang::EOpConvUint8ToInt64:
6634 case glslang::EOpConvUint16ToInt64:
6635 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006636 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006637 break;
6638 default:
6639 assert(false && "Default missing");
6640 break;
6641 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006642 zero = makeSmearedConstant(zero, vectorSize);
6643 // Use OpIAdd, instead of OpBitcast to do the conversion when
6644 // generating for OpSpecConstantOp instruction.
6645 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6646 }
6647 // For normal run-time conversion instruction, use OpBitcast.
6648 convOp = spv::OpBitcast;
6649 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006650 case glslang::EOpConvUint64ToPtr:
6651 convOp = spv::OpConvertUToPtr;
6652 break;
6653 case glslang::EOpConvPtrToUint64:
6654 convOp = spv::OpConvertPtrToU;
6655 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006656 case glslang::EOpConvPtrToUvec2:
6657 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006658 if (builder.isVector(operand))
6659 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6660 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006661 convOp = spv::OpBitcast;
6662 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006663#endif
6664
John Kessenich140f3df2015-06-26 16:58:36 -06006665 default:
6666 break;
6667 }
6668
6669 spv::Id result = 0;
6670 if (convOp == spv::OpNop)
6671 return result;
6672
6673 if (convOp == spv::OpSelect) {
6674 zero = makeSmearedConstant(zero, vectorSize);
6675 one = makeSmearedConstant(one, vectorSize);
6676 result = builder.createTriOp(convOp, destType, operand, one, zero);
6677 } else
6678 result = builder.createUnaryOp(convOp, destType, operand);
6679
John Kessenichead86222018-03-28 18:01:20 -06006680 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006681 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006682 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006683}
6684
6685spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6686{
6687 if (vectorSize == 0)
6688 return constant;
6689
6690 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6691 std::vector<spv::Id> components;
6692 for (int c = 0; c < vectorSize; ++c)
6693 components.push_back(constant);
6694 return builder.makeCompositeConstant(vectorTypeId, components);
6695}
6696
John Kessenich426394d2015-07-23 10:22:48 -06006697// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006698spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6699 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6700 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006701{
6702 spv::Op opCode = spv::OpNop;
6703
6704 switch (op) {
6705 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006706 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006707 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006708 opCode = spv::OpAtomicIAdd;
Vikram Kushwaha79b93922020-07-19 15:45:01 -07006709 if (typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble) {
6710 opCode = spv::OpAtomicFAddEXT;
6711 builder.addExtension(spv::E_SPV_EXT_shader_atomic_float_add);
6712 if (typeProxy == glslang::EbtFloat)
6713 builder.addCapability(spv::CapabilityAtomicFloat32AddEXT);
6714 else
6715 builder.addCapability(spv::CapabilityAtomicFloat64AddEXT);
6716 }
John Kessenich426394d2015-07-23 10:22:48 -06006717 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006718 case glslang::EOpAtomicCounterSubtract:
6719 opCode = spv::OpAtomicISub;
6720 break;
John Kessenich426394d2015-07-23 10:22:48 -06006721 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006722 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006723 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006724 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6725 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006726 break;
6727 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006728 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006729 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006730 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6731 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006732 break;
6733 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006734 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006735 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006736 opCode = spv::OpAtomicAnd;
6737 break;
6738 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006739 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006740 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006741 opCode = spv::OpAtomicOr;
6742 break;
6743 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006744 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006745 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006746 opCode = spv::OpAtomicXor;
6747 break;
6748 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006749 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006750 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006751 opCode = spv::OpAtomicExchange;
6752 break;
6753 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006754 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006755 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006756 opCode = spv::OpAtomicCompareExchange;
6757 break;
6758 case glslang::EOpAtomicCounterIncrement:
6759 opCode = spv::OpAtomicIIncrement;
6760 break;
6761 case glslang::EOpAtomicCounterDecrement:
6762 opCode = spv::OpAtomicIDecrement;
6763 break;
6764 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006765 case glslang::EOpImageAtomicLoad:
6766 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006767 opCode = spv::OpAtomicLoad;
6768 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006769 case glslang::EOpAtomicStore:
6770 case glslang::EOpImageAtomicStore:
6771 opCode = spv::OpAtomicStore;
6772 break;
John Kessenich426394d2015-07-23 10:22:48 -06006773 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006774 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006775 break;
6776 }
6777
Rex Xue8fe8b02017-09-26 15:42:56 +08006778 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6779 builder.addCapability(spv::CapabilityInt64Atomics);
6780
John Kessenich426394d2015-07-23 10:22:48 -06006781 // Sort out the operands
6782 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006783 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006784 // - compare-exchange swaps the value and comparator
6785 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006786 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006787 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6788 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6789 spv::Id scopeId;
6790 if (glslangIntermediate->usingVulkanMemoryModel()) {
6791 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6792 } else {
6793 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6794 }
6795 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006796 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6797 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006798 spv::MemorySemanticsVolatileMask :
6799 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006800 spv::Id semanticsId2 = semanticsId;
6801
6802 pointerId = operands[0];
6803 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6804 // no additional operands
6805 } else if (opCode == spv::OpAtomicCompareExchange) {
6806 compareId = operands[1];
6807 valueId = operands[2];
6808 if (operands.size() > 3) {
6809 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006810 semanticsId = builder.makeUintConstant(
6811 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6812 semanticsId2 = builder.makeUintConstant(
6813 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006814 }
6815 } else if (opCode == spv::OpAtomicLoad) {
6816 if (operands.size() > 1) {
6817 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006818 semanticsId = builder.makeUintConstant(
6819 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006820 }
6821 } else {
6822 // atomic store or RMW
6823 valueId = operands[1];
6824 if (operands.size() > 2) {
6825 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006826 semanticsId = builder.makeUintConstant
6827 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006828 }
Rex Xu04db3f52015-09-16 11:44:02 +08006829 }
John Kessenich426394d2015-07-23 10:22:48 -06006830
Jeff Bolz36831c92018-09-05 10:11:41 -05006831 // Check for capabilities
6832 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006833 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6834 spv::MemorySemanticsMakeVisibleKHRMask |
6835 spv::MemorySemanticsOutputMemoryKHRMask |
6836 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006837 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6838 }
John Kessenich426394d2015-07-23 10:22:48 -06006839
Jeff Bolz36831c92018-09-05 10:11:41 -05006840 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6841 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6842 }
John Kessenich48d6e792017-10-06 21:21:48 -06006843
Jeff Bolz36831c92018-09-05 10:11:41 -05006844 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6845 spvAtomicOperands.push_back(pointerId);
6846 spvAtomicOperands.push_back(scopeId);
6847 spvAtomicOperands.push_back(semanticsId);
6848 if (opCode == spv::OpAtomicCompareExchange) {
6849 spvAtomicOperands.push_back(semanticsId2);
6850 spvAtomicOperands.push_back(valueId);
6851 spvAtomicOperands.push_back(compareId);
6852 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6853 spvAtomicOperands.push_back(valueId);
6854 }
John Kessenich48d6e792017-10-06 21:21:48 -06006855
Jeff Bolz36831c92018-09-05 10:11:41 -05006856 if (opCode == spv::OpAtomicStore) {
6857 builder.createNoResultOp(opCode, spvAtomicOperands);
6858 return 0;
6859 } else {
6860 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6861
6862 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6863 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6864 if (op == glslang::EOpAtomicCounterDecrement)
6865 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6866
6867 return resultId;
6868 }
John Kessenich426394d2015-07-23 10:22:48 -06006869}
6870
John Kessenich91cef522016-05-05 16:45:40 -06006871// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07006872spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
6873 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006874{
John Kessenich66011cb2018-03-06 16:12:04 -07006875 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6876 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006877
Rex Xu51596642016-09-21 18:56:12 +08006878 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006879 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006880 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6881
chaocf200da82016-12-20 12:44:35 -08006882 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6883 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006884 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6885 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006886 } else if (op == glslang::EOpAnyInvocation ||
6887 op == glslang::EOpAllInvocations ||
6888 op == glslang::EOpAllInvocationsEqual) {
6889 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6890 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006891 } else {
6892 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006893 if (op == glslang::EOpMinInvocationsNonUniform ||
6894 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006895 op == glslang::EOpAddInvocationsNonUniform ||
6896 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6897 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6898 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6899 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6900 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6901 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006902 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006903
Rex Xu430ef402016-10-14 17:22:23 +08006904 switch (op) {
6905 case glslang::EOpMinInvocations:
6906 case glslang::EOpMaxInvocations:
6907 case glslang::EOpAddInvocations:
6908 case glslang::EOpMinInvocationsNonUniform:
6909 case glslang::EOpMaxInvocationsNonUniform:
6910 case glslang::EOpAddInvocationsNonUniform:
6911 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006912 break;
6913 case glslang::EOpMinInvocationsInclusiveScan:
6914 case glslang::EOpMaxInvocationsInclusiveScan:
6915 case glslang::EOpAddInvocationsInclusiveScan:
6916 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6917 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6918 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6919 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006920 break;
6921 case glslang::EOpMinInvocationsExclusiveScan:
6922 case glslang::EOpMaxInvocationsExclusiveScan:
6923 case glslang::EOpAddInvocationsExclusiveScan:
6924 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6925 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6926 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6927 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006928 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006929 default:
6930 break;
Rex Xu430ef402016-10-14 17:22:23 +08006931 }
John Kessenich149afc32018-08-14 13:31:43 -06006932 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6933 spvGroupOperands.push_back(scope);
6934 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006935 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006936 spvGroupOperands.push_back(groupOp);
6937 }
Rex Xu51596642016-09-21 18:56:12 +08006938 }
6939
John Kessenich149afc32018-08-14 13:31:43 -06006940 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6941 spv::IdImmediate op = { true, *opIt };
6942 spvGroupOperands.push_back(op);
6943 }
John Kessenich91cef522016-05-05 16:45:40 -06006944
6945 switch (op) {
6946 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006947 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006948 break;
John Kessenich91cef522016-05-05 16:45:40 -06006949 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006950 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006951 break;
John Kessenich91cef522016-05-05 16:45:40 -06006952 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006953 opCode = spv::OpSubgroupAllEqualKHR;
6954 break;
Rex Xu51596642016-09-21 18:56:12 +08006955 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006956 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006957 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006958 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006959 break;
6960 case glslang::EOpReadFirstInvocation:
6961 opCode = spv::OpSubgroupFirstInvocationKHR;
6962 break;
6963 case glslang::EOpBallot:
6964 {
6965 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6966 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6967 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6968 //
6969 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6970 //
6971 spv::Id uintType = builder.makeUintType(32);
6972 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6973 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6974
6975 std::vector<spv::Id> components;
6976 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6977 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6978
6979 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6980 return builder.createUnaryOp(spv::OpBitcast, typeId,
6981 builder.createCompositeConstruct(uvec2Type, components));
6982 }
6983
Rex Xu9d93a232016-05-05 12:30:44 +08006984 case glslang::EOpMinInvocations:
6985 case glslang::EOpMaxInvocations:
6986 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006987 case glslang::EOpMinInvocationsInclusiveScan:
6988 case glslang::EOpMaxInvocationsInclusiveScan:
6989 case glslang::EOpAddInvocationsInclusiveScan:
6990 case glslang::EOpMinInvocationsExclusiveScan:
6991 case glslang::EOpMaxInvocationsExclusiveScan:
6992 case glslang::EOpAddInvocationsExclusiveScan:
6993 if (op == glslang::EOpMinInvocations ||
6994 op == glslang::EOpMinInvocationsInclusiveScan ||
6995 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006996 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006997 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006998 else {
6999 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007000 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08007001 else
Rex Xu51596642016-09-21 18:56:12 +08007002 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08007003 }
Rex Xu430ef402016-10-14 17:22:23 +08007004 } else if (op == glslang::EOpMaxInvocations ||
7005 op == glslang::EOpMaxInvocationsInclusiveScan ||
7006 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08007007 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007008 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007009 else {
7010 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007011 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007012 else
Rex Xu51596642016-09-21 18:56:12 +08007013 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007014 }
7015 } else {
7016 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007017 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08007018 else
Rex Xu51596642016-09-21 18:56:12 +08007019 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08007020 }
7021
Rex Xu2bbbe062016-08-23 15:41:05 +08007022 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007023 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007024
7025 break;
Rex Xu9d93a232016-05-05 12:30:44 +08007026 case glslang::EOpMinInvocationsNonUniform:
7027 case glslang::EOpMaxInvocationsNonUniform:
7028 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08007029 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
7030 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
7031 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
7032 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
7033 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
7034 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
7035 if (op == glslang::EOpMinInvocationsNonUniform ||
7036 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
7037 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007038 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007039 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007040 else {
7041 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007042 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007043 else
Rex Xu51596642016-09-21 18:56:12 +08007044 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007045 }
7046 }
Rex Xu430ef402016-10-14 17:22:23 +08007047 else if (op == glslang::EOpMaxInvocationsNonUniform ||
7048 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
7049 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007050 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007051 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007052 else {
7053 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007054 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007055 else
Rex Xu51596642016-09-21 18:56:12 +08007056 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007057 }
7058 }
7059 else {
7060 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007061 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007062 else
Rex Xu51596642016-09-21 18:56:12 +08007063 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007064 }
7065
Rex Xu2bbbe062016-08-23 15:41:05 +08007066 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007067 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007068
7069 break;
John Kessenich91cef522016-05-05 16:45:40 -06007070 default:
7071 logger->missingFunctionality("invocation operation");
7072 return spv::NoResult;
7073 }
Rex Xu51596642016-09-21 18:56:12 +08007074
7075 assert(opCode != spv::OpNop);
7076 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06007077}
7078
Rex Xu2bbbe062016-08-23 15:41:05 +08007079// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06007080spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
7081 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08007082{
7083 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
7084 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08007085 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08007086 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07007087 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
7088 op == spv::OpGroupSMinNonUniformAMD ||
7089 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
7090 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08007091 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
7092
7093 // Handle group invocation operations scalar by scalar.
7094 // The result type is the same type as the original type.
7095 // The algorithm is to:
7096 // - break the vector into scalars
7097 // - apply the operation to each scalar
7098 // - make a vector out the scalar results
7099
7100 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08007101 int numComponents = builder.getNumComponents(operands[0]);
7102 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08007103 std::vector<spv::Id> results;
7104
7105 // do each scalar op
7106 for (int comp = 0; comp < numComponents; ++comp) {
7107 std::vector<unsigned int> indexes;
7108 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06007109 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
7110 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08007111 if (op == spv::OpSubgroupReadInvocationKHR) {
7112 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007113 spv::IdImmediate operand = { true, operands[1] };
7114 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08007115 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06007116 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7117 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08007118 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007119 spv::IdImmediate operand = { true, operands[1] };
7120 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08007121 } else {
John Kessenich149afc32018-08-14 13:31:43 -06007122 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7123 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06007124 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007125 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08007126 spvGroupOperands.push_back(scalar);
7127 }
Rex Xu2bbbe062016-08-23 15:41:05 +08007128
Rex Xub7072052016-09-26 15:53:40 +08007129 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08007130 }
7131
7132 // put the pieces together
7133 return builder.createCompositeConstruct(typeId, results);
7134}
Rex Xu2bbbe062016-08-23 15:41:05 +08007135
John Kessenich66011cb2018-03-06 16:12:04 -07007136// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06007137spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
7138 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07007139{
7140 // Add the required capabilities.
7141 switch (op) {
7142 case glslang::EOpSubgroupElect:
7143 builder.addCapability(spv::CapabilityGroupNonUniform);
7144 break;
7145 case glslang::EOpSubgroupAll:
7146 case glslang::EOpSubgroupAny:
7147 case glslang::EOpSubgroupAllEqual:
7148 builder.addCapability(spv::CapabilityGroupNonUniform);
7149 builder.addCapability(spv::CapabilityGroupNonUniformVote);
7150 break;
7151 case glslang::EOpSubgroupBroadcast:
7152 case glslang::EOpSubgroupBroadcastFirst:
7153 case glslang::EOpSubgroupBallot:
7154 case glslang::EOpSubgroupInverseBallot:
7155 case glslang::EOpSubgroupBallotBitExtract:
7156 case glslang::EOpSubgroupBallotBitCount:
7157 case glslang::EOpSubgroupBallotInclusiveBitCount:
7158 case glslang::EOpSubgroupBallotExclusiveBitCount:
7159 case glslang::EOpSubgroupBallotFindLSB:
7160 case glslang::EOpSubgroupBallotFindMSB:
7161 builder.addCapability(spv::CapabilityGroupNonUniform);
7162 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
7163 break;
7164 case glslang::EOpSubgroupShuffle:
7165 case glslang::EOpSubgroupShuffleXor:
7166 builder.addCapability(spv::CapabilityGroupNonUniform);
7167 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
7168 break;
7169 case glslang::EOpSubgroupShuffleUp:
7170 case glslang::EOpSubgroupShuffleDown:
7171 builder.addCapability(spv::CapabilityGroupNonUniform);
7172 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
7173 break;
7174 case glslang::EOpSubgroupAdd:
7175 case glslang::EOpSubgroupMul:
7176 case glslang::EOpSubgroupMin:
7177 case glslang::EOpSubgroupMax:
7178 case glslang::EOpSubgroupAnd:
7179 case glslang::EOpSubgroupOr:
7180 case glslang::EOpSubgroupXor:
7181 case glslang::EOpSubgroupInclusiveAdd:
7182 case glslang::EOpSubgroupInclusiveMul:
7183 case glslang::EOpSubgroupInclusiveMin:
7184 case glslang::EOpSubgroupInclusiveMax:
7185 case glslang::EOpSubgroupInclusiveAnd:
7186 case glslang::EOpSubgroupInclusiveOr:
7187 case glslang::EOpSubgroupInclusiveXor:
7188 case glslang::EOpSubgroupExclusiveAdd:
7189 case glslang::EOpSubgroupExclusiveMul:
7190 case glslang::EOpSubgroupExclusiveMin:
7191 case glslang::EOpSubgroupExclusiveMax:
7192 case glslang::EOpSubgroupExclusiveAnd:
7193 case glslang::EOpSubgroupExclusiveOr:
7194 case glslang::EOpSubgroupExclusiveXor:
7195 builder.addCapability(spv::CapabilityGroupNonUniform);
7196 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
7197 break;
7198 case glslang::EOpSubgroupClusteredAdd:
7199 case glslang::EOpSubgroupClusteredMul:
7200 case glslang::EOpSubgroupClusteredMin:
7201 case glslang::EOpSubgroupClusteredMax:
7202 case glslang::EOpSubgroupClusteredAnd:
7203 case glslang::EOpSubgroupClusteredOr:
7204 case glslang::EOpSubgroupClusteredXor:
7205 builder.addCapability(spv::CapabilityGroupNonUniform);
7206 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7207 break;
7208 case glslang::EOpSubgroupQuadBroadcast:
7209 case glslang::EOpSubgroupQuadSwapHorizontal:
7210 case glslang::EOpSubgroupQuadSwapVertical:
7211 case glslang::EOpSubgroupQuadSwapDiagonal:
7212 builder.addCapability(spv::CapabilityGroupNonUniform);
7213 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7214 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007215 case glslang::EOpSubgroupPartitionedAdd:
7216 case glslang::EOpSubgroupPartitionedMul:
7217 case glslang::EOpSubgroupPartitionedMin:
7218 case glslang::EOpSubgroupPartitionedMax:
7219 case glslang::EOpSubgroupPartitionedAnd:
7220 case glslang::EOpSubgroupPartitionedOr:
7221 case glslang::EOpSubgroupPartitionedXor:
7222 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7223 case glslang::EOpSubgroupPartitionedInclusiveMul:
7224 case glslang::EOpSubgroupPartitionedInclusiveMin:
7225 case glslang::EOpSubgroupPartitionedInclusiveMax:
7226 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7227 case glslang::EOpSubgroupPartitionedInclusiveOr:
7228 case glslang::EOpSubgroupPartitionedInclusiveXor:
7229 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7230 case glslang::EOpSubgroupPartitionedExclusiveMul:
7231 case glslang::EOpSubgroupPartitionedExclusiveMin:
7232 case glslang::EOpSubgroupPartitionedExclusiveMax:
7233 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7234 case glslang::EOpSubgroupPartitionedExclusiveOr:
7235 case glslang::EOpSubgroupPartitionedExclusiveXor:
7236 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7237 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7238 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007239 default: assert(0 && "Unhandled subgroup operation!");
7240 }
7241
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007242
7243 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7244 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007245 const bool isBool = typeProxy == glslang::EbtBool;
7246
7247 spv::Op opCode = spv::OpNop;
7248
7249 // Figure out which opcode to use.
7250 switch (op) {
7251 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7252 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7253 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7254 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7255 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7256 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7257 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7258 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7259 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7260 case glslang::EOpSubgroupBallotBitCount:
7261 case glslang::EOpSubgroupBallotInclusiveBitCount:
7262 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7263 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7264 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7265 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7266 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7267 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7268 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7269 case glslang::EOpSubgroupAdd:
7270 case glslang::EOpSubgroupInclusiveAdd:
7271 case glslang::EOpSubgroupExclusiveAdd:
7272 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007273 case glslang::EOpSubgroupPartitionedAdd:
7274 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7275 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007276 if (isFloat) {
7277 opCode = spv::OpGroupNonUniformFAdd;
7278 } else {
7279 opCode = spv::OpGroupNonUniformIAdd;
7280 }
7281 break;
7282 case glslang::EOpSubgroupMul:
7283 case glslang::EOpSubgroupInclusiveMul:
7284 case glslang::EOpSubgroupExclusiveMul:
7285 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007286 case glslang::EOpSubgroupPartitionedMul:
7287 case glslang::EOpSubgroupPartitionedInclusiveMul:
7288 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007289 if (isFloat) {
7290 opCode = spv::OpGroupNonUniformFMul;
7291 } else {
7292 opCode = spv::OpGroupNonUniformIMul;
7293 }
7294 break;
7295 case glslang::EOpSubgroupMin:
7296 case glslang::EOpSubgroupInclusiveMin:
7297 case glslang::EOpSubgroupExclusiveMin:
7298 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007299 case glslang::EOpSubgroupPartitionedMin:
7300 case glslang::EOpSubgroupPartitionedInclusiveMin:
7301 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007302 if (isFloat) {
7303 opCode = spv::OpGroupNonUniformFMin;
7304 } else if (isUnsigned) {
7305 opCode = spv::OpGroupNonUniformUMin;
7306 } else {
7307 opCode = spv::OpGroupNonUniformSMin;
7308 }
7309 break;
7310 case glslang::EOpSubgroupMax:
7311 case glslang::EOpSubgroupInclusiveMax:
7312 case glslang::EOpSubgroupExclusiveMax:
7313 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007314 case glslang::EOpSubgroupPartitionedMax:
7315 case glslang::EOpSubgroupPartitionedInclusiveMax:
7316 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007317 if (isFloat) {
7318 opCode = spv::OpGroupNonUniformFMax;
7319 } else if (isUnsigned) {
7320 opCode = spv::OpGroupNonUniformUMax;
7321 } else {
7322 opCode = spv::OpGroupNonUniformSMax;
7323 }
7324 break;
7325 case glslang::EOpSubgroupAnd:
7326 case glslang::EOpSubgroupInclusiveAnd:
7327 case glslang::EOpSubgroupExclusiveAnd:
7328 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007329 case glslang::EOpSubgroupPartitionedAnd:
7330 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7331 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007332 if (isBool) {
7333 opCode = spv::OpGroupNonUniformLogicalAnd;
7334 } else {
7335 opCode = spv::OpGroupNonUniformBitwiseAnd;
7336 }
7337 break;
7338 case glslang::EOpSubgroupOr:
7339 case glslang::EOpSubgroupInclusiveOr:
7340 case glslang::EOpSubgroupExclusiveOr:
7341 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007342 case glslang::EOpSubgroupPartitionedOr:
7343 case glslang::EOpSubgroupPartitionedInclusiveOr:
7344 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007345 if (isBool) {
7346 opCode = spv::OpGroupNonUniformLogicalOr;
7347 } else {
7348 opCode = spv::OpGroupNonUniformBitwiseOr;
7349 }
7350 break;
7351 case glslang::EOpSubgroupXor:
7352 case glslang::EOpSubgroupInclusiveXor:
7353 case glslang::EOpSubgroupExclusiveXor:
7354 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007355 case glslang::EOpSubgroupPartitionedXor:
7356 case glslang::EOpSubgroupPartitionedInclusiveXor:
7357 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007358 if (isBool) {
7359 opCode = spv::OpGroupNonUniformLogicalXor;
7360 } else {
7361 opCode = spv::OpGroupNonUniformBitwiseXor;
7362 }
7363 break;
7364 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7365 case glslang::EOpSubgroupQuadSwapHorizontal:
7366 case glslang::EOpSubgroupQuadSwapVertical:
7367 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7368 default: assert(0 && "Unhandled subgroup operation!");
7369 }
7370
John Kessenich149afc32018-08-14 13:31:43 -06007371 // get the right Group Operation
7372 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007373 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007374 default:
7375 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007376 case glslang::EOpSubgroupBallotBitCount:
7377 case glslang::EOpSubgroupAdd:
7378 case glslang::EOpSubgroupMul:
7379 case glslang::EOpSubgroupMin:
7380 case glslang::EOpSubgroupMax:
7381 case glslang::EOpSubgroupAnd:
7382 case glslang::EOpSubgroupOr:
7383 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007384 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007385 break;
7386 case glslang::EOpSubgroupBallotInclusiveBitCount:
7387 case glslang::EOpSubgroupInclusiveAdd:
7388 case glslang::EOpSubgroupInclusiveMul:
7389 case glslang::EOpSubgroupInclusiveMin:
7390 case glslang::EOpSubgroupInclusiveMax:
7391 case glslang::EOpSubgroupInclusiveAnd:
7392 case glslang::EOpSubgroupInclusiveOr:
7393 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007394 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007395 break;
7396 case glslang::EOpSubgroupBallotExclusiveBitCount:
7397 case glslang::EOpSubgroupExclusiveAdd:
7398 case glslang::EOpSubgroupExclusiveMul:
7399 case glslang::EOpSubgroupExclusiveMin:
7400 case glslang::EOpSubgroupExclusiveMax:
7401 case glslang::EOpSubgroupExclusiveAnd:
7402 case glslang::EOpSubgroupExclusiveOr:
7403 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007404 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007405 break;
7406 case glslang::EOpSubgroupClusteredAdd:
7407 case glslang::EOpSubgroupClusteredMul:
7408 case glslang::EOpSubgroupClusteredMin:
7409 case glslang::EOpSubgroupClusteredMax:
7410 case glslang::EOpSubgroupClusteredAnd:
7411 case glslang::EOpSubgroupClusteredOr:
7412 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007413 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007414 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007415 case glslang::EOpSubgroupPartitionedAdd:
7416 case glslang::EOpSubgroupPartitionedMul:
7417 case glslang::EOpSubgroupPartitionedMin:
7418 case glslang::EOpSubgroupPartitionedMax:
7419 case glslang::EOpSubgroupPartitionedAnd:
7420 case glslang::EOpSubgroupPartitionedOr:
7421 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007422 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007423 break;
7424 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7425 case glslang::EOpSubgroupPartitionedInclusiveMul:
7426 case glslang::EOpSubgroupPartitionedInclusiveMin:
7427 case glslang::EOpSubgroupPartitionedInclusiveMax:
7428 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7429 case glslang::EOpSubgroupPartitionedInclusiveOr:
7430 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007431 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007432 break;
7433 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7434 case glslang::EOpSubgroupPartitionedExclusiveMul:
7435 case glslang::EOpSubgroupPartitionedExclusiveMin:
7436 case glslang::EOpSubgroupPartitionedExclusiveMax:
7437 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7438 case glslang::EOpSubgroupPartitionedExclusiveOr:
7439 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007440 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007441 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007442 }
7443
John Kessenich149afc32018-08-14 13:31:43 -06007444 // build the instruction
7445 std::vector<spv::IdImmediate> spvGroupOperands;
7446
7447 // Every operation begins with the Execution Scope operand.
7448 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7449 spvGroupOperands.push_back(executionScope);
7450
7451 // Next, for all operations that use a Group Operation, push that as an operand.
7452 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007453 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007454 spvGroupOperands.push_back(groupOperand);
7455 }
7456
John Kessenich66011cb2018-03-06 16:12:04 -07007457 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007458 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7459 spv::IdImmediate operand = { true, *opIt };
7460 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007461 }
7462
7463 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007464 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007465 switch (op) {
7466 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007467 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7468 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7469 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7470 }
7471 if (directionId != spv::NoResult) {
7472 spv::IdImmediate direction = { true, directionId };
7473 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007474 }
7475
7476 return builder.createOp(opCode, typeId, spvGroupOperands);
7477}
7478
John Kessenich8985fc92020-03-03 10:25:07 -07007479spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7480 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007481{
John Kessenich66011cb2018-03-06 16:12:04 -07007482 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7483 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007484
John Kessenich140f3df2015-06-26 16:58:36 -06007485 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007486 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007487 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007488 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007489 spv::Id typeId0 = 0;
7490 if (consumedOperands > 0)
7491 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007492 spv::Id typeId1 = 0;
7493 if (consumedOperands > 1)
7494 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007495 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007496
7497 switch (op) {
7498 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007499 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007500 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007501 else if (isUnsigned)
7502 libCall = spv::GLSLstd450UMin;
7503 else
7504 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007505 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007506 break;
7507 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007508 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007509 break;
7510 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007511 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007512 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007513 else if (isUnsigned)
7514 libCall = spv::GLSLstd450UMax;
7515 else
7516 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007517 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007518 break;
7519 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007520 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007521 break;
7522 case glslang::EOpDot:
7523 opCode = spv::OpDot;
7524 break;
7525 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007526 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007527 break;
7528
7529 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007530 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007531 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007532 else if (isUnsigned)
7533 libCall = spv::GLSLstd450UClamp;
7534 else
7535 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007536 builder.promoteScalar(precision, operands.front(), operands[1]);
7537 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007538 break;
7539 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007540 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7541 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007542 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007543 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007544 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007545 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007546 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007547 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007548 break;
7549 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007550 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007551 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007552 break;
7553 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007554 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007555 builder.promoteScalar(precision, operands[0], operands[2]);
7556 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007557 break;
7558
7559 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007560 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007561 break;
7562 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007563 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007564 break;
7565 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007566 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007567 break;
7568 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007569 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007570 break;
7571 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007572 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007573 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007574 case glslang::EOpBarrier:
7575 {
7576 // This is for the extended controlBarrier function, with four operands.
7577 // The unextended barrier() goes through createNoArgOperation.
7578 assert(operands.size() == 4);
7579 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7580 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7581 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007582 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7583 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007584 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7585 spv::MemorySemanticsMakeVisibleKHRMask |
7586 spv::MemorySemanticsOutputMemoryKHRMask |
7587 spv::MemorySemanticsVolatileMask)) {
7588 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7589 }
John Kessenich8985fc92020-03-03 10:25:07 -07007590 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7591 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007592 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7593 }
7594 return 0;
7595 }
7596 break;
7597 case glslang::EOpMemoryBarrier:
7598 {
7599 // This is for the extended memoryBarrier function, with three operands.
7600 // The unextended memoryBarrier() goes through createNoArgOperation.
7601 assert(operands.size() == 3);
7602 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7603 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7604 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7605 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7606 spv::MemorySemanticsMakeVisibleKHRMask |
7607 spv::MemorySemanticsOutputMemoryKHRMask |
7608 spv::MemorySemanticsVolatileMask)) {
7609 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7610 }
7611 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7612 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7613 }
7614 return 0;
7615 }
7616 break;
7617
John Kessenicha28f7a72019-08-06 07:00:58 -06007618#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007619 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007620 if (typeProxy == glslang::EbtFloat16)
7621 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007622 libCall = spv::GLSLstd450InterpolateAtSample;
7623 break;
7624 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007625 if (typeProxy == glslang::EbtFloat16)
7626 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007627 libCall = spv::GLSLstd450InterpolateAtOffset;
7628 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007629 case glslang::EOpAddCarry:
7630 opCode = spv::OpIAddCarry;
7631 typeId = builder.makeStructResultType(typeId0, typeId0);
7632 consumedOperands = 2;
7633 break;
7634 case glslang::EOpSubBorrow:
7635 opCode = spv::OpISubBorrow;
7636 typeId = builder.makeStructResultType(typeId0, typeId0);
7637 consumedOperands = 2;
7638 break;
7639 case glslang::EOpUMulExtended:
7640 opCode = spv::OpUMulExtended;
7641 typeId = builder.makeStructResultType(typeId0, typeId0);
7642 consumedOperands = 2;
7643 break;
7644 case glslang::EOpIMulExtended:
7645 opCode = spv::OpSMulExtended;
7646 typeId = builder.makeStructResultType(typeId0, typeId0);
7647 consumedOperands = 2;
7648 break;
7649 case glslang::EOpBitfieldExtract:
7650 if (isUnsigned)
7651 opCode = spv::OpBitFieldUExtract;
7652 else
7653 opCode = spv::OpBitFieldSExtract;
7654 break;
7655 case glslang::EOpBitfieldInsert:
7656 opCode = spv::OpBitFieldInsert;
7657 break;
7658
7659 case glslang::EOpFma:
7660 libCall = spv::GLSLstd450Fma;
7661 break;
7662 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007663 {
7664 libCall = spv::GLSLstd450FrexpStruct;
7665 assert(builder.isPointerType(typeId1));
7666 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007667 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007668 if (width == 16)
7669 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7670 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007671 if (builder.getNumComponents(operands[0]) == 1)
7672 frexpIntType = builder.makeIntegerType(width, true);
7673 else
John Kessenich8985fc92020-03-03 10:25:07 -07007674 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7675 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007676 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7677 consumedOperands = 1;
7678 }
John Kessenich55e7d112015-11-15 21:33:39 -07007679 break;
7680 case glslang::EOpLdexp:
7681 libCall = spv::GLSLstd450Ldexp;
7682 break;
7683
Rex Xu574ab042016-04-14 16:53:07 +08007684 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007685 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007686
John Kessenich66011cb2018-03-06 16:12:04 -07007687 case glslang::EOpSubgroupBroadcast:
7688 case glslang::EOpSubgroupBallotBitExtract:
7689 case glslang::EOpSubgroupShuffle:
7690 case glslang::EOpSubgroupShuffleXor:
7691 case glslang::EOpSubgroupShuffleUp:
7692 case glslang::EOpSubgroupShuffleDown:
7693 case glslang::EOpSubgroupClusteredAdd:
7694 case glslang::EOpSubgroupClusteredMul:
7695 case glslang::EOpSubgroupClusteredMin:
7696 case glslang::EOpSubgroupClusteredMax:
7697 case glslang::EOpSubgroupClusteredAnd:
7698 case glslang::EOpSubgroupClusteredOr:
7699 case glslang::EOpSubgroupClusteredXor:
7700 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007701 case glslang::EOpSubgroupPartitionedAdd:
7702 case glslang::EOpSubgroupPartitionedMul:
7703 case glslang::EOpSubgroupPartitionedMin:
7704 case glslang::EOpSubgroupPartitionedMax:
7705 case glslang::EOpSubgroupPartitionedAnd:
7706 case glslang::EOpSubgroupPartitionedOr:
7707 case glslang::EOpSubgroupPartitionedXor:
7708 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7709 case glslang::EOpSubgroupPartitionedInclusiveMul:
7710 case glslang::EOpSubgroupPartitionedInclusiveMin:
7711 case glslang::EOpSubgroupPartitionedInclusiveMax:
7712 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7713 case glslang::EOpSubgroupPartitionedInclusiveOr:
7714 case glslang::EOpSubgroupPartitionedInclusiveXor:
7715 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7716 case glslang::EOpSubgroupPartitionedExclusiveMul:
7717 case glslang::EOpSubgroupPartitionedExclusiveMin:
7718 case glslang::EOpSubgroupPartitionedExclusiveMax:
7719 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7720 case glslang::EOpSubgroupPartitionedExclusiveOr:
7721 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007722 return createSubgroupOperation(op, typeId, operands, typeProxy);
7723
Rex Xu9d93a232016-05-05 12:30:44 +08007724 case glslang::EOpSwizzleInvocations:
7725 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7726 libCall = spv::SwizzleInvocationsAMD;
7727 break;
7728 case glslang::EOpSwizzleInvocationsMasked:
7729 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7730 libCall = spv::SwizzleInvocationsMaskedAMD;
7731 break;
7732 case glslang::EOpWriteInvocation:
7733 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7734 libCall = spv::WriteInvocationAMD;
7735 break;
7736
7737 case glslang::EOpMin3:
7738 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7739 if (isFloat)
7740 libCall = spv::FMin3AMD;
7741 else {
7742 if (isUnsigned)
7743 libCall = spv::UMin3AMD;
7744 else
7745 libCall = spv::SMin3AMD;
7746 }
7747 break;
7748 case glslang::EOpMax3:
7749 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7750 if (isFloat)
7751 libCall = spv::FMax3AMD;
7752 else {
7753 if (isUnsigned)
7754 libCall = spv::UMax3AMD;
7755 else
7756 libCall = spv::SMax3AMD;
7757 }
7758 break;
7759 case glslang::EOpMid3:
7760 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7761 if (isFloat)
7762 libCall = spv::FMid3AMD;
7763 else {
7764 if (isUnsigned)
7765 libCall = spv::UMid3AMD;
7766 else
7767 libCall = spv::SMid3AMD;
7768 }
7769 break;
7770
7771 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007772 if (typeProxy == glslang::EbtFloat16)
7773 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007774 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7775 libCall = spv::InterpolateAtVertexAMD;
7776 break;
Chao Chen3c366992018-09-19 11:41:59 -07007777
Daniel Kochdb32b242020-03-17 20:42:47 -04007778 case glslang::EOpReportIntersection:
Chao Chenb50c02e2018-09-19 11:42:24 -07007779 typeId = builder.makeBoolType();
Daniel Kochdb32b242020-03-17 20:42:47 -04007780 opCode = spv::OpReportIntersectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007781 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04007782 case glslang::EOpTrace:
Daniel Kochdb32b242020-03-17 20:42:47 -04007783 builder.createNoResultOp(spv::OpTraceRayKHR, operands);
Ashwin Leleff1783d2018-10-22 16:41:44 -07007784 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04007785 case glslang::EOpExecuteCallable:
Daniel Kochdb32b242020-03-17 20:42:47 -04007786 builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007787 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007788
7789 case glslang::EOpRayQueryInitialize:
Torosdagli06c2eee2020-03-19 11:09:57 -04007790 builder.createNoResultOp(spv::OpRayQueryInitializeKHR, operands);
7791 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007792 case glslang::EOpRayQueryTerminate:
Torosdagli06c2eee2020-03-19 11:09:57 -04007793 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operands);
7794 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007795 case glslang::EOpRayQueryGenerateIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007796 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR, operands);
7797 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007798 case glslang::EOpRayQueryConfirmIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007799 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operands);
7800 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007801 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04007802 typeId = builder.makeBoolType();
7803 opCode = spv::OpRayQueryProceedKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007804 break;
7805 case glslang::EOpRayQueryGetIntersectionType:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007806 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007807 opCode = spv::OpRayQueryGetIntersectionTypeKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007808 break;
7809 case glslang::EOpRayQueryGetRayTMin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007810 typeId = builder.makeFloatType(32);
7811 opCode = spv::OpRayQueryGetRayTMinKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007812 break;
7813 case glslang::EOpRayQueryGetRayFlags:
Torosdagli06c2eee2020-03-19 11:09:57 -04007814 typeId = builder.makeIntType(32);
7815 opCode = spv::OpRayQueryGetRayFlagsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007816 break;
7817 case glslang::EOpRayQueryGetIntersectionT:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007818 typeId = builder.makeFloatType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007819 opCode = spv::OpRayQueryGetIntersectionTKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007820 break;
7821 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007822 typeId = builder.makeIntType(32);
7823 opCode = spv::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007824 break;
7825 case glslang::EOpRayQueryGetIntersectionInstanceId:
Torosdagli06c2eee2020-03-19 11:09:57 -04007826 typeId = builder.makeIntType(32);
7827 opCode = spv::OpRayQueryGetIntersectionInstanceIdKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007828 break;
7829 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
Torosdagli06c2eee2020-03-19 11:09:57 -04007830 typeId = builder.makeIntType(32);
7831 opCode = spv::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007832 break;
7833 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007834 typeId = builder.makeIntType(32);
7835 opCode = spv::OpRayQueryGetIntersectionGeometryIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007836 break;
7837 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007838 typeId = builder.makeIntType(32);
7839 opCode = spv::OpRayQueryGetIntersectionPrimitiveIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007840 break;
7841 case glslang::EOpRayQueryGetIntersectionBarycentrics:
Torosdagli06c2eee2020-03-19 11:09:57 -04007842 typeId = builder.makeVectorType(builder.makeFloatType(32), 2);
7843 opCode = spv::OpRayQueryGetIntersectionBarycentricsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007844 break;
7845 case glslang::EOpRayQueryGetIntersectionFrontFace:
Torosdagli06c2eee2020-03-19 11:09:57 -04007846 typeId = builder.makeBoolType();
7847 opCode = spv::OpRayQueryGetIntersectionFrontFaceKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007848 break;
7849 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
Torosdagli06c2eee2020-03-19 11:09:57 -04007850 typeId = builder.makeBoolType();
7851 opCode = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007852 break;
7853 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007854 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7855 opCode = spv::OpRayQueryGetIntersectionObjectRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007856 break;
7857 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007858 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7859 opCode = spv::OpRayQueryGetIntersectionObjectRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007860 break;
7861 case glslang::EOpRayQueryGetWorldRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007862 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7863 opCode = spv::OpRayQueryGetWorldRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007864 break;
7865 case glslang::EOpRayQueryGetWorldRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007866 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7867 opCode = spv::OpRayQueryGetWorldRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007868 break;
7869 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
Torosdagli06c2eee2020-03-19 11:09:57 -04007870 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007871 opCode = spv::OpRayQueryGetIntersectionObjectToWorldKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007872 break;
7873 case glslang::EOpRayQueryGetIntersectionWorldToObject:
Torosdagli06c2eee2020-03-19 11:09:57 -04007874 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007875 opCode = spv::OpRayQueryGetIntersectionWorldToObjectKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007876 break;
Chao Chen3c366992018-09-19 11:41:59 -07007877 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7878 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7879 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007880 case glslang::EOpCooperativeMatrixMulAdd:
7881 opCode = spv::OpCooperativeMatrixMulAddNV;
7882 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007883#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007884 default:
7885 return 0;
7886 }
7887
7888 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007889 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007890 // Use an extended instruction from the standard library.
7891 // Construct the call arguments, without modifying the original operands vector.
7892 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7893 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007894 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007895 } else if (opCode == spv::OpDot && !isFloat) {
7896 // int dot(int, int)
7897 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7898 const int componentCount = builder.getNumComponents(operands[0]);
7899 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7900 builder.setPrecision(mulOp, precision);
7901 id = builder.createCompositeExtract(mulOp, typeId, 0);
7902 for (int i = 1; i < componentCount; ++i) {
7903 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07007904 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01007905 }
John Kessenich2359bd02015-12-06 19:29:11 -07007906 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007907 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007908 case 0:
7909 // should all be handled by visitAggregate and createNoArgOperation
7910 assert(0);
7911 return 0;
7912 case 1:
7913 // should all be handled by createUnaryOperation
7914 assert(0);
7915 return 0;
7916 case 2:
7917 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7918 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007919 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007920 // anything 3 or over doesn't have l-value operands, so all should be consumed
7921 assert(consumedOperands == operands.size());
7922 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007923 break;
7924 }
7925 }
7926
John Kessenichb9197c82019-08-11 07:41:45 -06007927#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007928 // Decode the return types that were structures
7929 switch (op) {
7930 case glslang::EOpAddCarry:
7931 case glslang::EOpSubBorrow:
7932 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7933 id = builder.createCompositeExtract(id, typeId0, 0);
7934 break;
7935 case glslang::EOpUMulExtended:
7936 case glslang::EOpIMulExtended:
7937 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7938 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7939 break;
7940 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007941 {
7942 assert(operands.size() == 2);
7943 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7944 // "exp" is floating-point type (from HLSL intrinsic)
7945 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7946 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7947 builder.createStore(member1, operands[1]);
7948 } else
7949 // "exp" is integer type (from GLSL built-in function)
7950 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7951 id = builder.createCompositeExtract(id, typeId0, 0);
7952 }
John Kessenich55e7d112015-11-15 21:33:39 -07007953 break;
7954 default:
7955 break;
7956 }
John Kessenichb9197c82019-08-11 07:41:45 -06007957#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007958
John Kessenich32cfd492016-02-02 12:37:46 -07007959 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007960}
7961
Rex Xu9d93a232016-05-05 12:30:44 +08007962// Intrinsics with no arguments (or no return value, and no precision).
7963spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007964{
Jeff Bolz36831c92018-09-05 10:11:41 -05007965 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07007966 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
7967 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007968
7969 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007970 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007971 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007972 if (glslangIntermediate->usingVulkanMemoryModel()) {
7973 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7974 spv::MemorySemanticsOutputMemoryKHRMask |
7975 spv::MemorySemanticsAcquireReleaseMask);
7976 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7977 } else {
7978 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7979 }
John Kessenich82979362017-12-11 04:02:24 -07007980 } else {
7981 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7982 spv::MemorySemanticsWorkgroupMemoryMask |
7983 spv::MemorySemanticsAcquireReleaseMask);
7984 }
John Kessenich140f3df2015-06-26 16:58:36 -06007985 return 0;
7986 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007987 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7988 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007989 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007990 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007991 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7992 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007993 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007994 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007995 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7996 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007997 return 0;
7998 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007999 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
8000 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06008001 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06008002#ifndef GLSLANG_WEB
8003 case glslang::EOpMemoryBarrierAtomicCounter:
8004 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
8005 spv::MemorySemanticsAcquireReleaseMask);
8006 return 0;
8007 case glslang::EOpMemoryBarrierImage:
8008 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
8009 spv::MemorySemanticsAcquireReleaseMask);
8010 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06008011 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07008012 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07008013 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07008014 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008015 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07008016 case glslang::EOpDeviceMemoryBarrier:
8017 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
8018 spv::MemorySemanticsImageMemoryMask |
8019 spv::MemorySemanticsAcquireReleaseMask);
8020 return 0;
8021 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
8022 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
8023 spv::MemorySemanticsImageMemoryMask |
8024 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008025 return 0;
8026 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07008027 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8028 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008029 return 0;
8030 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07008031 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8032 spv::MemorySemanticsWorkgroupMemoryMask |
8033 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008034 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07008035 case glslang::EOpSubgroupBarrier:
8036 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8037 spv::MemorySemanticsAcquireReleaseMask);
8038 return spv::NoResult;
8039 case glslang::EOpSubgroupMemoryBarrier:
8040 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8041 spv::MemorySemanticsAcquireReleaseMask);
8042 return spv::NoResult;
8043 case glslang::EOpSubgroupMemoryBarrierBuffer:
8044 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
8045 spv::MemorySemanticsAcquireReleaseMask);
8046 return spv::NoResult;
8047 case glslang::EOpSubgroupMemoryBarrierImage:
8048 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
8049 spv::MemorySemanticsAcquireReleaseMask);
8050 return spv::NoResult;
8051 case glslang::EOpSubgroupMemoryBarrierShared:
8052 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8053 spv::MemorySemanticsAcquireReleaseMask);
8054 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06008055
8056 case glslang::EOpEmitVertex:
8057 builder.createNoResultOp(spv::OpEmitVertex);
8058 return 0;
8059 case glslang::EOpEndPrimitive:
8060 builder.createNoResultOp(spv::OpEndPrimitive);
8061 return 0;
8062
John Kessenich66011cb2018-03-06 16:12:04 -07008063 case glslang::EOpSubgroupElect: {
8064 std::vector<spv::Id> operands;
8065 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
8066 }
Rex Xu9d93a232016-05-05 12:30:44 +08008067 case glslang::EOpTime:
8068 {
8069 std::vector<spv::Id> args; // Dummy arguments
8070 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
8071 return builder.setPrecision(id, precision);
8072 }
Daniel Kochdb32b242020-03-17 20:42:47 -04008073 case glslang::EOpIgnoreIntersection:
8074 builder.createNoResultOp(spv::OpIgnoreIntersectionKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008075 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04008076 case glslang::EOpTerminateRay:
8077 builder.createNoResultOp(spv::OpTerminateRayKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008078 return 0;
Torosdagli06c2eee2020-03-19 11:09:57 -04008079 case glslang::EOpRayQueryInitialize:
8080 builder.createNoResultOp(spv::OpRayQueryInitializeKHR);
8081 return 0;
8082 case glslang::EOpRayQueryTerminate:
8083 builder.createNoResultOp(spv::OpRayQueryTerminateKHR);
8084 return 0;
8085 case glslang::EOpRayQueryGenerateIntersection:
8086 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR);
8087 return 0;
8088 case glslang::EOpRayQueryConfirmIntersection:
8089 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR);
8090 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05008091 case glslang::EOpBeginInvocationInterlock:
8092 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
8093 return 0;
8094 case glslang::EOpEndInvocationInterlock:
8095 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
8096 return 0;
8097
Jeff Bolzba6170b2019-07-01 09:23:23 -05008098 case glslang::EOpIsHelperInvocation:
8099 {
8100 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08008101 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
8102 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
8103 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05008104 }
8105
amhagan91fb0092019-07-10 21:14:38 -04008106 case glslang::EOpReadClockSubgroupKHR: {
8107 std::vector<spv::Id> args;
8108 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
8109 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8110 builder.addCapability(spv::CapabilityShaderClockKHR);
8111 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8112 }
8113
8114 case glslang::EOpReadClockDeviceKHR: {
8115 std::vector<spv::Id> args;
8116 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
8117 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8118 builder.addCapability(spv::CapabilityShaderClockKHR);
8119 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8120 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06008121#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008122 default:
John Kessenich155d3512019-08-08 23:29:20 -06008123 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008124 }
John Kessenich155d3512019-08-08 23:29:20 -06008125
8126 logger->missingFunctionality("unknown operation with no arguments");
8127
8128 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008129}
8130
8131spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
8132{
John Kessenich2f273362015-07-18 22:34:27 -06008133 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06008134 spv::Id id;
8135 if (symbolValues.end() != iter) {
8136 id = iter->second;
8137 return id;
8138 }
8139
8140 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06008141 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
Daniel Kochdb32b242020-03-17 20:42:47 -04008142 auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06008143 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06008144 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06008145 if (forcedType.second != spv::NoType)
8146 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06008147
Rex Xuc884b4a2016-06-29 15:03:44 +08008148 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008149 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
8150 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
8151 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06008152#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008153 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06008154 if (symbol->getQualifier().hasComponent())
8155 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
8156 if (symbol->getQualifier().hasIndex())
8157 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07008158#endif
John Kessenich6c292d32016-02-15 20:58:50 -07008159 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07008160 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06008161 // atomic counters use this:
8162 if (symbol->getQualifier().hasOffset())
8163 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008164 }
8165
scygan2c864272016-05-18 18:09:17 +02008166 if (symbol->getQualifier().hasLocation())
8167 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07008168 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07008169 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07008170 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06008171 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07008172 }
John Kessenich140f3df2015-06-26 16:58:36 -06008173 if (symbol->getQualifier().hasSet())
8174 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07008175 else if (IsDescriptorResource(symbol->getType())) {
8176 // default to 0
8177 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
8178 }
John Kessenich140f3df2015-06-26 16:58:36 -06008179 if (symbol->getQualifier().hasBinding())
8180 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06008181 else if (IsDescriptorResource(symbol->getType())) {
8182 // default to 0
8183 builder.addDecoration(id, spv::DecorationBinding, 0);
8184 }
John Kessenich6c292d32016-02-15 20:58:50 -07008185 if (symbol->getQualifier().hasAttachment())
8186 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06008187 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07008188 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07008189 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008190 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07008191 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
8192 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
8193 builder.addDecoration(id, spv::DecorationXfbStride, stride);
8194 }
8195 if (symbol->getQualifier().hasXfbOffset())
8196 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008197 }
8198
John Kessenichb9197c82019-08-11 07:41:45 -06008199 // add built-in variable decoration
8200 if (builtIn != spv::BuiltInMax) {
8201 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
8202 }
8203
8204#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08008205 if (symbol->getType().isImage()) {
8206 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07008207 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
8208 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08008209 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07008210 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08008211 }
8212
John Kessenich5611c6d2018-04-05 11:25:02 -06008213 // nonuniform
8214 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
8215
chaoc0ad6a4e2016-12-19 16:29:34 -08008216 if (builtIn == spv::BuiltInSampleMask) {
8217 spv::Decoration decoration;
8218 // GL_NV_sample_mask_override_coverage extension
8219 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08008220 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08008221 else
8222 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07008223 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08008224 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07008225 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08008226 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
8227 }
8228 }
chaoc771d89f2017-01-13 01:10:53 -08008229 else if (builtIn == spv::BuiltInLayer) {
8230 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06008231 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008232 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08008233 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
8234 builder.addExtension(spv::E_SPV_NV_viewport_array2);
8235 }
John Kessenichb41bff62017-08-11 13:07:17 -06008236 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008237 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
8238 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08008239 builder.addCapability(spv::CapabilityShaderStereoViewNV);
8240 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
8241 }
8242 }
8243
chaoc6e5acae2016-12-20 13:28:52 -08008244 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008245 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08008246 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08008247 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
8248 }
Chao Chen9eada4b2018-09-19 11:39:56 -07008249 if (symbol->getQualifier().pervertexNV) {
8250 builder.addDecoration(id, spv::DecorationPerVertexNV);
8251 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
8252 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
8253 }
chaoc0ad6a4e2016-12-19 16:29:34 -08008254
John Kessenich5d610ee2018-03-07 18:05:55 -07008255 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
8256 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
8257 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
8258 symbol->getType().getQualifier().semanticName);
8259 }
8260
John Kessenich7015bd62019-08-01 03:28:08 -06008261 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07008262 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
8263 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008264 }
John Kessenichb9197c82019-08-11 07:41:45 -06008265#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008266
John Kessenich140f3df2015-06-26 16:58:36 -06008267 return id;
8268}
8269
John Kessenicha28f7a72019-08-06 07:00:58 -06008270#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008271// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
8272void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
8273{
8274 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07008275 if (qualifier.perPrimitiveNV) {
8276 // Need to add capability/extension for fragment shader.
8277 // Mesh shader already adds this by default.
8278 if (glslangIntermediate->getStage() == EShLangFragment) {
8279 builder.addCapability(spv::CapabilityMeshShadingNV);
8280 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8281 }
Chao Chen3c366992018-09-19 11:41:59 -07008282 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008283 }
Chao Chen3c366992018-09-19 11:41:59 -07008284 if (qualifier.perViewNV)
8285 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
8286 if (qualifier.perTaskNV)
8287 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
8288 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07008289 if (qualifier.perPrimitiveNV) {
8290 // Need to add capability/extension for fragment shader.
8291 // Mesh shader already adds this by default.
8292 if (glslangIntermediate->getStage() == EShLangFragment) {
8293 builder.addCapability(spv::CapabilityMeshShadingNV);
8294 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8295 }
Chao Chen3c366992018-09-19 11:41:59 -07008296 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008297 }
Chao Chen3c366992018-09-19 11:41:59 -07008298 if (qualifier.perViewNV)
8299 builder.addDecoration(id, spv::DecorationPerViewNV);
8300 if (qualifier.perTaskNV)
8301 builder.addDecoration(id, spv::DecorationPerTaskNV);
8302 }
8303}
8304#endif
8305
John Kessenich55e7d112015-11-15 21:33:39 -07008306// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008307// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008308//
8309// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8310//
8311// Recursively walk the nodes. The nodes form a tree whose leaves are
8312// regular constants, which themselves are trees that createSpvConstant()
8313// recursively walks. So, this function walks the "top" of the tree:
8314// - emit specialization constant-building instructions for specConstant
8315// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008316spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008317{
John Kessenich7cc0e282016-03-20 00:46:02 -06008318 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008319
qining4f4bb812016-04-03 23:55:17 -04008320 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008321 if (! node.getQualifier().specConstant) {
8322 // hand off to the non-spec-constant path
8323 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8324 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008325 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8326 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8327 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008328 }
8329
8330 // We now know we have a specialization constant to build
8331
Ricardo Garcia232ba0d2020-06-03 15:52:55 +02008332 // Extra capabilities may be needed.
8333 if (node.getType().contains8BitInt())
8334 builder.addCapability(spv::CapabilityInt8);
8335 if (node.getType().contains16BitFloat())
8336 builder.addCapability(spv::CapabilityFloat16);
8337 if (node.getType().contains16BitInt())
8338 builder.addCapability(spv::CapabilityInt16);
8339 if (node.getType().contains64BitInt())
8340 builder.addCapability(spv::CapabilityInt64);
8341 if (node.getType().containsDouble())
8342 builder.addCapability(spv::CapabilityFloat64);
8343
John Kessenichd94c0032016-05-30 19:29:40 -06008344 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008345 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8346 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8347 std::vector<spv::Id> dimConstId;
8348 for (int dim = 0; dim < 3; ++dim) {
8349 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8350 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008351 if (specConst) {
8352 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8353 glslangIntermediate->getLocalSizeSpecId(dim));
8354 }
qining4f4bb812016-04-03 23:55:17 -04008355 }
8356 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8357 }
8358
8359 // An AST node labelled as specialization constant should be a symbol node.
8360 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8361 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008362 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008363 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008364 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8365 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8366 // will set the builder into spec constant op instruction generating mode.
8367 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008368 result = accessChainLoad(sub_tree->getType());
8369 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008370 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008371 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008372 } else {
8373 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008374 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008375 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008376 builder.addName(result, sn->getName().c_str());
8377 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008378 }
qining4f4bb812016-04-03 23:55:17 -04008379
8380 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8381 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008382 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008383 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008384}
8385
John Kessenich140f3df2015-06-26 16:58:36 -06008386// Use 'consts' as the flattened glslang source of scalar constants to recursively
8387// build the aggregate SPIR-V constant.
8388//
8389// If there are not enough elements present in 'consts', 0 will be substituted;
8390// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8391//
John Kessenich8985fc92020-03-03 10:25:07 -07008392spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8393 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008394{
8395 // vector of constants for SPIR-V
8396 std::vector<spv::Id> spvConsts;
8397
8398 // Type is used for struct and array constants
8399 spv::Id typeId = convertGlslangToSpvType(glslangType);
8400
8401 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008402 glslang::TType elementType(glslangType, 0);
8403 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008404 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008405 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008406 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008407 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008408 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008409 } else if (glslangType.isCoopMat()) {
8410 glslang::TType componentType(glslangType.getBasicType());
8411 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008412 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008413 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8414 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008415 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008416 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008417 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8418 bool zero = nextConst >= consts.size();
8419 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008420 case glslang::EbtInt:
8421 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8422 break;
8423 case glslang::EbtUint:
8424 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8425 break;
8426 case glslang::EbtFloat:
8427 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8428 break;
8429 case glslang::EbtBool:
8430 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8431 break;
8432#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008433 case glslang::EbtInt8:
8434 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8435 break;
8436 case glslang::EbtUint8:
8437 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8438 break;
8439 case glslang::EbtInt16:
8440 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8441 break;
8442 case glslang::EbtUint16:
8443 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8444 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008445 case glslang::EbtInt64:
8446 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8447 break;
8448 case glslang::EbtUint64:
8449 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8450 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008451 case glslang::EbtDouble:
8452 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8453 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008454 case glslang::EbtFloat16:
8455 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8456 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008457#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008458 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008459 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008460 break;
8461 }
8462 ++nextConst;
8463 }
8464 } else {
8465 // we have a non-aggregate (scalar) constant
8466 bool zero = nextConst >= consts.size();
8467 spv::Id scalar = 0;
8468 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008469 case glslang::EbtInt:
8470 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8471 break;
8472 case glslang::EbtUint:
8473 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8474 break;
8475 case glslang::EbtFloat:
8476 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8477 break;
8478 case glslang::EbtBool:
8479 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8480 break;
8481#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008482 case glslang::EbtInt8:
8483 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8484 break;
8485 case glslang::EbtUint8:
8486 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8487 break;
8488 case glslang::EbtInt16:
8489 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8490 break;
8491 case glslang::EbtUint16:
8492 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8493 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008494 case glslang::EbtInt64:
8495 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8496 break;
8497 case glslang::EbtUint64:
8498 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8499 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008500 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008501 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008502 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008503 case glslang::EbtFloat16:
8504 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8505 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008506 case glslang::EbtReference:
8507 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8508 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8509 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008510#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008511 case glslang::EbtString:
8512 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8513 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008514 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008515 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008516 break;
8517 }
8518 ++nextConst;
8519 return scalar;
8520 }
8521
8522 return builder.makeCompositeConstant(typeId, spvConsts);
8523}
8524
John Kessenich7c1aa102015-10-15 13:29:11 -06008525// Return true if the node is a constant or symbol whose reading has no
8526// non-trivial observable cost or effect.
8527bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8528{
8529 // don't know what this is
8530 if (node == nullptr)
8531 return false;
8532
8533 // a constant is safe
8534 if (node->getAsConstantUnion() != nullptr)
8535 return true;
8536
8537 // not a symbol means non-trivial
8538 if (node->getAsSymbolNode() == nullptr)
8539 return false;
8540
8541 // a symbol, depends on what's being read
8542 switch (node->getType().getQualifier().storage) {
8543 case glslang::EvqTemporary:
8544 case glslang::EvqGlobal:
8545 case glslang::EvqIn:
8546 case glslang::EvqInOut:
8547 case glslang::EvqConst:
8548 case glslang::EvqConstReadOnly:
8549 case glslang::EvqUniform:
8550 return true;
8551 default:
8552 return false;
8553 }
qining25262b32016-05-06 17:25:16 -04008554}
John Kessenich7c1aa102015-10-15 13:29:11 -06008555
8556// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008557// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008558// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008559// Return true if trivial.
8560bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8561{
8562 if (node == nullptr)
8563 return false;
8564
John Kessenich84cc15f2017-05-24 16:44:47 -06008565 // count non scalars as trivial, as well as anything coming from HLSL
8566 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008567 return true;
8568
John Kessenich7c1aa102015-10-15 13:29:11 -06008569 // symbols and constants are trivial
8570 if (isTrivialLeaf(node))
8571 return true;
8572
8573 // otherwise, it needs to be a simple operation or one or two leaf nodes
8574
8575 // not a simple operation
8576 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8577 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8578 if (binaryNode == nullptr && unaryNode == nullptr)
8579 return false;
8580
8581 // not on leaf nodes
8582 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8583 return false;
8584
8585 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8586 return false;
8587 }
8588
8589 switch (node->getAsOperator()->getOp()) {
8590 case glslang::EOpLogicalNot:
8591 case glslang::EOpConvIntToBool:
8592 case glslang::EOpConvUintToBool:
8593 case glslang::EOpConvFloatToBool:
8594 case glslang::EOpConvDoubleToBool:
8595 case glslang::EOpEqual:
8596 case glslang::EOpNotEqual:
8597 case glslang::EOpLessThan:
8598 case glslang::EOpGreaterThan:
8599 case glslang::EOpLessThanEqual:
8600 case glslang::EOpGreaterThanEqual:
8601 case glslang::EOpIndexDirect:
8602 case glslang::EOpIndexDirectStruct:
8603 case glslang::EOpLogicalXor:
8604 case glslang::EOpAny:
8605 case glslang::EOpAll:
8606 return true;
8607 default:
8608 return false;
8609 }
8610}
8611
8612// Emit short-circuiting code, where 'right' is never evaluated unless
8613// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008614spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8615 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008616{
8617 spv::Id boolTypeId = builder.makeBoolType();
8618
8619 // emit left operand
8620 builder.clearAccessChain();
8621 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008622 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008623
8624 // Operands to accumulate OpPhi operands
8625 std::vector<spv::Id> phiOperands;
8626 // accumulate left operand's phi information
8627 phiOperands.push_back(leftId);
8628 phiOperands.push_back(builder.getBuildPoint()->getId());
8629
8630 // Make the two kinds of operation symmetric with a "!"
8631 // || => emit "if (! left) result = right"
8632 // && => emit "if ( left) result = right"
8633 //
8634 // TODO: this runtime "not" for || could be avoided by adding functionality
8635 // to 'builder' to have an "else" without an "then"
8636 if (op == glslang::EOpLogicalOr)
8637 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8638
8639 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008640 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008641
8642 // emit right operand as the "then" part of the "if"
8643 builder.clearAccessChain();
8644 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008645 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008646
8647 // accumulate left operand's phi information
8648 phiOperands.push_back(rightId);
8649 phiOperands.push_back(builder.getBuildPoint()->getId());
8650
8651 // finish the "if"
8652 ifBuilder.makeEndIf();
8653
8654 // phi together the two results
8655 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8656}
8657
John Kessenicha28f7a72019-08-06 07:00:58 -06008658#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008659// Return type Id of the imported set of extended instructions corresponds to the name.
8660// Import this set if it has not been imported yet.
8661spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8662{
8663 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8664 return extBuiltinMap[name];
8665 else {
Rex Xu51596642016-09-21 18:56:12 +08008666 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008667 spv::Id extBuiltins = builder.import(name);
8668 extBuiltinMap[name] = extBuiltins;
8669 return extBuiltins;
8670 }
8671}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008672#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008673
John Kessenich140f3df2015-06-26 16:58:36 -06008674}; // end anonymous namespace
8675
8676namespace glslang {
8677
John Kessenich68d78fd2015-07-12 19:28:10 -06008678void GetSpirvVersion(std::string& version)
8679{
John Kessenich9e55f632015-07-15 10:03:39 -06008680 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008681 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008682 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008683 version = buf;
8684}
8685
John Kessenicha372a3e2017-11-02 22:32:14 -06008686// For low-order part of the generator's magic number. Bump up
8687// when there is a change in the style (e.g., if SSA form changes,
8688// or a different instruction sequence to do something gets used).
8689int GetSpirvGeneratorVersion()
8690{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008691 // return 1; // start
8692 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008693 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008694 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008695 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008696 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8697 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008698 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenich3641ff72020-06-10 07:38:31 -06008699 // return 8; // switch to new dead block eliminator; use OpUnreachable
Graeme Leese060882f2020-06-22 11:03:46 +01008700 // return 9; // don't include opaque function parameters in OpEntryPoint global's operand list
8701 return 10; // Generate OpFUnordNotEqual for != comparisons
John Kessenicha372a3e2017-11-02 22:32:14 -06008702}
8703
John Kessenich140f3df2015-06-26 16:58:36 -06008704// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008705void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008706{
8707 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008708 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008709 if (out.fail())
8710 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008711 for (int i = 0; i < (int)spirv.size(); ++i) {
8712 unsigned int word = spirv[i];
8713 out.write((const char*)&word, 4);
8714 }
8715 out.close();
8716}
8717
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008718// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008719void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008720{
Shahbaz Youssefi1ef2e252020-07-03 15:42:53 -04008721#if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008722 std::ofstream out;
8723 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008724 if (out.fail())
8725 printf("ERROR: Failed to open file: %s\n", baseName);
Ben Claytonfbe9a232020-06-17 11:17:19 +01008726 out << "\t// " <<
8727 GetSpirvGeneratorVersion() <<
8728 GLSLANG_VERSION_MAJOR << "." << GLSLANG_VERSION_MINOR << "." << GLSLANG_VERSION_PATCH <<
8729 GLSLANG_VERSION_FLAVOR << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008730 if (varName != nullptr) {
8731 out << "\t #pragma once" << std::endl;
8732 out << "const uint32_t " << varName << "[] = {" << std::endl;
8733 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008734 const int WORDS_PER_LINE = 8;
8735 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8736 out << "\t";
8737 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8738 const unsigned int word = spirv[i + j];
8739 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8740 if (i + j + 1 < (int)spirv.size()) {
8741 out << ",";
8742 }
8743 }
8744 out << std::endl;
8745 }
Flavio15017db2017-02-15 14:29:33 -08008746 if (varName != nullptr) {
8747 out << "};";
johnkslangf881f082020-08-04 02:13:50 -06008748 out << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008749 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008750 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008751#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008752}
8753
John Kessenich140f3df2015-06-26 16:58:36 -06008754//
8755// Set up the glslang traversal
8756//
John Kessenich4e11b612018-08-30 16:56:59 -06008757void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008758{
Lei Zhang17535f72016-05-04 15:55:59 -04008759 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008760 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008761}
8762
John Kessenich4e11b612018-08-30 16:56:59 -06008763void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008764 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008765{
John Kessenich140f3df2015-06-26 16:58:36 -06008766 TIntermNode* root = intermediate.getTreeRoot();
8767
8768 if (root == 0)
8769 return;
8770
John Kessenich4e11b612018-08-30 16:56:59 -06008771 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008772 if (options == nullptr)
8773 options = &defaultOptions;
8774
John Kessenich4e11b612018-08-30 16:56:59 -06008775 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008776
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008777 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008778 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008779 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008780 it.dumpSpv(spirv);
8781
GregFfb03a552018-03-29 11:49:14 -06008782#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008783 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8784 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008785 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008786 if ((prelegalization || options->optimizeSize) && !options->disableOptimizer) {
8787 SpirvToolsTransform(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008788 prelegalization = false;
8789 }
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008790 else if (options->stripDebugInfo) {
8791 // Strip debug info even if optimization is disabled.
8792 SpirvToolsStripDebugInfo(intermediate, spirv, logger);
8793 }
John Kessenich717c80a2018-08-23 15:17:10 -06008794
John Kessenich4e11b612018-08-30 16:56:59 -06008795 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008796 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008797
John Kessenich717c80a2018-08-23 15:17:10 -06008798 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008799 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008800
GregFcd1f1692017-09-21 18:40:22 -06008801#endif
8802
John Kessenich4e11b612018-08-30 16:56:59 -06008803 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008804}
8805
8806}; // end namespace glslang