blob: 5b7f89a56b497dbcfe3bb1b1ca99998141e65b63 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
John Kessenich56364b62020-03-01 04:51:40 -07003// Copyright (C) 2015-2020 Google, Inc.
John Kessenich66011cb2018-03-06 16:12:04 -07004// Copyright (C) 2017 ARM Limited.
Torosdagli06c2eee2020-03-19 11:09:57 -04005// Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06006//
John Kessenich927608b2017-01-06 12:34:14 -07007// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06008//
John Kessenich927608b2017-01-06 12:34:14 -07009// Redistribution and use in source and binary forms, with or without
10// modification, are permitted provided that the following conditions
11// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060012//
13// Redistributions of source code must retain the above copyright
14// notice, this list of conditions and the following disclaimer.
15//
16// Redistributions in binary form must reproduce the above
17// copyright notice, this list of conditions and the following
18// disclaimer in the documentation and/or other materials provided
19// with the distribution.
20//
21// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
22// contributors may be used to endorse or promote products derived
23// from this software without specific prior written permission.
24//
John Kessenich927608b2017-01-06 12:34:14 -070025// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
28// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
29// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
30// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
31// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
32// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
33// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060037
38//
John Kessenich140f3df2015-06-26 16:58:36 -060039// Visit the nodes in the glslang intermediate tree representation to
40// translate them to SPIR-V.
41//
42
John Kessenich5e4b1242015-08-06 22:53:06 -060043#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060044#include "GlslangToSpv.h"
45#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060046namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080047 #include "GLSL.std.450.h"
48 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070049 #include "GLSL.ext.EXT.h"
Rex Xu51596642016-09-21 18:56:12 +080050 #include "GLSL.ext.AMD.h"
chaoc0ad6a4e2016-12-19 16:29:34 -080051 #include "GLSL.ext.NV.h"
Jeff Bolz04d73732019-05-31 13:06:01 -050052 #include "NonSemanticDebugPrintf.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Ben Claytonfbe9a232020-06-17 11:17:19 +010059
60// Build-time generated includes
61#include "glslang/build_info.h"
John Kessenich140f3df2015-06-26 16:58:36 -060062
John Kessenich140f3df2015-06-26 16:58:36 -060063#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050064#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040065#include <list>
66#include <map>
67#include <stack>
68#include <string>
69#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060070
71namespace {
72
qining4c912612016-04-01 10:35:16 -040073namespace {
74class SpecConstantOpModeGuard {
75public:
76 SpecConstantOpModeGuard(spv::Builder* builder)
77 : builder_(builder) {
78 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040079 }
80 ~SpecConstantOpModeGuard() {
81 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
82 : builder_->setToNormalCodeGenMode();
83 }
qining40887662016-04-03 22:20:42 -040084 void turnOnSpecConstantOpMode() {
85 builder_->setToSpecConstCodeGenMode();
86 }
qining4c912612016-04-01 10:35:16 -040087
88private:
89 spv::Builder* builder_;
90 bool previous_flag_;
91};
John Kessenichead86222018-03-28 18:01:20 -060092
93struct OpDecorations {
John Kessenichb9197c82019-08-11 07:41:45 -060094 public:
95 OpDecorations(spv::Decoration precision, spv::Decoration noContraction, spv::Decoration nonUniform) :
96 precision(precision)
97#ifndef GLSLANG_WEB
98 ,
99 noContraction(noContraction),
100 nonUniform(nonUniform)
101#endif
102 { }
103
John Kessenichead86222018-03-28 18:01:20 -0600104 spv::Decoration precision;
John Kessenichb9197c82019-08-11 07:41:45 -0600105
106#ifdef GLSLANG_WEB
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400107 void addNoContraction(spv::Builder&, spv::Id) const { }
108 void addNonUniform(spv::Builder&, spv::Id) const { }
John Kessenichb9197c82019-08-11 07:41:45 -0600109#else
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400110 void addNoContraction(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, noContraction); }
111 void addNonUniform(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, nonUniform); }
John Kessenichb9197c82019-08-11 07:41:45 -0600112 protected:
113 spv::Decoration noContraction;
114 spv::Decoration nonUniform;
115#endif
116
John Kessenichead86222018-03-28 18:01:20 -0600117};
118
119} // namespace
qining4c912612016-04-01 10:35:16 -0400120
John Kessenich140f3df2015-06-26 16:58:36 -0600121//
122// The main holder of information for translating glslang to SPIR-V.
123//
124// Derives from the AST walking base class.
125//
126class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
127public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700128 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
129 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700130 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600131
132 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
133 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
134 void visitConstantUnion(glslang::TIntermConstantUnion*);
135 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
136 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
137 void visitSymbol(glslang::TIntermSymbol* symbol);
138 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
139 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
140 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
141
John Kessenichfca82622016-11-26 13:23:20 -0700142 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700143 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600144
145protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700146 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
147 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
148
Rex Xu17ff3432016-10-14 17:41:45 +0800149 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800150 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600151 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500152 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
153 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
154 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
155 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100156 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700157 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700158 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
159 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700160 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600161 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600162 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich9c14f772019-06-17 08:38:35 -0600163 spv::Id createSpvVariable(const glslang::TIntermSymbol*, spv::Id forcedType);
John Kessenich140f3df2015-06-26 16:58:36 -0600164 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600165 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
166 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
167 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600168 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600169 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600170 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600171 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600172 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
173 glslang::TLayoutPacking, const glslang::TQualifier&);
174 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
175 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700176 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700177 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800178 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600179 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700180 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700181 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
182 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700183 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
184 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100185 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600186
John Kessenich6fccb3c2016-09-19 16:01:41 -0600187 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600188 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600189 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600190 void makeFunctions(const glslang::TIntermSequence&);
191 void makeGlobalInitializers(const glslang::TIntermSequence&);
192 void visitFunctions(const glslang::TIntermSequence&);
193 void handleFunctionEntry(const glslang::TIntermAggregate* node);
John Kessenich8985fc92020-03-03 10:25:07 -0700194 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
195 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -0600196 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
197 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600198 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
199
John Kessenichead86222018-03-28 18:01:20 -0600200 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
201 glslang::TBasicType typeProxy, bool reduceComparison = true);
202 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
203 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
John Kessenich8985fc92020-03-03 10:25:07 -0700204 glslang::TBasicType typeProxy,
205 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -0600206 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
207 glslang::TBasicType typeProxy);
208 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
209 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600210 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600211 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
John Kessenich8985fc92020-03-03 10:25:07 -0700212 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId,
213 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
214 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
215 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands,
216 glslang::TBasicType typeProxy);
217 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
218 spv::Id typeId, std::vector<spv::Id>& operands);
219 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands,
220 glslang::TBasicType typeProxy);
221 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId,
222 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800223 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600224 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700225 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
qining08408382016-03-21 09:51:37 -0400226 spv::Id createSpvConstant(const glslang::TIntermTyped&);
John Kessenich8985fc92020-03-03 10:25:07 -0700227 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&,
228 int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600229 bool isTrivialLeaf(const glslang::TIntermTyped* node);
230 bool isTrivial(const glslang::TIntermTyped* node);
231 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800232 spv::Id getExtBuiltins(const char* name);
Daniel Kochdb32b242020-03-17 20:42:47 -0400233 std::pair<spv::Id, spv::Id> getForcedType(glslang::TBuiltInVariable builtIn, const glslang::TType&);
John Kessenich9c14f772019-06-17 08:38:35 -0600234 spv::Id translateForcedType(spv::Id object);
Jeff Bolz53134492019-06-25 13:31:10 -0500235 spv::Id createCompositeConstruct(spv::Id typeId, std::vector<spv::Id> constituents);
John Kessenich140f3df2015-06-26 16:58:36 -0600236
John Kessenich121853f2017-05-31 17:11:16 -0600237 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600238 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600239 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700240 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600241 int sequenceDepth;
242
Lei Zhang17535f72016-05-04 15:55:59 -0400243 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400244
John Kessenich140f3df2015-06-26 16:58:36 -0600245 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
246 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700247 bool inEntryPoint;
248 bool entryPointTerminated;
John Kessenich8985fc92020-03-03 10:25:07 -0700249 bool linkageOnly; // true when visiting the set of objects in the AST present only for
250 // establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700251 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600252 const glslang::TIntermediate* glslangIntermediate;
John Kessenich605afc72019-06-17 23:33:09 -0600253 bool nanMinMaxClamp; // true if use NMin/NMax/NClamp instead of FMin/FMax/FClamp
John Kessenich140f3df2015-06-26 16:58:36 -0600254 spv::Id stdBuiltins;
Jeff Bolz04d73732019-05-31 13:06:01 -0500255 spv::Id nonSemanticDebugPrintf;
Rex Xu9d93a232016-05-05 12:30:44 +0800256 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600257
John Kessenich2f273362015-07-18 22:34:27 -0600258 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich8985fc92020-03-03 10:25:07 -0700259 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues,
260 // rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600261 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700262 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700263 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
Roy05a5b532020-01-03 16:21:34 +0800264 std::unordered_map<int, std::vector<int>> memberRemapper;
265 // for mapping glslang symbol struct to symbol Id
266 std::unordered_map<const glslang::TTypeList*, int> glslangTypeToIdMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600267 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700268 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600269 // Map pointee types for EbtReference to their forward pointers
270 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich9c14f772019-06-17 08:38:35 -0600271 // Type forcing, for when SPIR-V wants a different type than the AST,
272 // requiring local translation to and from SPIR-V type on every access.
273 // Maps <builtin-variable-id -> AST-required-type-id>
274 std::unordered_map<spv::Id, spv::Id> forceType;
John Kessenich140f3df2015-06-26 16:58:36 -0600275};
276
277//
278// Helper functions for translating glslang representations to SPIR-V enumerants.
279//
280
281// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700282spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600283{
John Kessenich155d3512019-08-08 23:29:20 -0600284#ifdef GLSLANG_WEB
285 return spv::SourceLanguageESSL;
Shahbaz Youssefi1ef2e252020-07-03 15:42:53 -0400286#elif defined(GLSLANG_ANGLE)
287 return spv::SourceLanguageGLSL;
John Kessenich155d3512019-08-08 23:29:20 -0600288#endif
289
John Kessenich66e2faf2016-03-12 18:34:36 -0700290 switch (source) {
291 case glslang::EShSourceGlsl:
292 switch (profile) {
293 case ENoProfile:
294 case ECoreProfile:
295 case ECompatibilityProfile:
296 return spv::SourceLanguageGLSL;
297 case EEsProfile:
298 return spv::SourceLanguageESSL;
299 default:
300 return spv::SourceLanguageUnknown;
301 }
302 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600303 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600304 default:
305 return spv::SourceLanguageUnknown;
306 }
307}
308
309// Translate glslang language (stage) to SPIR-V execution model.
310spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
311{
312 switch (stage) {
313 case EShLangVertex: return spv::ExecutionModelVertex;
John Kessenicha28f7a72019-08-06 07:00:58 -0600314 case EShLangFragment: return spv::ExecutionModelFragment;
John Kessenicha28f7a72019-08-06 07:00:58 -0600315 case EShLangCompute: return spv::ExecutionModelGLCompute;
John Kessenich51ed01c2019-10-10 11:40:11 -0600316#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -0600317 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
318 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
319 case EShLangGeometry: return spv::ExecutionModelGeometry;
Daniel Kochdb32b242020-03-17 20:42:47 -0400320 case EShLangRayGen: return spv::ExecutionModelRayGenerationKHR;
321 case EShLangIntersect: return spv::ExecutionModelIntersectionKHR;
322 case EShLangAnyHit: return spv::ExecutionModelAnyHitKHR;
323 case EShLangClosestHit: return spv::ExecutionModelClosestHitKHR;
324 case EShLangMiss: return spv::ExecutionModelMissKHR;
325 case EShLangCallable: return spv::ExecutionModelCallableKHR;
Chao Chen3c366992018-09-19 11:41:59 -0700326 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
327 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
328#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600329 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700330 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600331 return spv::ExecutionModelFragment;
332 }
333}
334
John Kessenich140f3df2015-06-26 16:58:36 -0600335// Translate glslang sampler type to SPIR-V dimensionality.
336spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
337{
338 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700339 case glslang::Esd1D: return spv::Dim1D;
340 case glslang::Esd2D: return spv::Dim2D;
341 case glslang::Esd3D: return spv::Dim3D;
342 case glslang::EsdCube: return spv::DimCube;
343 case glslang::EsdRect: return spv::DimRect;
344 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700345 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600346 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700347 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600348 return spv::Dim2D;
349 }
350}
351
John Kessenichf6640762016-08-01 19:44:00 -0600352// Translate glslang precision to SPIR-V precision decorations.
353spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600354{
John Kessenichf6640762016-08-01 19:44:00 -0600355 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700356 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600357 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600358 default:
359 return spv::NoPrecision;
360 }
361}
362
John Kessenichf6640762016-08-01 19:44:00 -0600363// Translate glslang type to SPIR-V precision decorations.
364spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
365{
366 return TranslatePrecisionDecoration(type.getQualifier().precision);
367}
368
John Kessenich140f3df2015-06-26 16:58:36 -0600369// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600370spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600371{
372 if (type.getBasicType() == glslang::EbtBlock) {
373 switch (type.getQualifier().storage) {
374 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600375 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600376 case glslang::EvqVaryingIn: return spv::DecorationBlock;
377 case glslang::EvqVaryingOut: return spv::DecorationBlock;
John Kessenicha28f7a72019-08-06 07:00:58 -0600378#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -0400379 case glslang::EvqPayload: return spv::DecorationBlock;
380 case glslang::EvqPayloadIn: return spv::DecorationBlock;
381 case glslang::EvqHitAttr: return spv::DecorationBlock;
382 case glslang::EvqCallableData: return spv::DecorationBlock;
383 case glslang::EvqCallableDataIn: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700384#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600385 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700386 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600387 break;
388 }
389 }
390
John Kessenich4016e382016-07-15 11:53:56 -0600391 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600392}
393
Rex Xu1da878f2016-02-21 20:59:01 +0800394// Translate glslang type to SPIR-V memory decorations.
John Kessenich8985fc92020-03-03 10:25:07 -0700395void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory,
396 bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800397{
Jeff Bolz36831c92018-09-05 10:11:41 -0500398 if (!useVulkanMemoryModel) {
John Kessenichf8d1d742019-10-21 06:55:11 -0600399 if (qualifier.isCoherent())
Jeff Bolz36831c92018-09-05 10:11:41 -0500400 memory.push_back(spv::DecorationCoherent);
John Kessenichf8d1d742019-10-21 06:55:11 -0600401 if (qualifier.isVolatile()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500402 memory.push_back(spv::DecorationVolatile);
403 memory.push_back(spv::DecorationCoherent);
404 }
John Kessenich14b85d32018-06-04 15:36:03 -0600405 }
John Kessenichf8d1d742019-10-21 06:55:11 -0600406 if (qualifier.isRestrict())
Rex Xu1da878f2016-02-21 20:59:01 +0800407 memory.push_back(spv::DecorationRestrict);
John Kessenichdeec1932019-08-13 08:00:30 -0600408 if (qualifier.isReadOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800409 memory.push_back(spv::DecorationNonWritable);
John Kessenichdeec1932019-08-13 08:00:30 -0600410 if (qualifier.isWriteOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800411 memory.push_back(spv::DecorationNonReadable);
412}
413
John Kessenich140f3df2015-06-26 16:58:36 -0600414// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700415spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600416{
417 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700418 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600419 case glslang::ElmRowMajor:
420 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700421 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600422 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700423 default:
424 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600425 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600426 }
427 } else {
428 switch (type.getBasicType()) {
429 default:
John Kessenich4016e382016-07-15 11:53:56 -0600430 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600431 break;
432 case glslang::EbtBlock:
433 switch (type.getQualifier().storage) {
434 case glslang::EvqUniform:
435 case glslang::EvqBuffer:
436 switch (type.getQualifier().layoutPacking) {
437 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600438 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
439 default:
John Kessenich4016e382016-07-15 11:53:56 -0600440 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600441 }
442 case glslang::EvqVaryingIn:
443 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700444 if (type.getQualifier().isTaskMemory()) {
445 switch (type.getQualifier().layoutPacking) {
446 case glslang::ElpShared: return spv::DecorationGLSLShared;
447 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
448 default: break;
449 }
450 } else {
451 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
452 }
John Kessenich4016e382016-07-15 11:53:56 -0600453 return spv::DecorationMax;
John Kessenicha28f7a72019-08-06 07:00:58 -0600454#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -0400455 case glslang::EvqPayload:
456 case glslang::EvqPayloadIn:
457 case glslang::EvqHitAttr:
458 case glslang::EvqCallableData:
459 case glslang::EvqCallableDataIn:
Chao Chenb50c02e2018-09-19 11:42:24 -0700460 return spv::DecorationMax;
461#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600462 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700463 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600464 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600465 }
466 }
467 }
468}
469
470// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600471// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700472// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800473spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600474{
Rex Xubbceed72016-05-21 09:40:44 +0800475 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700476 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600477 return spv::DecorationMax;
John Kessenich7015bd62019-08-01 03:28:08 -0600478 else if (qualifier.isNonPerspective())
John Kessenich55e7d112015-11-15 21:33:39 -0700479 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700480 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600481 return spv::DecorationFlat;
John Kessenicha28f7a72019-08-06 07:00:58 -0600482 else if (qualifier.isExplicitInterpolation()) {
Rex Xu17ff3432016-10-14 17:41:45 +0800483 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800484 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800485 }
Rex Xubbceed72016-05-21 09:40:44 +0800486 else
John Kessenich4016e382016-07-15 11:53:56 -0600487 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800488}
489
490// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600491// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800492// should be applied.
493spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
494{
John Kessenichb9197c82019-08-11 07:41:45 -0600495 if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600496 return spv::DecorationCentroid;
John Kessenichb9197c82019-08-11 07:41:45 -0600497#ifndef GLSLANG_WEB
498 else if (qualifier.patch)
499 return spv::DecorationPatch;
John Kessenich5e801132016-02-15 11:09:46 -0700500 else if (qualifier.sample) {
501 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600502 return spv::DecorationSample;
John Kessenichb9197c82019-08-11 07:41:45 -0600503 }
504#endif
505
506 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600507}
508
John Kessenich92187592016-02-01 13:45:25 -0700509// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700510spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600511{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700512 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600513 return spv::DecorationInvariant;
514 else
John Kessenich4016e382016-07-15 11:53:56 -0600515 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600516}
517
qining9220dbb2016-05-04 17:34:38 -0400518// If glslang type is noContraction, return SPIR-V NoContraction decoration.
519spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
520{
John Kessenichb9197c82019-08-11 07:41:45 -0600521#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -0600522 if (qualifier.isNoContraction())
qining9220dbb2016-05-04 17:34:38 -0400523 return spv::DecorationNoContraction;
524 else
John Kessenichb9197c82019-08-11 07:41:45 -0600525#endif
John Kessenich4016e382016-07-15 11:53:56 -0600526 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400527}
528
John Kessenich5611c6d2018-04-05 11:25:02 -0600529// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
530spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
531{
John Kessenichb9197c82019-08-11 07:41:45 -0600532#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -0600533 if (qualifier.isNonUniform()) {
John Kessenich8317e6c2019-08-18 23:58:08 -0600534 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -0600535 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
536 return spv::DecorationNonUniformEXT;
537 } else
John Kessenichb9197c82019-08-11 07:41:45 -0600538#endif
John Kessenich5611c6d2018-04-05 11:25:02 -0600539 return spv::DecorationMax;
540}
541
John Kessenichb9197c82019-08-11 07:41:45 -0600542spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(
543 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500544{
Jeff Bolz36831c92018-09-05 10:11:41 -0500545 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600546
547#ifndef GLSLANG_WEB
548 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage)
549 return mask;
550
Daniel Kochdb32b242020-03-17 20:42:47 -0400551 if (coherentFlags.isVolatile() || coherentFlags.anyCoherent()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500552 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
553 spv::MemoryAccessMakePointerVisibleKHRMask;
554 }
Daniel Kochdb32b242020-03-17 20:42:47 -0400555
Jeff Bolz36831c92018-09-05 10:11:41 -0500556 if (coherentFlags.nonprivate) {
557 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
558 }
559 if (coherentFlags.volatil) {
560 mask = mask | spv::MemoryAccessVolatileMask;
561 }
562 if (mask != spv::MemoryAccessMaskNone) {
563 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
564 }
John Kessenichb9197c82019-08-11 07:41:45 -0600565#endif
566
Jeff Bolz36831c92018-09-05 10:11:41 -0500567 return mask;
568}
569
John Kessenichb9197c82019-08-11 07:41:45 -0600570spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(
571 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500572{
Jeff Bolz36831c92018-09-05 10:11:41 -0500573 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600574
575#ifndef GLSLANG_WEB
576 if (!glslangIntermediate->usingVulkanMemoryModel())
577 return mask;
578
Jeff Bolz36831c92018-09-05 10:11:41 -0500579 if (coherentFlags.volatil ||
Daniel Kochdb32b242020-03-17 20:42:47 -0400580 coherentFlags.anyCoherent()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500581 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
582 spv::ImageOperandsMakeTexelVisibleKHRMask;
583 }
584 if (coherentFlags.nonprivate) {
585 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
586 }
587 if (coherentFlags.volatil) {
588 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
589 }
590 if (mask != spv::ImageOperandsMaskNone) {
591 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
592 }
John Kessenichb9197c82019-08-11 07:41:45 -0600593#endif
594
Jeff Bolz36831c92018-09-05 10:11:41 -0500595 return mask;
596}
597
598spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
599{
John Kessenichb9197c82019-08-11 07:41:45 -0600600 spv::Builder::AccessChain::CoherentFlags flags = {};
601#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -0500602 flags.coherent = type.getQualifier().coherent;
603 flags.devicecoherent = type.getQualifier().devicecoherent;
604 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
605 // shared variables are implicitly workgroupcoherent in GLSL.
606 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
607 type.getQualifier().storage == glslang::EvqShared;
608 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Daniel Kochdb32b242020-03-17 20:42:47 -0400609 flags.shadercallcoherent = type.getQualifier().shadercallcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600610 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500611 // *coherent variables are implicitly nonprivate in GLSL
612 flags.nonprivate = type.getQualifier().nonprivate ||
Daniel Kochdb32b242020-03-17 20:42:47 -0400613 flags.anyCoherent() ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600614 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500615 flags.isImage = type.getBasicType() == glslang::EbtSampler;
John Kessenichb9197c82019-08-11 07:41:45 -0600616#endif
Jeff Bolz36831c92018-09-05 10:11:41 -0500617 return flags;
618}
619
John Kessenichb9197c82019-08-11 07:41:45 -0600620spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(
621 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500622{
John Kessenichb9197c82019-08-11 07:41:45 -0600623 spv::Scope scope = spv::ScopeMax;
624
625#ifndef GLSLANG_WEB
Jeff Bolz38cbad12019-03-05 14:40:07 -0600626 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500627 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
628 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
629 } else if (coherentFlags.devicecoherent) {
630 scope = spv::ScopeDevice;
631 } else if (coherentFlags.queuefamilycoherent) {
632 scope = spv::ScopeQueueFamilyKHR;
633 } else if (coherentFlags.workgroupcoherent) {
634 scope = spv::ScopeWorkgroup;
635 } else if (coherentFlags.subgroupcoherent) {
636 scope = spv::ScopeSubgroup;
Daniel Kochdb32b242020-03-17 20:42:47 -0400637 } else if (coherentFlags.shadercallcoherent) {
638 scope = spv::ScopeShaderCallKHR;
Jeff Bolz36831c92018-09-05 10:11:41 -0500639 }
640 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
641 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
642 }
John Kessenichb9197c82019-08-11 07:41:45 -0600643#endif
644
Jeff Bolz36831c92018-09-05 10:11:41 -0500645 return scope;
646}
647
David Netoa901ffe2016-06-08 14:11:40 +0100648// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
649// associated capabilities when required. For some built-in variables, a capability
650// is generated only when using the variable in an executable instruction, but not when
651// just declaring a struct member variable with it. This is true for PointSize,
652// ClipDistance, and CullDistance.
John Kessenich8985fc92020-03-03 10:25:07 -0700653spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn,
654 bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600655{
656 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700657 case glslang::EbvPointSize:
John Kessenich155d3512019-08-08 23:29:20 -0600658#ifndef GLSLANG_WEB
John Kessenich78a45572016-07-08 14:05:15 -0600659 // Defer adding the capability until the built-in is actually used.
660 if (! memberDeclaration) {
661 switch (glslangIntermediate->getStage()) {
662 case EShLangGeometry:
663 builder.addCapability(spv::CapabilityGeometryPointSize);
664 break;
665 case EShLangTessControl:
666 case EShLangTessEvaluation:
667 builder.addCapability(spv::CapabilityTessellationPointSize);
668 break;
669 default:
670 break;
671 }
John Kessenich92187592016-02-01 13:45:25 -0700672 }
John Kessenich155d3512019-08-08 23:29:20 -0600673#endif
John Kessenich92187592016-02-01 13:45:25 -0700674 return spv::BuiltInPointSize;
675
John Kessenicha28f7a72019-08-06 07:00:58 -0600676 case glslang::EbvPosition: return spv::BuiltInPosition;
677 case glslang::EbvVertexId: return spv::BuiltInVertexId;
678 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
679 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
680 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
681
682 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
683 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
684 case glslang::EbvFace: return spv::BuiltInFrontFacing;
685 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
686
John Kessenich3dd1ce52019-10-17 07:08:40 -0600687 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
688 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
689 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
690 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
691 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
692 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
693
John Kessenicha28f7a72019-08-06 07:00:58 -0600694#ifndef GLSLANG_WEB
John Kessenichebb50532016-05-16 19:22:05 -0600695 // These *Distance capabilities logically belong here, but if the member is declared and
696 // then never used, consumers of SPIR-V prefer the capability not be declared.
697 // They are now generated when used, rather than here when declared.
698 // Potentially, the specification should be more clear what the minimum
699 // use needed is to trigger the capability.
700 //
John Kessenich92187592016-02-01 13:45:25 -0700701 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100702 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800703 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700704 return spv::BuiltInClipDistance;
705
706 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100707 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800708 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700709 return spv::BuiltInCullDistance;
710
711 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600712 builder.addCapability(spv::CapabilityMultiViewport);
713 if (glslangIntermediate->getStage() == EShLangVertex ||
714 glslangIntermediate->getStage() == EShLangTessControl ||
715 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800716
John Kessenich8317e6c2019-08-18 23:58:08 -0600717 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600718 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800719 }
John Kessenich92187592016-02-01 13:45:25 -0700720 return spv::BuiltInViewportIndex;
721
John Kessenich5e801132016-02-15 11:09:46 -0700722 case glslang::EbvSampleId:
723 builder.addCapability(spv::CapabilitySampleRateShading);
724 return spv::BuiltInSampleId;
725
726 case glslang::EbvSamplePosition:
727 builder.addCapability(spv::CapabilitySampleRateShading);
728 return spv::BuiltInSamplePosition;
729
730 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700731 return spv::BuiltInSampleMask;
732
John Kessenich78a45572016-07-08 14:05:15 -0600733 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700734 if (glslangIntermediate->getStage() == EShLangMeshNV) {
735 return spv::BuiltInLayer;
736 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600737 builder.addCapability(spv::CapabilityGeometry);
738 if (glslangIntermediate->getStage() == EShLangVertex ||
739 glslangIntermediate->getStage() == EShLangTessControl ||
740 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800741
John Kessenich8317e6c2019-08-18 23:58:08 -0600742 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600743 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800744 }
John Kessenich78a45572016-07-08 14:05:15 -0600745 return spv::BuiltInLayer;
746
John Kessenichda581a22015-10-14 14:10:30 -0600747 case glslang::EbvBaseVertex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600748 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800749 builder.addCapability(spv::CapabilityDrawParameters);
750 return spv::BuiltInBaseVertex;
751
John Kessenichda581a22015-10-14 14:10:30 -0600752 case glslang::EbvBaseInstance:
John Kessenich8317e6c2019-08-18 23:58:08 -0600753 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800754 builder.addCapability(spv::CapabilityDrawParameters);
755 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200756
John Kessenichda581a22015-10-14 14:10:30 -0600757 case glslang::EbvDrawId:
John Kessenich8317e6c2019-08-18 23:58:08 -0600758 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800759 builder.addCapability(spv::CapabilityDrawParameters);
760 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200761
762 case glslang::EbvPrimitiveId:
763 if (glslangIntermediate->getStage() == EShLangFragment)
764 builder.addCapability(spv::CapabilityGeometry);
765 return spv::BuiltInPrimitiveId;
766
Rex Xu37cdcee2017-06-29 17:46:34 +0800767 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800768 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
769 builder.addCapability(spv::CapabilityStencilExportEXT);
770 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800771
Chowa315b562020-07-02 15:50:36 +0800772 case glslang::EbvShadingRateKHR:
773 builder.addExtension(spv::E_SPV_KHR_fragment_shading_rate);
774 builder.addCapability(spv::CapabilityFragmentShadingRateKHR);
775 return spv::BuiltInShadingRateKHR;
776
777 case glslang::EbvPrimitiveShadingRateKHR:
778 builder.addExtension(spv::E_SPV_KHR_fragment_shading_rate);
779 builder.addCapability(spv::CapabilityFragmentShadingRateKHR);
780 return spv::BuiltInPrimitiveShadingRateKHR;
781
John Kessenich140f3df2015-06-26 16:58:36 -0600782 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600783 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
784 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
785 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
786 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
John Kessenich140f3df2015-06-26 16:58:36 -0600787 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
Rex Xu51596642016-09-21 18:56:12 +0800788
Rex Xu574ab042016-04-14 16:53:07 +0800789 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800790 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800791 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
792 return spv::BuiltInSubgroupSize;
793
Rex Xu574ab042016-04-14 16:53:07 +0800794 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800795 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800796 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
797 return spv::BuiltInSubgroupLocalInvocationId;
798
Rex Xu574ab042016-04-14 16:53:07 +0800799 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800800 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
801 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600802 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800803
Rex Xu574ab042016-04-14 16:53:07 +0800804 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800805 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
806 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600807 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800808
Rex Xu574ab042016-04-14 16:53:07 +0800809 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800810 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
811 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600812 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800813
Rex Xu574ab042016-04-14 16:53:07 +0800814 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800815 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
816 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600817 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800818
Rex Xu574ab042016-04-14 16:53:07 +0800819 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800820 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
821 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600822 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800823
John Kessenich66011cb2018-03-06 16:12:04 -0700824 case glslang::EbvNumSubgroups:
825 builder.addCapability(spv::CapabilityGroupNonUniform);
826 return spv::BuiltInNumSubgroups;
827
828 case glslang::EbvSubgroupID:
829 builder.addCapability(spv::CapabilityGroupNonUniform);
830 return spv::BuiltInSubgroupId;
831
832 case glslang::EbvSubgroupSize2:
833 builder.addCapability(spv::CapabilityGroupNonUniform);
834 return spv::BuiltInSubgroupSize;
835
836 case glslang::EbvSubgroupInvocation2:
837 builder.addCapability(spv::CapabilityGroupNonUniform);
838 return spv::BuiltInSubgroupLocalInvocationId;
839
840 case glslang::EbvSubgroupEqMask2:
841 builder.addCapability(spv::CapabilityGroupNonUniform);
842 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
843 return spv::BuiltInSubgroupEqMask;
844
845 case glslang::EbvSubgroupGeMask2:
846 builder.addCapability(spv::CapabilityGroupNonUniform);
847 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
848 return spv::BuiltInSubgroupGeMask;
849
850 case glslang::EbvSubgroupGtMask2:
851 builder.addCapability(spv::CapabilityGroupNonUniform);
852 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
853 return spv::BuiltInSubgroupGtMask;
854
855 case glslang::EbvSubgroupLeMask2:
856 builder.addCapability(spv::CapabilityGroupNonUniform);
857 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
858 return spv::BuiltInSubgroupLeMask;
859
860 case glslang::EbvSubgroupLtMask2:
861 builder.addCapability(spv::CapabilityGroupNonUniform);
862 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
863 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600864
Rex Xu17ff3432016-10-14 17:41:45 +0800865 case glslang::EbvBaryCoordNoPersp:
866 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
867 return spv::BuiltInBaryCoordNoPerspAMD;
868
869 case glslang::EbvBaryCoordNoPerspCentroid:
870 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
871 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
872
873 case glslang::EbvBaryCoordNoPerspSample:
874 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
875 return spv::BuiltInBaryCoordNoPerspSampleAMD;
876
877 case glslang::EbvBaryCoordSmooth:
878 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
879 return spv::BuiltInBaryCoordSmoothAMD;
880
881 case glslang::EbvBaryCoordSmoothCentroid:
882 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
883 return spv::BuiltInBaryCoordSmoothCentroidAMD;
884
885 case glslang::EbvBaryCoordSmoothSample:
886 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
887 return spv::BuiltInBaryCoordSmoothSampleAMD;
888
889 case glslang::EbvBaryCoordPullModel:
890 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
891 return spv::BuiltInBaryCoordPullModelAMD;
chaoc771d89f2017-01-13 01:10:53 -0800892
John Kessenich6c8aaac2017-02-27 01:20:51 -0700893 case glslang::EbvDeviceIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600894 builder.addIncorporatedExtension(spv::E_SPV_KHR_device_group, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700895 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700896 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700897
898 case glslang::EbvViewIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600899 builder.addIncorporatedExtension(spv::E_SPV_KHR_multiview, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700900 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700901 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700902
Daniel Koch5154db52018-11-26 10:01:58 -0500903 case glslang::EbvFragSizeEXT:
904 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
905 builder.addCapability(spv::CapabilityFragmentDensityEXT);
906 return spv::BuiltInFragSizeEXT;
907
908 case glslang::EbvFragInvocationCountEXT:
909 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
910 builder.addCapability(spv::CapabilityFragmentDensityEXT);
911 return spv::BuiltInFragInvocationCountEXT;
912
chaoc771d89f2017-01-13 01:10:53 -0800913 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800914 if (!memberDeclaration) {
915 builder.addExtension(spv::E_SPV_NV_viewport_array2);
916 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
917 }
chaoc771d89f2017-01-13 01:10:53 -0800918 return spv::BuiltInViewportMaskNV;
919 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800920 if (!memberDeclaration) {
921 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
922 builder.addCapability(spv::CapabilityShaderStereoViewNV);
923 }
chaoc771d89f2017-01-13 01:10:53 -0800924 return spv::BuiltInSecondaryPositionNV;
925 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800926 if (!memberDeclaration) {
927 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
928 builder.addCapability(spv::CapabilityShaderStereoViewNV);
929 }
chaoc771d89f2017-01-13 01:10:53 -0800930 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800931 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800932 if (!memberDeclaration) {
933 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
934 builder.addCapability(spv::CapabilityPerViewAttributesNV);
935 }
chaocdf3956c2017-02-14 14:52:34 -0800936 return spv::BuiltInPositionPerViewNV;
937 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800938 if (!memberDeclaration) {
939 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
940 builder.addCapability(spv::CapabilityPerViewAttributesNV);
941 }
chaocdf3956c2017-02-14 14:52:34 -0800942 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700943 case glslang::EbvFragFullyCoveredNV:
944 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
945 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
946 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700947 case glslang::EbvFragmentSizeNV:
948 builder.addExtension(spv::E_SPV_NV_shading_rate);
949 builder.addCapability(spv::CapabilityShadingRateNV);
950 return spv::BuiltInFragmentSizeNV;
951 case glslang::EbvInvocationsPerPixelNV:
952 builder.addExtension(spv::E_SPV_NV_shading_rate);
953 builder.addCapability(spv::CapabilityShadingRateNV);
954 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700955
Daniel Koch593a4e02019-05-27 16:46:31 -0400956 // ray tracing
Daniel Kochdb32b242020-03-17 20:42:47 -0400957 case glslang::EbvLaunchId:
958 return spv::BuiltInLaunchIdKHR;
959 case glslang::EbvLaunchSize:
960 return spv::BuiltInLaunchSizeKHR;
961 case glslang::EbvWorldRayOrigin:
962 return spv::BuiltInWorldRayOriginKHR;
963 case glslang::EbvWorldRayDirection:
964 return spv::BuiltInWorldRayDirectionKHR;
965 case glslang::EbvObjectRayOrigin:
966 return spv::BuiltInObjectRayOriginKHR;
967 case glslang::EbvObjectRayDirection:
968 return spv::BuiltInObjectRayDirectionKHR;
969 case glslang::EbvRayTmin:
970 return spv::BuiltInRayTminKHR;
971 case glslang::EbvRayTmax:
972 return spv::BuiltInRayTmaxKHR;
973 case glslang::EbvInstanceCustomIndex:
974 return spv::BuiltInInstanceCustomIndexKHR;
975 case glslang::EbvHitT:
976 return spv::BuiltInHitTKHR;
977 case glslang::EbvHitKind:
978 return spv::BuiltInHitKindKHR;
979 case glslang::EbvObjectToWorld:
980 case glslang::EbvObjectToWorld3x4:
981 return spv::BuiltInObjectToWorldKHR;
982 case glslang::EbvWorldToObject:
983 case glslang::EbvWorldToObject3x4:
984 return spv::BuiltInWorldToObjectKHR;
985 case glslang::EbvIncomingRayFlags:
986 return spv::BuiltInIncomingRayFlagsKHR;
987 case glslang::EbvGeometryIndex:
988 return spv::BuiltInRayGeometryIndexKHR;
Daniel Koch593a4e02019-05-27 16:46:31 -0400989
990 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700991 case glslang::EbvBaryCoordNV:
992 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
993 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
994 return spv::BuiltInBaryCoordNV;
995 case glslang::EbvBaryCoordNoPerspNV:
996 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
997 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
998 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400999
1000 // mesh shaders
1001 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001002 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001003 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001004 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001005 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -07001006 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001007 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001008 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001009 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001010 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001011 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001012 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001013 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001014 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001015 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -07001016 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch2cb2f192019-06-04 08:43:32 -04001017
1018 // sm builtins
1019 case glslang::EbvWarpsPerSM:
1020 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1021 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1022 return spv::BuiltInWarpsPerSMNV;
1023 case glslang::EbvSMCount:
1024 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1025 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1026 return spv::BuiltInSMCountNV;
1027 case glslang::EbvWarpID:
1028 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1029 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1030 return spv::BuiltInWarpIDNV;
1031 case glslang::EbvSMID:
1032 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1033 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1034 return spv::BuiltInSMIDNV;
John Kessenicha28f7a72019-08-06 07:00:58 -06001035#endif
1036
Rex Xu3e783f92017-02-22 16:44:48 +08001037 default:
1038 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -06001039 }
1040}
1041
Rex Xufc618912015-09-09 16:42:49 +08001042// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -07001043spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +08001044{
1045 assert(type.getBasicType() == glslang::EbtSampler);
1046
John Kessenichb9197c82019-08-11 07:41:45 -06001047#ifdef GLSLANG_WEB
1048 return spv::ImageFormatUnknown;
1049#endif
1050
John Kessenich5d0fa972016-02-15 11:57:00 -07001051 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -06001052 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -07001053 case glslang::ElfRg32f:
1054 case glslang::ElfRg16f:
1055 case glslang::ElfR11fG11fB10f:
1056 case glslang::ElfR16f:
1057 case glslang::ElfRgba16:
1058 case glslang::ElfRgb10A2:
1059 case glslang::ElfRg16:
1060 case glslang::ElfRg8:
1061 case glslang::ElfR16:
1062 case glslang::ElfR8:
1063 case glslang::ElfRgba16Snorm:
1064 case glslang::ElfRg16Snorm:
1065 case glslang::ElfRg8Snorm:
1066 case glslang::ElfR16Snorm:
1067 case glslang::ElfR8Snorm:
1068
1069 case glslang::ElfRg32i:
1070 case glslang::ElfRg16i:
1071 case glslang::ElfRg8i:
1072 case glslang::ElfR16i:
1073 case glslang::ElfR8i:
1074
1075 case glslang::ElfRgb10a2ui:
1076 case glslang::ElfRg32ui:
1077 case glslang::ElfRg16ui:
1078 case glslang::ElfRg8ui:
1079 case glslang::ElfR16ui:
1080 case glslang::ElfR8ui:
1081 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1082 break;
1083
1084 default:
1085 break;
1086 }
1087
1088 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001089 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001090 case glslang::ElfNone: return spv::ImageFormatUnknown;
1091 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1092 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1093 case glslang::ElfR32f: return spv::ImageFormatR32f;
1094 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1095 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1096 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1097 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1098 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1099 case glslang::ElfR16f: return spv::ImageFormatR16f;
1100 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1101 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1102 case glslang::ElfRg16: return spv::ImageFormatRg16;
1103 case glslang::ElfRg8: return spv::ImageFormatRg8;
1104 case glslang::ElfR16: return spv::ImageFormatR16;
1105 case glslang::ElfR8: return spv::ImageFormatR8;
1106 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1107 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1108 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1109 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1110 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1111 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1112 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1113 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1114 case glslang::ElfR32i: return spv::ImageFormatR32i;
1115 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1116 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1117 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1118 case glslang::ElfR16i: return spv::ImageFormatR16i;
1119 case glslang::ElfR8i: return spv::ImageFormatR8i;
1120 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1121 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1122 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1123 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1124 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1125 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1126 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1127 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1128 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1129 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001130 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001131 }
1132}
1133
John Kessenich8985fc92020-03-03 10:25:07 -07001134spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(
1135 const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001136{
John Kesseniche18fd202018-01-30 11:01:39 -07001137 if (selectionNode.getFlatten())
1138 return spv::SelectionControlFlattenMask;
1139 if (selectionNode.getDontFlatten())
1140 return spv::SelectionControlDontFlattenMask;
1141 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001142}
1143
John Kessenich8985fc92020-03-03 10:25:07 -07001144spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode)
1145 const
steve-lunargf1709e72017-05-02 20:14:50 -06001146{
John Kesseniche18fd202018-01-30 11:01:39 -07001147 if (switchNode.getFlatten())
1148 return spv::SelectionControlFlattenMask;
1149 if (switchNode.getDontFlatten())
1150 return spv::SelectionControlDontFlattenMask;
1151 return spv::SelectionControlMaskNone;
1152}
1153
John Kessenicha2858d92018-01-31 08:11:18 -07001154// return a non-0 dependency if the dependency argument must be set
1155spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001156 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001157{
1158 spv::LoopControlMask control = spv::LoopControlMaskNone;
1159
1160 if (loopNode.getDontUnroll())
1161 control = control | spv::LoopControlDontUnrollMask;
1162 if (loopNode.getUnroll())
1163 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001164 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001165 control = control | spv::LoopControlDependencyInfiniteMask;
1166 else if (loopNode.getLoopDependency() > 0) {
1167 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001168 operands.push_back((unsigned int)loopNode.getLoopDependency());
1169 }
1170 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1171 if (loopNode.getMinIterations() > 0) {
1172 control = control | spv::LoopControlMinIterationsMask;
1173 operands.push_back(loopNode.getMinIterations());
1174 }
1175 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1176 control = control | spv::LoopControlMaxIterationsMask;
1177 operands.push_back(loopNode.getMaxIterations());
1178 }
1179 if (loopNode.getIterationMultiple() > 1) {
1180 control = control | spv::LoopControlIterationMultipleMask;
1181 operands.push_back(loopNode.getIterationMultiple());
1182 }
1183 if (loopNode.getPeelCount() > 0) {
1184 control = control | spv::LoopControlPeelCountMask;
1185 operands.push_back(loopNode.getPeelCount());
1186 }
1187 if (loopNode.getPartialCount() > 0) {
1188 control = control | spv::LoopControlPartialCountMask;
1189 operands.push_back(loopNode.getPartialCount());
1190 }
John Kessenicha2858d92018-01-31 08:11:18 -07001191 }
John Kesseniche18fd202018-01-30 11:01:39 -07001192
1193 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001194}
1195
John Kessenicha5c5fb62017-05-05 05:09:58 -06001196// Translate glslang type to SPIR-V storage class.
1197spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1198{
Torosdagli06c2eee2020-03-19 11:09:57 -04001199 if (type.getBasicType() == glslang::EbtRayQuery)
Neslisah Torosdagli054b5e32020-03-26 12:24:31 -04001200 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001201 if (type.getQualifier().isPipeInput())
1202 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001203 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001204 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001205
1206 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001207 type.getQualifier().storage == glslang::EvqUniform) {
John Kessenichdeec1932019-08-13 08:00:30 -06001208 if (type.isAtomic())
John Kessenichbed4e4f2017-09-08 02:38:07 -06001209 return spv::StorageClassAtomicCounter;
1210 if (type.containsOpaque())
1211 return spv::StorageClassUniformConstant;
1212 }
1213
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001214 if (type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001215 type.getQualifier().isShaderRecord()) {
1216 return spv::StorageClassShaderRecordBufferKHR;
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001217 }
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001218
John Kessenichbed4e4f2017-09-08 02:38:07 -06001219 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001220 builder.addIncorporatedExtension(spv::E_SPV_KHR_storage_buffer_storage_class, spv::Spv_1_3);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001221 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001222 }
1223
1224 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich7015bd62019-08-01 03:28:08 -06001225 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001226 return spv::StorageClassPushConstant;
1227 if (type.getBasicType() == glslang::EbtBlock)
1228 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001229 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001230 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001231
1232 switch (type.getQualifier().storage) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001233 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1234 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1235 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenichdeec1932019-08-13 08:00:30 -06001236 case glslang::EvqShared: return spv::StorageClassWorkgroup;
John Kessenich3dd1ce52019-10-17 07:08:40 -06001237#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -04001238 case glslang::EvqPayload: return spv::StorageClassRayPayloadKHR;
1239 case glslang::EvqPayloadIn: return spv::StorageClassIncomingRayPayloadKHR;
1240 case glslang::EvqHitAttr: return spv::StorageClassHitAttributeKHR;
1241 case glslang::EvqCallableData: return spv::StorageClassCallableDataKHR;
1242 case glslang::EvqCallableDataIn: return spv::StorageClassIncomingCallableDataKHR;
Chao Chenb50c02e2018-09-19 11:42:24 -07001243#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001244 default:
1245 assert(0);
1246 break;
1247 }
1248
1249 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001250}
1251
John Kessenich5611c6d2018-04-05 11:25:02 -06001252// Add capabilities pertaining to how an array is indexed.
1253void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1254 const glslang::TType& indexType)
1255{
John Kessenichb9197c82019-08-11 07:41:45 -06001256#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06001257 if (indexType.getQualifier().isNonUniform()) {
1258 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001259 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001260 if (baseType.getBasicType() == glslang::EbtSampler) {
1261 if (baseType.getQualifier().hasAttachment())
1262 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001263 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001264 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001265 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001266 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1267 else if (baseType.isImage())
1268 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1269 else if (baseType.isTexture())
1270 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1271 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1272 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1273 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1274 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1275 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1276 }
1277 } else {
1278 // assume a dynamically uniform index
1279 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001280 if (baseType.getQualifier().hasAttachment()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001281 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001282 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001283 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001284 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001285 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001286 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001287 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001288 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001289 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001290 }
1291 }
John Kessenichb9197c82019-08-11 07:41:45 -06001292#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06001293}
1294
qining25262b32016-05-06 17:25:16 -04001295// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001296// descriptor set.
1297bool IsDescriptorResource(const glslang::TType& type)
1298{
John Kessenichf7497e22016-03-08 21:36:22 -07001299 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001300 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001301 return type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001302 ! type.getQualifier().isShaderRecord() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001303 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001304
1305 // non block...
1306 // basically samplerXXX/subpass/sampler/texture are all included
1307 // if they are the global-scope-class, not the function parameter
1308 // (or local, if they ever exist) class.
alelenv999d4fd2020-06-01 23:24:41 -07001309 if (type.getBasicType() == glslang::EbtSampler ||
1310 type.getBasicType() == glslang::EbtAccStruct)
John Kessenich6c292d32016-02-15 20:58:50 -07001311 return type.getQualifier().isUniformOrBuffer();
1312
1313 // None of the above.
1314 return false;
1315}
1316
John Kesseniche0b6cad2015-12-24 10:30:13 -07001317void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1318{
1319 if (child.layoutMatrix == glslang::ElmNone)
1320 child.layoutMatrix = parent.layoutMatrix;
1321
1322 if (parent.invariant)
1323 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001324 if (parent.flat)
1325 child.flat = true;
1326 if (parent.centroid)
1327 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001328#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001329 if (parent.nopersp)
1330 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001331 if (parent.explicitInterp)
1332 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001333 if (parent.perPrimitiveNV)
1334 child.perPrimitiveNV = true;
1335 if (parent.perViewNV)
1336 child.perViewNV = true;
1337 if (parent.perTaskNV)
1338 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001339 if (parent.patch)
1340 child.patch = true;
1341 if (parent.sample)
1342 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001343 if (parent.coherent)
1344 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001345 if (parent.devicecoherent)
1346 child.devicecoherent = true;
1347 if (parent.queuefamilycoherent)
1348 child.queuefamilycoherent = true;
1349 if (parent.workgroupcoherent)
1350 child.workgroupcoherent = true;
1351 if (parent.subgroupcoherent)
1352 child.subgroupcoherent = true;
Daniel Kochdb32b242020-03-17 20:42:47 -04001353 if (parent.shadercallcoherent)
1354 child.shadercallcoherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001355 if (parent.nonprivate)
1356 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001357 if (parent.volatil)
1358 child.volatil = true;
1359 if (parent.restrict)
1360 child.restrict = true;
1361 if (parent.readonly)
1362 child.readonly = true;
1363 if (parent.writeonly)
1364 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001365#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001366}
1367
John Kessenichf2b7f332016-09-01 17:05:23 -06001368bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001369{
John Kessenich7b9fa252016-01-21 18:56:57 -07001370 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001371 // - struct members might inherit from a struct declaration
1372 // (note that non-block structs don't explicitly inherit,
1373 // only implicitly, meaning no decoration involved)
1374 // - affect decorations on the struct members
1375 // (note smooth does not, and expecting something like volatile
1376 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001377 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001378 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001379}
1380
John Kessenich140f3df2015-06-26 16:58:36 -06001381//
1382// Implement the TGlslangToSpvTraverser class.
1383//
1384
John Kessenich8985fc92020-03-03 10:25:07 -07001385TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion,
1386 const glslang::TIntermediate* glslangIntermediate,
1387 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options) :
1388 TIntermTraverser(true, false, true),
1389 options(options),
1390 shaderEntry(nullptr), currentFunction(nullptr),
1391 sequenceDepth(0), logger(buildLogger),
1392 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
1393 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
1394 glslangIntermediate(glslangIntermediate),
Jeff Bolz04d73732019-05-31 13:06:01 -05001395 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp()),
1396 nonSemanticDebugPrintf(0)
John Kessenich140f3df2015-06-26 16:58:36 -06001397{
1398 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1399
1400 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001401 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1402 glslangIntermediate->getVersion());
1403
John Kessenich121853f2017-05-31 17:11:16 -06001404 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001405 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001406 builder.setSourceFile(glslangIntermediate->getSourceFile());
1407
1408 // Set the source shader's text. If for SPV version 1.0, include
1409 // a preamble in comments stating the OpModuleProcessed instructions.
1410 // Otherwise, emit those as actual instructions.
1411 std::string text;
1412 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1413 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001414 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001415 text.append("// OpModuleProcessed ");
1416 text.append(processes[p]);
1417 text.append("\n");
1418 } else
1419 builder.addModuleProcessed(processes[p]);
1420 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001421 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001422 text.append("#line 1\n");
1423 text.append(glslangIntermediate->getSourceText());
1424 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001425 // Pass name and text for all included files
1426 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1427 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1428 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001429 }
John Kessenich140f3df2015-06-26 16:58:36 -06001430 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001431
1432 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1433 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1434
1435 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1436 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
John Kessenich1ff0c182019-10-10 12:01:13 -06001437 builder.addIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001438 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
John Kessenich8985fc92020-03-03 10:25:07 -07001439 }
Jeff Bolz36831c92018-09-05 10:11:41 -05001440 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001441 memoryModel = spv::MemoryModelVulkanKHR;
1442 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001443 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001444 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001445 builder.setMemoryModel(addressingModel, memoryModel);
1446
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001447 if (glslangIntermediate->usingVariablePointers()) {
1448 builder.addCapability(spv::CapabilityVariablePointers);
1449 }
1450
John Kessenicheee9d532016-09-19 18:09:30 -06001451 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1452 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001453
1454 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001455 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1456 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
johnkslang01384722020-08-14 08:40:06 -06001457 builder.addSourceExtension(it->c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001458
1459 // Add the top-level modes for this shader.
1460
John Kessenich92187592016-02-01 13:45:25 -07001461 if (glslangIntermediate->getXfbMode()) {
1462 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001463 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001464 }
John Kessenich140f3df2015-06-26 16:58:36 -06001465
alelenv59216d52020-05-21 04:38:41 -07001466 if (glslangIntermediate->getLayoutPrimitiveCulling()) {
alelenv75de1962020-04-08 21:09:20 -07001467 builder.addCapability(spv::CapabilityRayTraversalPrimitiveCullingProvisionalKHR);
1468 }
1469
John Kessenich140f3df2015-06-26 16:58:36 -06001470 unsigned int mode;
1471 switch (glslangIntermediate->getStage()) {
1472 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001473 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001474 break;
1475
John Kessenicha28f7a72019-08-06 07:00:58 -06001476 case EShLangFragment:
1477 builder.addCapability(spv::CapabilityShader);
1478 if (glslangIntermediate->getPixelCenterInteger())
1479 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1480
1481 if (glslangIntermediate->getOriginUpperLeft())
1482 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1483 else
1484 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1485
1486 if (glslangIntermediate->getEarlyFragmentTests())
1487 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1488
1489 if (glslangIntermediate->getPostDepthCoverage()) {
1490 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1491 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1492 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1493 }
1494
John Kessenichb9197c82019-08-11 07:41:45 -06001495 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1496 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1497
1498#ifndef GLSLANG_WEB
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001499
John Kessenicha28f7a72019-08-06 07:00:58 -06001500 switch(glslangIntermediate->getDepth()) {
1501 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1502 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1503 default: mode = spv::ExecutionModeMax; break;
1504 }
1505 if (mode != spv::ExecutionModeMax)
1506 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001507 switch (glslangIntermediate->getInterlockOrdering()) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001508 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT;
1509 break;
1510 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT;
1511 break;
1512 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT;
1513 break;
1514 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT;
1515 break;
1516 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT;
1517 break;
1518 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT;
1519 break;
1520 default: mode = spv::ExecutionModeMax;
1521 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001522 }
1523 if (mode != spv::ExecutionModeMax) {
1524 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1525 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1526 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1527 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1528 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1529 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1530 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1531 } else {
1532 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1533 }
1534 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1535 }
John Kessenichb9197c82019-08-11 07:41:45 -06001536#endif
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001537 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001538
John Kessenicha28f7a72019-08-06 07:00:58 -06001539 case EShLangCompute:
1540 builder.addCapability(spv::CapabilityShader);
1541 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1542 glslangIntermediate->getLocalSize(1),
1543 glslangIntermediate->getLocalSize(2));
1544 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1545 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1546 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1547 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1548 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1549 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1550 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1551 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1552 }
1553 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001554#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001555 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001556 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001557 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001558
steve-lunarge7412492017-03-23 11:56:07 -06001559 glslang::TLayoutGeometry primitive;
1560
1561 if (glslangIntermediate->getStage() == EShLangTessControl) {
John Kessenich8985fc92020-03-03 10:25:07 -07001562 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1563 glslangIntermediate->getVertices());
steve-lunarge7412492017-03-23 11:56:07 -06001564 primitive = glslangIntermediate->getOutputPrimitive();
1565 } else {
1566 primitive = glslangIntermediate->getInputPrimitive();
1567 }
1568
1569 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001570 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1571 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1572 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001573 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001574 }
John Kessenich4016e382016-07-15 11:53:56 -06001575 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001576 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1577
John Kesseniche6903322015-10-13 16:29:02 -06001578 switch (glslangIntermediate->getVertexSpacing()) {
1579 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1580 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1581 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001582 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001583 }
John Kessenich4016e382016-07-15 11:53:56 -06001584 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001585 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1586
1587 switch (glslangIntermediate->getVertexOrder()) {
1588 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1589 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001590 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001591 }
John Kessenich4016e382016-07-15 11:53:56 -06001592 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001593 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1594
1595 if (glslangIntermediate->getPointMode())
1596 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001597 break;
1598
1599 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001600 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001601 switch (glslangIntermediate->getInputPrimitive()) {
1602 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1603 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1604 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001605 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001606 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001607 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001608 }
John Kessenich4016e382016-07-15 11:53:56 -06001609 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001610 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001611
John Kessenich140f3df2015-06-26 16:58:36 -06001612 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1613
1614 switch (glslangIntermediate->getOutputPrimitive()) {
1615 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1616 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1617 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001618 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001619 }
John Kessenich4016e382016-07-15 11:53:56 -06001620 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001621 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1622 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1623 break;
1624
Daniel Kochdb32b242020-03-17 20:42:47 -04001625 case EShLangRayGen:
1626 case EShLangIntersect:
1627 case EShLangAnyHit:
1628 case EShLangClosestHit:
1629 case EShLangMiss:
1630 case EShLangCallable:
1631 {
1632 auto& extensions = glslangIntermediate->getRequestedExtensions();
1633 if (extensions.find("GL_NV_ray_tracing") == extensions.end()) {
1634 builder.addCapability(spv::CapabilityRayTracingProvisionalKHR);
1635 builder.addExtension("SPV_KHR_ray_tracing");
1636 }
1637 else {
1638 builder.addCapability(spv::CapabilityRayTracingNV);
1639 builder.addExtension("SPV_NV_ray_tracing");
1640 }
Chao Chenb50c02e2018-09-19 11:42:24 -07001641 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04001642 }
Chao Chen3c366992018-09-19 11:41:59 -07001643 case EShLangTaskNV:
1644 case EShLangMeshNV:
1645 builder.addCapability(spv::CapabilityMeshShadingNV);
1646 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1647 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1648 glslangIntermediate->getLocalSize(1),
1649 glslangIntermediate->getLocalSize(2));
1650 if (glslangIntermediate->getStage() == EShLangMeshNV) {
John Kessenich8985fc92020-03-03 10:25:07 -07001651 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1652 glslangIntermediate->getVertices());
1653 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV,
1654 glslangIntermediate->getPrimitives());
Chao Chen3c366992018-09-19 11:41:59 -07001655
1656 switch (glslangIntermediate->getOutputPrimitive()) {
1657 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1658 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1659 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1660 default: mode = spv::ExecutionModeMax; break;
1661 }
1662 if (mode != spv::ExecutionModeMax)
1663 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1664 }
1665 break;
1666#endif
1667
John Kessenich140f3df2015-06-26 16:58:36 -06001668 default:
1669 break;
1670 }
John Kessenich140f3df2015-06-26 16:58:36 -06001671}
1672
John Kessenichfca82622016-11-26 13:23:20 -07001673// Finish creating SPV, after the traversal is complete.
1674void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001675{
John Kessenichf04c51b2018-08-03 15:56:12 -06001676 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001677 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001678 builder.setBuildPoint(shaderEntry->getLastBlock());
1679 builder.leaveFunction();
1680 }
1681
John Kessenich7ba63412015-12-20 17:37:07 -07001682 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001683 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1684 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001685
David Neto8c3d5b42019-10-21 14:50:31 -04001686 // Add capabilities, extensions, remove unneeded decorations, etc.,
John Kessenichf04c51b2018-08-03 15:56:12 -06001687 // based on the resulting SPIR-V.
David Neto8c3d5b42019-10-21 14:50:31 -04001688 // Note: WebGPU code generation must have the opportunity to aggressively
1689 // prune unreachable merge blocks and continue targets.
John Kessenichf04c51b2018-08-03 15:56:12 -06001690 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001691}
1692
John Kessenichfca82622016-11-26 13:23:20 -07001693// Write the SPV into 'out'.
1694void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001695{
John Kessenichfca82622016-11-26 13:23:20 -07001696 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001697}
1698
1699//
1700// Implement the traversal functions.
1701//
1702// Return true from interior nodes to have the external traversal
1703// continue on to children. Return false if children were
1704// already processed.
1705//
1706
1707//
qining25262b32016-05-06 17:25:16 -04001708// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001709// - uniform/input reads
1710// - output writes
1711// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1712// - something simple that degenerates into the last bullet
1713//
1714void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1715{
qining75d1d802016-04-06 14:42:01 -04001716 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
Roy05a5b532020-01-03 16:21:34 +08001717 if (symbol->getType().isStruct())
1718 glslangTypeToIdMap[symbol->getType().getStruct()] = symbol->getId();
1719
qining75d1d802016-04-06 14:42:01 -04001720 if (symbol->getType().getQualifier().isSpecConstant())
1721 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1722
Rex Xuf6e0fe82020-10-23 22:54:35 +08001723#ifdef ENABLE_HLSL
1724 // Skip symbol handling if it is string-typed
1725 if (symbol->getBasicType() == glslang::EbtString)
1726 return;
1727#endif
1728
John Kessenich140f3df2015-06-26 16:58:36 -06001729 // getSymbolId() will set up all the IO decorations on the first call.
1730 // Formal function parameters were mapped during makeFunctions().
1731 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001732
John Kessenich7ba63412015-12-20 17:37:07 -07001733 if (builder.isPointer(id)) {
John Kessenichc30d3352020-06-10 07:15:24 -06001734 if (!symbol->getType().getQualifier().isParamInput() &&
1735 !symbol->getType().getQualifier().isParamOutput()) {
1736 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1737 // Consider adding to the OpEntryPoint interface list.
1738 // Only looking at structures if they have at least one member.
1739 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1740 spv::StorageClass sc = builder.getStorageClass(id);
1741 // Before SPIR-V 1.4, we only want to include Input and Output.
1742 // Starting with SPIR-V 1.4, we want all globals.
John Kessenich4e13c902020-07-13 00:35:58 -06001743 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && builder.isGlobalStorage(id)) ||
John Kessenichc30d3352020-06-10 07:15:24 -06001744 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
1745 iOSet.insert(id);
1746 }
John Kessenich7c7731e2019-01-04 16:47:06 +07001747 }
John Kessenich5f77d862017-09-19 11:09:59 -06001748 }
John Kessenich9c14f772019-06-17 08:38:35 -06001749
Daniel Kochdb32b242020-03-17 20:42:47 -04001750 // If the SPIR-V type is required to be different than the AST type
1751 // (for ex SubgroupMasks or 3x4 ObjectToWorld/WorldToObject matrices),
John Kessenich9c14f772019-06-17 08:38:35 -06001752 // translate now from the SPIR-V type to the AST type, for the consuming
1753 // operation.
1754 // Note this turns it from an l-value to an r-value.
1755 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1756 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1757 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001758 }
1759
1760 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001761 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001762 // Prepare to generate code for the access
1763
1764 // L-value chains will be computed left to right. We're on the symbol now,
1765 // which is the left-most part of the access chain, so now is "clear" time,
1766 // followed by setting the base.
1767 builder.clearAccessChain();
1768
1769 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001770 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001771 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001772 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001773 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001774 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001775 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001776 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001777 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1778 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001779 builder.setAccessChainRValue(id);
1780 else
1781 builder.setAccessChainLValue(id);
1782 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001783
John Kessenichb9197c82019-08-11 07:41:45 -06001784#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001785 // Process linkage-only nodes for any special additional interface work.
1786 if (linkageOnly) {
1787 if (glslangIntermediate->getHlslFunctionality1()) {
1788 // Map implicit counter buffers to their originating buffers, which should have been
1789 // seen by now, given earlier pruning of unused counters, and preservation of order
1790 // of declaration.
1791 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1792 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1793 // Save possible originating buffers for counter buffers, keyed by
1794 // making the potential counter-buffer name.
1795 std::string keyName = symbol->getName().c_str();
1796 keyName = glslangIntermediate->addCounterBufferName(keyName);
1797 counterOriginator[keyName] = symbol;
1798 } else {
1799 // Handle a counter buffer, by finding the saved originating buffer.
1800 std::string keyName = symbol->getName().c_str();
1801 auto it = counterOriginator.find(keyName);
1802 if (it != counterOriginator.end()) {
1803 id = getSymbolId(it->second);
1804 if (id != spv::NoResult) {
1805 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001806 if (counterId != spv::NoResult) {
1807 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001808 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001809 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001810 }
1811 }
1812 }
1813 }
1814 }
1815 }
John Kessenich155d3512019-08-08 23:29:20 -06001816#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001817}
1818
1819bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1820{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001821 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Roy05a5b532020-01-03 16:21:34 +08001822 if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
1823 glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
1824 }
1825 if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
1826 glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
1827 }
John Kesseniche485c7a2017-05-31 18:50:53 -06001828
qining40887662016-04-03 22:20:42 -04001829 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1830 if (node->getType().getQualifier().isSpecConstant())
1831 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1832
John Kessenich140f3df2015-06-26 16:58:36 -06001833 // First, handle special cases
1834 switch (node->getOp()) {
1835 case glslang::EOpAssign:
1836 case glslang::EOpAddAssign:
1837 case glslang::EOpSubAssign:
1838 case glslang::EOpMulAssign:
1839 case glslang::EOpVectorTimesMatrixAssign:
1840 case glslang::EOpVectorTimesScalarAssign:
1841 case glslang::EOpMatrixTimesScalarAssign:
1842 case glslang::EOpMatrixTimesMatrixAssign:
1843 case glslang::EOpDivAssign:
1844 case glslang::EOpModAssign:
1845 case glslang::EOpAndAssign:
1846 case glslang::EOpInclusiveOrAssign:
1847 case glslang::EOpExclusiveOrAssign:
1848 case glslang::EOpLeftShiftAssign:
1849 case glslang::EOpRightShiftAssign:
1850 // A bin-op assign "a += b" means the same thing as "a = a + b"
1851 // where a is evaluated before b. For a simple assignment, GLSL
1852 // says to evaluate the left before the right. So, always, left
1853 // node then right node.
1854 {
1855 // get the left l-value, save it away
1856 builder.clearAccessChain();
1857 node->getLeft()->traverse(this);
1858 spv::Builder::AccessChain lValue = builder.getAccessChain();
1859
1860 // evaluate the right
1861 builder.clearAccessChain();
1862 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001863 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001864
1865 if (node->getOp() != glslang::EOpAssign) {
1866 // the left is also an r-value
1867 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001868 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001869
1870 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001871 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001872 TranslateNoContractionDecoration(node->getType().getQualifier()),
1873 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001874 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001875 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1876 node->getType().getBasicType());
1877
1878 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001879 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001880 }
1881
1882 // store the result
1883 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001884 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001885
1886 // assignments are expressions having an rValue after they are evaluated...
1887 builder.clearAccessChain();
1888 builder.setAccessChainRValue(rValue);
1889 }
1890 return false;
1891 case glslang::EOpIndexDirect:
1892 case glslang::EOpIndexDirectStruct:
1893 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001894 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001895 // Get the left part of the access chain.
1896 node->getLeft()->traverse(this);
1897
1898 // Add the next element in the chain
1899
David Netoa901ffe2016-06-08 14:11:40 +01001900 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001901 if (! node->getLeft()->getType().isArray() &&
1902 node->getLeft()->getType().isVector() &&
1903 node->getOp() == glslang::EOpIndexDirect) {
1904 // This is essentially a hard-coded vector swizzle of size 1,
1905 // so short circuit the access-chain stuff with a swizzle.
1906 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001907 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001908 int dummySize;
1909 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1910 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001911 glslangIntermediate->getBaseAlignmentScalar(
1912 node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001913 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001914
1915 // Load through a block reference is performed with a dot operator that
1916 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1917 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001918 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001919 !node->getLeft()->getType().isArray() &&
1920 node->getOp() == glslang::EOpIndexDirectStruct)
1921 {
1922 spv::Id left = accessChainLoad(node->getLeft()->getType());
1923 builder.clearAccessChain();
1924 builder.setAccessChainLValue(left);
1925 }
1926
David Netoa901ffe2016-06-08 14:11:40 +01001927 int spvIndex = glslangIndex;
1928 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1929 node->getOp() == glslang::EOpIndexDirectStruct)
1930 {
1931 // This may be, e.g., an anonymous block-member selection, which generally need
1932 // index remapping due to hidden members in anonymous blocks.
Roy05a5b532020-01-03 16:21:34 +08001933 int glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
1934 if (memberRemapper.find(glslangId) != memberRemapper.end()) {
1935 std::vector<int>& remapper = memberRemapper[glslangId];
1936 assert(remapper.size() > 0);
1937 spvIndex = remapper[glslangIndex];
1938 }
David Netoa901ffe2016-06-08 14:11:40 +01001939 }
John Kessenichebb50532016-05-16 19:22:05 -06001940
David Netoa901ffe2016-06-08 14:11:40 +01001941 // normal case for indexing array or structure or block
John Kessenich8985fc92020-03-03 10:25:07 -07001942 builder.accessChainPush(builder.makeIntConstant(spvIndex),
1943 TranslateCoherent(node->getLeft()->getType()),
1944 node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001945
1946 // Add capabilities here for accessing PointSize and clip/cull distance.
1947 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001948 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001949 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001950 }
1951 }
1952 return false;
1953 case glslang::EOpIndexIndirect:
1954 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001955 // Array, matrix, or vector indirection with variable index.
1956 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001957 // matrices are arrays of vectors, so will also work for a matrix.
1958 // Will use the access chain's 'component' for variable index into a vector.
1959
1960 // This adapter is building access chains left to right.
1961 // Set up the access chain to the left.
1962 node->getLeft()->traverse(this);
1963
1964 // save it so that computing the right side doesn't trash it
1965 spv::Builder::AccessChain partial = builder.getAccessChain();
1966
1967 // compute the next index in the chain
1968 builder.clearAccessChain();
1969 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001970 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001971
John Kessenich5611c6d2018-04-05 11:25:02 -06001972 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1973
John Kessenich140f3df2015-06-26 16:58:36 -06001974 // restore the saved access chain
1975 builder.setAccessChain(partial);
1976
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001977 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1978 int dummySize;
1979 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1980 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001981 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1982 dummySize));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001983 } else
John Kessenich8985fc92020-03-03 10:25:07 -07001984 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()),
1985 node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001986 }
1987 return false;
1988 case glslang::EOpVectorSwizzle:
1989 {
1990 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001991 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001992 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001993 int dummySize;
1994 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1995 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001996 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1997 dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001998 }
1999 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07002000 case glslang::EOpMatrixSwizzle:
2001 logger->missingFunctionality("matrix swizzle");
2002 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06002003 case glslang::EOpLogicalOr:
2004 case glslang::EOpLogicalAnd:
2005 {
2006
2007 // These may require short circuiting, but can sometimes be done as straight
2008 // binary operations. The right operand must be short circuited if it has
2009 // side effects, and should probably be if it is complex.
2010 if (isTrivial(node->getRight()->getAsTyped()))
2011 break; // handle below as a normal binary operation
2012 // otherwise, we need to do dynamic short circuiting on the right operand
John Kessenich8985fc92020-03-03 10:25:07 -07002013 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(),
2014 *node->getRight()->getAsTyped());
John Kessenich7c1aa102015-10-15 13:29:11 -06002015 builder.clearAccessChain();
2016 builder.setAccessChainRValue(result);
2017 }
2018 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06002019 default:
2020 break;
2021 }
2022
2023 // Assume generic binary op...
2024
John Kessenich32cfd492016-02-02 12:37:46 -07002025 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06002026 builder.clearAccessChain();
2027 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002028 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002029
John Kessenich32cfd492016-02-02 12:37:46 -07002030 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06002031 builder.clearAccessChain();
2032 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002033 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002034
John Kessenich32cfd492016-02-02 12:37:46 -07002035 // get result
John Kessenichead86222018-03-28 18:01:20 -06002036 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002037 TranslateNoContractionDecoration(node->getType().getQualifier()),
2038 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002039 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07002040 convertGlslangToSpvType(node->getType()), left, right,
2041 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002042
John Kessenich50e57562015-12-21 21:21:11 -07002043 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06002044 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002045 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07002046 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06002047 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06002048 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06002049 return false;
2050 }
John Kessenich140f3df2015-06-26 16:58:36 -06002051}
2052
John Kessenich9c14f772019-06-17 08:38:35 -06002053// Figure out what, if any, type changes are needed when accessing a specific built-in.
2054// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
2055// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
Daniel Kochdb32b242020-03-17 20:42:47 -04002056std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(glslang::TBuiltInVariable glslangBuiltIn,
John Kessenich9c14f772019-06-17 08:38:35 -06002057 const glslang::TType& glslangType)
2058{
Daniel Kochdb32b242020-03-17 20:42:47 -04002059 switch(glslangBuiltIn)
John Kessenich9c14f772019-06-17 08:38:35 -06002060 {
Daniel Kochdb32b242020-03-17 20:42:47 -04002061 case glslang::EbvSubGroupEqMask:
2062 case glslang::EbvSubGroupGeMask:
2063 case glslang::EbvSubGroupGtMask:
2064 case glslang::EbvSubGroupLeMask:
2065 case glslang::EbvSubGroupLtMask: {
John Kessenich9c14f772019-06-17 08:38:35 -06002066 // these require changing a 64-bit scaler -> a vector of 32-bit components
2067 if (glslangType.isVector())
2068 break;
2069 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
2070 builder.makeUintType(64));
2071 return ret;
2072 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002073 // There are no SPIR-V builtins defined for these and map onto original non-transposed
2074 // builtins. During visitBinary we insert a transpose
2075 case glslang::EbvWorldToObject3x4:
2076 case glslang::EbvObjectToWorld3x4: {
John Kessenichf80ef742020-07-14 01:44:35 -06002077 spv::Id mat43 = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
2078 spv::Id mat34 = builder.makeMatrixType(builder.makeFloatType(32), 3, 4);
2079 std::pair<spv::Id, spv::Id> ret(mat43, mat34);
Daniel Kochdb32b242020-03-17 20:42:47 -04002080 return ret;
2081 }
John Kessenich9c14f772019-06-17 08:38:35 -06002082 default:
2083 break;
2084 }
2085
2086 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2087 return ret;
2088}
2089
2090// For an object previously identified (see getForcedType() and forceType)
2091// as needing type translations, do the translation needed for a load, turning
2092// an L-value into in R-value.
2093spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2094{
2095 const auto forceIt = forceType.find(object);
2096 if (forceIt == forceType.end())
2097 return object;
2098
2099 spv::Id desiredTypeId = forceIt->second;
2100 spv::Id objectTypeId = builder.getTypeId(object);
2101 assert(builder.isPointerType(objectTypeId));
2102 objectTypeId = builder.getContainedTypeId(objectTypeId);
2103 if (builder.isVectorType(objectTypeId) &&
2104 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2105 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2106 // handle 32-bit v.xy* -> 64-bit
2107 builder.clearAccessChain();
2108 builder.setAccessChainLValue(object);
2109 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2110 std::vector<spv::Id> components;
2111 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2112 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2113
2114 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2115 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2116 builder.createCompositeConstruct(vecType, components));
2117 } else {
2118 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2119 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002120 } else if (builder.isMatrixType(objectTypeId)) {
2121 // There are no SPIR-V builtins defined for 3x4 variants of ObjectToWorld/WorldToObject
2122 // and we insert a transpose after loading the original non-transposed builtins
2123 builder.clearAccessChain();
2124 builder.setAccessChainLValue(object);
2125 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2126 return builder.createUnaryOp(spv::OpTranspose, desiredTypeId, object);
2127
2128 } else {
John Kessenich9c14f772019-06-17 08:38:35 -06002129 logger->missingFunctionality("forcing non 32-bit vector type");
2130 }
2131
2132 return object;
2133}
2134
John Kessenich140f3df2015-06-26 16:58:36 -06002135bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2136{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002137 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002138
qining40887662016-04-03 22:20:42 -04002139 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2140 if (node->getType().getQualifier().isSpecConstant())
2141 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2142
John Kessenichfc51d282015-08-19 13:34:18 -06002143 spv::Id result = spv::NoResult;
2144
2145 // try texturing first
2146 result = createImageTextureFunctionCall(node);
2147 if (result != spv::NoResult) {
2148 builder.clearAccessChain();
2149 builder.setAccessChainRValue(result);
2150
2151 return false; // done with this node
2152 }
2153
2154 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002155
2156 if (node->getOp() == glslang::EOpArrayLength) {
2157 // Quite special; won't want to evaluate the operand.
2158
John Kessenich5611c6d2018-04-05 11:25:02 -06002159 // Currently, the front-end does not allow .length() on an array until it is sized,
2160 // except for the last block membeor of an SSBO.
2161 // TODO: If this changes, link-time sized arrays might show up here, and need their
2162 // size extracted.
2163
John Kessenichc9a80832015-09-12 12:17:44 -06002164 // Normal .length() would have been constant folded by the front-end.
2165 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002166 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002167
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002168 spv::Id length;
2169 if (node->getOperand()->getType().isCoopMat()) {
2170 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2171
2172 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2173 assert(builder.isCooperativeMatrixType(typeId));
2174
2175 length = builder.createCooperativeMatrixLength(typeId);
2176 } else {
2177 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2178 block->traverse(this);
John Kessenich8985fc92020-03-03 10:25:07 -07002179 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()
2180 ->getConstArray()[0].getUConst();
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002181 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2182 }
John Kessenichc9a80832015-09-12 12:17:44 -06002183
John Kessenich8c869672018-11-28 07:01:37 -07002184 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2185 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2186 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002187 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2188 if (builder.isInSpecConstCodeGenMode()) {
2189 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2190 } else {
2191 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2192 }
2193 }
John Kessenich8c869672018-11-28 07:01:37 -07002194
John Kessenichc9a80832015-09-12 12:17:44 -06002195 builder.clearAccessChain();
2196 builder.setAccessChainRValue(length);
2197
2198 return false;
2199 }
2200
John Kessenichfc51d282015-08-19 13:34:18 -06002201 // Start by evaluating the operand
2202
John Kessenich8c8505c2016-07-26 12:50:38 -06002203 // Does it need a swizzle inversion? If so, evaluation is inverted;
2204 // operate first on the swizzle base, then apply the swizzle.
2205 spv::Id invertedType = spv::NoType;
John Kessenich8985fc92020-03-03 10:25:07 -07002206 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2207 invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenich8c8505c2016-07-26 12:50:38 -06002208 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2209 invertedType = getInvertedSwizzleType(*node->getOperand());
2210
John Kessenich140f3df2015-06-26 16:58:36 -06002211 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002212 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002213 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002214 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002215 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002216 operandNode = node->getOperand();
2217
2218 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002219
Rex Xufc618912015-09-09 16:42:49 +08002220 spv::Id operand = spv::NoResult;
2221
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002222 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2223
John Kessenichfb4f2332019-08-09 03:49:15 -06002224#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002225 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2226 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002227 node->getOp() == glslang::EOpAtomicCounter ||
Neslisah Torosdagli7d37a682020-03-26 10:52:33 -04002228 node->getOp() == glslang::EOpInterpolateAtCentroid ||
2229 node->getOp() == glslang::EOpRayQueryProceed ||
2230 node->getOp() == glslang::EOpRayQueryGetRayTMin ||
2231 node->getOp() == glslang::EOpRayQueryGetRayFlags ||
2232 node->getOp() == glslang::EOpRayQueryGetWorldRayOrigin ||
2233 node->getOp() == glslang::EOpRayQueryGetWorldRayDirection ||
2234 node->getOp() == glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque ||
2235 node->getOp() == glslang::EOpRayQueryTerminate ||
2236 node->getOp() == glslang::EOpRayQueryConfirmIntersection) {
Rex Xufc618912015-09-09 16:42:49 +08002237 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002238 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2239 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2240 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002241#endif
2242 {
John Kessenich32cfd492016-02-02 12:37:46 -07002243 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002244 }
John Kessenich140f3df2015-06-26 16:58:36 -06002245
John Kessenichead86222018-03-28 18:01:20 -06002246 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002247 TranslateNoContractionDecoration(node->getType().getQualifier()),
2248 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002249
2250 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002251 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002252 result = createConversion(node->getOp(), decorations, resultType(), operand,
2253 node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002254
2255 // if not, then possibly an operation
2256 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002257 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand,
2258 node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002259
2260 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002261 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002262 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002263 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002264 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002265
John Kessenich140f3df2015-06-26 16:58:36 -06002266 builder.clearAccessChain();
2267 builder.setAccessChainRValue(result);
2268
2269 return false; // done with this node
2270 }
2271
2272 // it must be a special case, check...
2273 switch (node->getOp()) {
2274 case glslang::EOpPostIncrement:
2275 case glslang::EOpPostDecrement:
2276 case glslang::EOpPreIncrement:
2277 case glslang::EOpPreDecrement:
2278 {
2279 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002280 spv::Id one = 0;
2281 if (node->getBasicType() == glslang::EbtFloat)
2282 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002283#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002284 else if (node->getBasicType() == glslang::EbtDouble)
2285 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002286 else if (node->getBasicType() == glslang::EbtFloat16)
2287 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002288 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2289 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002290 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2291 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002292 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2293 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002294#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002295 else
2296 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002297 glslang::TOperator op;
2298 if (node->getOp() == glslang::EOpPreIncrement ||
2299 node->getOp() == glslang::EOpPostIncrement)
2300 op = glslang::EOpAdd;
2301 else
2302 op = glslang::EOpSub;
2303
John Kessenichead86222018-03-28 18:01:20 -06002304 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002305 convertGlslangToSpvType(node->getType()), operand, one,
2306 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002307 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002308
2309 // The result of operation is always stored, but conditionally the
2310 // consumed result. The consumed result is always an r-value.
2311 builder.accessChainStore(result);
2312 builder.clearAccessChain();
2313 if (node->getOp() == glslang::EOpPreIncrement ||
2314 node->getOp() == glslang::EOpPreDecrement)
2315 builder.setAccessChainRValue(result);
2316 else
2317 builder.setAccessChainRValue(operand);
2318 }
2319
2320 return false;
2321
John Kessenich155d3512019-08-08 23:29:20 -06002322#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002323 case glslang::EOpEmitStreamVertex:
2324 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2325 return false;
2326 case glslang::EOpEndStreamPrimitive:
2327 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2328 return false;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002329 case glslang::EOpRayQueryTerminate:
2330 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operand);
2331 return false;
2332 case glslang::EOpRayQueryConfirmIntersection:
2333 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operand);
2334 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002335#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002336
2337 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002338 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002339 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002340 }
John Kessenich140f3df2015-06-26 16:58:36 -06002341}
2342
Jeff Bolz53134492019-06-25 13:31:10 -05002343// Construct a composite object, recursively copying members if their types don't match
2344spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2345{
2346 for (int c = 0; c < (int)constituents.size(); ++c) {
2347 spv::Id& constituent = constituents[c];
2348 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2349 spv::Id rType = builder.getTypeId(constituent);
2350 if (lType != rType) {
2351 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2352 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2353 } else if (builder.isStructType(rType)) {
2354 std::vector<spv::Id> rTypeConstituents;
2355 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2356 for (int i = 0; i < numrTypeConstituents; ++i) {
John Kessenich8985fc92020-03-03 10:25:07 -07002357 rTypeConstituents.push_back(builder.createCompositeExtract(constituent,
2358 builder.getContainedTypeId(rType, i), i));
Jeff Bolz53134492019-06-25 13:31:10 -05002359 }
2360 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2361 } else {
2362 assert(builder.isArrayType(rType));
2363 std::vector<spv::Id> rTypeConstituents;
2364 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2365
2366 spv::Id elementRType = builder.getContainedTypeId(rType);
2367 for (int i = 0; i < numrTypeConstituents; ++i) {
2368 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2369 }
2370 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2371 }
2372 }
2373 }
2374 return builder.createCompositeConstruct(resultTypeId, constituents);
2375}
2376
John Kessenich140f3df2015-06-26 16:58:36 -06002377bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2378{
qining27e04a02016-04-14 16:40:20 -04002379 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2380 if (node->getType().getQualifier().isSpecConstant())
2381 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2382
John Kessenichfc51d282015-08-19 13:34:18 -06002383 spv::Id result = spv::NoResult;
Cody Northrop4d2298b2020-04-13 21:59:49 -06002384 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2385 std::vector<spv::Builder::AccessChain> complexLvalues; // for holding swizzling l-values too complex for
2386 // SPIR-V, for an out parameter
2387 std::vector<spv::Id> temporaryLvalues; // temporaries to pass, as proxies for complexLValues
John Kessenichbbbd9a22020-03-03 07:21:37 -07002388
John Kessenich8985fc92020-03-03 10:25:07 -07002389 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2390 invertedType :
2391 convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002392
2393 // try texturing
2394 result = createImageTextureFunctionCall(node);
2395 if (result != spv::NoResult) {
2396 builder.clearAccessChain();
2397 builder.setAccessChainRValue(result);
2398
2399 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002400 }
2401#ifndef GLSLANG_WEB
2402 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002403 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002404 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002405 // "imageStore" is a special case, which has no result
2406 return false;
2407 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002408#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002409
John Kessenich140f3df2015-06-26 16:58:36 -06002410 glslang::TOperator binOp = glslang::EOpNull;
2411 bool reduceComparison = true;
2412 bool isMatrix = false;
2413 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002414 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002415
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002416 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2417
John Kessenich140f3df2015-06-26 16:58:36 -06002418 assert(node->getOp());
2419
John Kessenichf6640762016-08-01 19:44:00 -06002420 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002421
2422 switch (node->getOp()) {
2423 case glslang::EOpSequence:
2424 {
2425 if (preVisit)
2426 ++sequenceDepth;
2427 else
2428 --sequenceDepth;
2429
2430 if (sequenceDepth == 1) {
2431 // If this is the parent node of all the functions, we want to see them
2432 // early, so all call points have actual SPIR-V functions to reference.
2433 // In all cases, still let the traverser visit the children for us.
2434 makeFunctions(node->getAsAggregate()->getSequence());
2435
John Kessenich6fccb3c2016-09-19 16:01:41 -06002436 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002437 // anything else gets there, so visit out of order, doing them all now.
2438 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2439
John Kessenich6a60c2f2016-12-08 21:01:59 -07002440 // 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 -06002441 // so do them manually.
2442 visitFunctions(node->getAsAggregate()->getSequence());
2443
2444 return false;
2445 }
2446
2447 return true;
2448 }
2449 case glslang::EOpLinkerObjects:
2450 {
2451 if (visit == glslang::EvPreVisit)
2452 linkageOnly = true;
2453 else
2454 linkageOnly = false;
2455
2456 return true;
2457 }
2458 case glslang::EOpComma:
2459 {
2460 // processing from left to right naturally leaves the right-most
2461 // lying around in the access chain
2462 glslang::TIntermSequence& glslangOperands = node->getSequence();
2463 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2464 glslangOperands[i]->traverse(this);
2465
2466 return false;
2467 }
2468 case glslang::EOpFunction:
2469 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002470 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002471 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002472 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002473 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002474 } else {
2475 handleFunctionEntry(node);
2476 }
2477 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002478 if (inEntryPoint)
2479 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002480 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002481 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002482 }
2483
2484 return true;
2485 case glslang::EOpParameters:
2486 // Parameters will have been consumed by EOpFunction processing, but not
2487 // the body, so we still visited the function node's children, making this
2488 // child redundant.
2489 return false;
2490 case glslang::EOpFunctionCall:
2491 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002492 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002493 if (node->isUserDefined())
2494 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07002495 if (result) {
2496 builder.clearAccessChain();
2497 builder.setAccessChainRValue(result);
2498 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002499 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002500
2501 return false;
2502 }
2503 case glslang::EOpConstructMat2x2:
2504 case glslang::EOpConstructMat2x3:
2505 case glslang::EOpConstructMat2x4:
2506 case glslang::EOpConstructMat3x2:
2507 case glslang::EOpConstructMat3x3:
2508 case glslang::EOpConstructMat3x4:
2509 case glslang::EOpConstructMat4x2:
2510 case glslang::EOpConstructMat4x3:
2511 case glslang::EOpConstructMat4x4:
2512 case glslang::EOpConstructDMat2x2:
2513 case glslang::EOpConstructDMat2x3:
2514 case glslang::EOpConstructDMat2x4:
2515 case glslang::EOpConstructDMat3x2:
2516 case glslang::EOpConstructDMat3x3:
2517 case glslang::EOpConstructDMat3x4:
2518 case glslang::EOpConstructDMat4x2:
2519 case glslang::EOpConstructDMat4x3:
2520 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002521 case glslang::EOpConstructIMat2x2:
2522 case glslang::EOpConstructIMat2x3:
2523 case glslang::EOpConstructIMat2x4:
2524 case glslang::EOpConstructIMat3x2:
2525 case glslang::EOpConstructIMat3x3:
2526 case glslang::EOpConstructIMat3x4:
2527 case glslang::EOpConstructIMat4x2:
2528 case glslang::EOpConstructIMat4x3:
2529 case glslang::EOpConstructIMat4x4:
2530 case glslang::EOpConstructUMat2x2:
2531 case glslang::EOpConstructUMat2x3:
2532 case glslang::EOpConstructUMat2x4:
2533 case glslang::EOpConstructUMat3x2:
2534 case glslang::EOpConstructUMat3x3:
2535 case glslang::EOpConstructUMat3x4:
2536 case glslang::EOpConstructUMat4x2:
2537 case glslang::EOpConstructUMat4x3:
2538 case glslang::EOpConstructUMat4x4:
2539 case glslang::EOpConstructBMat2x2:
2540 case glslang::EOpConstructBMat2x3:
2541 case glslang::EOpConstructBMat2x4:
2542 case glslang::EOpConstructBMat3x2:
2543 case glslang::EOpConstructBMat3x3:
2544 case glslang::EOpConstructBMat3x4:
2545 case glslang::EOpConstructBMat4x2:
2546 case glslang::EOpConstructBMat4x3:
2547 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002548 case glslang::EOpConstructF16Mat2x2:
2549 case glslang::EOpConstructF16Mat2x3:
2550 case glslang::EOpConstructF16Mat2x4:
2551 case glslang::EOpConstructF16Mat3x2:
2552 case glslang::EOpConstructF16Mat3x3:
2553 case glslang::EOpConstructF16Mat3x4:
2554 case glslang::EOpConstructF16Mat4x2:
2555 case glslang::EOpConstructF16Mat4x3:
2556 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002557 isMatrix = true;
2558 // fall through
2559 case glslang::EOpConstructFloat:
2560 case glslang::EOpConstructVec2:
2561 case glslang::EOpConstructVec3:
2562 case glslang::EOpConstructVec4:
2563 case glslang::EOpConstructDouble:
2564 case glslang::EOpConstructDVec2:
2565 case glslang::EOpConstructDVec3:
2566 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002567 case glslang::EOpConstructFloat16:
2568 case glslang::EOpConstructF16Vec2:
2569 case glslang::EOpConstructF16Vec3:
2570 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002571 case glslang::EOpConstructBool:
2572 case glslang::EOpConstructBVec2:
2573 case glslang::EOpConstructBVec3:
2574 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002575 case glslang::EOpConstructInt8:
2576 case glslang::EOpConstructI8Vec2:
2577 case glslang::EOpConstructI8Vec3:
2578 case glslang::EOpConstructI8Vec4:
2579 case glslang::EOpConstructUint8:
2580 case glslang::EOpConstructU8Vec2:
2581 case glslang::EOpConstructU8Vec3:
2582 case glslang::EOpConstructU8Vec4:
2583 case glslang::EOpConstructInt16:
2584 case glslang::EOpConstructI16Vec2:
2585 case glslang::EOpConstructI16Vec3:
2586 case glslang::EOpConstructI16Vec4:
2587 case glslang::EOpConstructUint16:
2588 case glslang::EOpConstructU16Vec2:
2589 case glslang::EOpConstructU16Vec3:
2590 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002591 case glslang::EOpConstructInt:
2592 case glslang::EOpConstructIVec2:
2593 case glslang::EOpConstructIVec3:
2594 case glslang::EOpConstructIVec4:
2595 case glslang::EOpConstructUint:
2596 case glslang::EOpConstructUVec2:
2597 case glslang::EOpConstructUVec3:
2598 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002599 case glslang::EOpConstructInt64:
2600 case glslang::EOpConstructI64Vec2:
2601 case glslang::EOpConstructI64Vec3:
2602 case glslang::EOpConstructI64Vec4:
2603 case glslang::EOpConstructUint64:
2604 case glslang::EOpConstructU64Vec2:
2605 case glslang::EOpConstructU64Vec3:
2606 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002607 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002608 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002609 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002610 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002611 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002612 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002613 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002614 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002615 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002616 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002617 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002618 else if (node->getOp() == glslang::EOpConstructStruct ||
2619 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2620 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002621 std::vector<spv::Id> constituents;
2622 for (int c = 0; c < (int)arguments.size(); ++c)
2623 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002624 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002625 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002626 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002627 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002628 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002629
2630 builder.clearAccessChain();
2631 builder.setAccessChainRValue(constructed);
2632
2633 return false;
2634 }
2635
2636 // These six are component-wise compares with component-wise results.
2637 // Forward on to createBinaryOperation(), requesting a vector result.
2638 case glslang::EOpLessThan:
2639 case glslang::EOpGreaterThan:
2640 case glslang::EOpLessThanEqual:
2641 case glslang::EOpGreaterThanEqual:
2642 case glslang::EOpVectorEqual:
2643 case glslang::EOpVectorNotEqual:
2644 {
2645 // Map the operation to a binary
2646 binOp = node->getOp();
2647 reduceComparison = false;
2648 switch (node->getOp()) {
2649 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2650 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2651 default: binOp = node->getOp(); break;
2652 }
2653
2654 break;
2655 }
2656 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002657 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002658 binOp = glslang::EOpMul;
2659 break;
2660 case glslang::EOpOuterProduct:
2661 // two vectors multiplied to make a matrix
2662 binOp = glslang::EOpOuterProduct;
2663 break;
2664 case glslang::EOpDot:
2665 {
qining25262b32016-05-06 17:25:16 -04002666 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002667 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002668 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002669 binOp = glslang::EOpMul;
2670 break;
2671 }
2672 case glslang::EOpMod:
2673 // when an aggregate, this is the floating-point mod built-in function,
2674 // which can be emitted by the one in createBinaryOperation()
2675 binOp = glslang::EOpMod;
2676 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002677
John Kessenich140f3df2015-06-26 16:58:36 -06002678 case glslang::EOpEmitVertex:
2679 case glslang::EOpEndPrimitive:
2680 case glslang::EOpBarrier:
2681 case glslang::EOpMemoryBarrier:
2682 case glslang::EOpMemoryBarrierAtomicCounter:
2683 case glslang::EOpMemoryBarrierBuffer:
2684 case glslang::EOpMemoryBarrierImage:
2685 case glslang::EOpMemoryBarrierShared:
2686 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002687 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002688 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002689 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002690 case glslang::EOpWorkgroupMemoryBarrier:
2691 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002692 case glslang::EOpSubgroupBarrier:
2693 case glslang::EOpSubgroupMemoryBarrier:
2694 case glslang::EOpSubgroupMemoryBarrierBuffer:
2695 case glslang::EOpSubgroupMemoryBarrierImage:
2696 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002697 noReturnValue = true;
2698 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2699 break;
2700
John Kessenich426394d2015-07-23 10:22:48 -06002701 case glslang::EOpAtomicAdd:
2702 case glslang::EOpAtomicMin:
2703 case glslang::EOpAtomicMax:
2704 case glslang::EOpAtomicAnd:
2705 case glslang::EOpAtomicOr:
2706 case glslang::EOpAtomicXor:
2707 case glslang::EOpAtomicExchange:
2708 case glslang::EOpAtomicCompSwap:
2709 atomic = true;
2710 break;
2711
John Kesseniche5eee8f2019-10-18 01:03:11 -06002712#ifndef GLSLANG_WEB
2713 case glslang::EOpAtomicStore:
2714 noReturnValue = true;
2715 // fallthrough
2716 case glslang::EOpAtomicLoad:
2717 atomic = true;
2718 break;
2719
John Kessenich0d0c6d32017-07-23 16:08:26 -06002720 case glslang::EOpAtomicCounterAdd:
2721 case glslang::EOpAtomicCounterSubtract:
2722 case glslang::EOpAtomicCounterMin:
2723 case glslang::EOpAtomicCounterMax:
2724 case glslang::EOpAtomicCounterAnd:
2725 case glslang::EOpAtomicCounterOr:
2726 case glslang::EOpAtomicCounterXor:
2727 case glslang::EOpAtomicCounterExchange:
2728 case glslang::EOpAtomicCounterCompSwap:
2729 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2730 builder.addCapability(spv::CapabilityAtomicStorageOps);
2731 atomic = true;
2732 break;
2733
Ian Romanickb3bd4022019-01-21 08:57:25 -08002734 case glslang::EOpAbsDifference:
2735 case glslang::EOpAddSaturate:
2736 case glslang::EOpSubSaturate:
2737 case glslang::EOpAverage:
2738 case glslang::EOpAverageRounded:
2739 case glslang::EOpMul32x16:
2740 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2741 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2742 binOp = node->getOp();
2743 break;
2744
Daniel Kochdb32b242020-03-17 20:42:47 -04002745 case glslang::EOpIgnoreIntersection:
2746 case glslang::EOpTerminateRay:
2747 case glslang::EOpTrace:
2748 case glslang::EOpExecuteCallable:
Chao Chen3c366992018-09-19 11:41:59 -07002749 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2750 noReturnValue = true;
2751 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04002752 case glslang::EOpRayQueryInitialize:
2753 case glslang::EOpRayQueryTerminate:
2754 case glslang::EOpRayQueryGenerateIntersection:
2755 case glslang::EOpRayQueryConfirmIntersection:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002756 builder.addExtension("SPV_KHR_ray_query");
2757 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
Torosdagli06c2eee2020-03-19 11:09:57 -04002758 noReturnValue = true;
2759 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002760 case glslang::EOpRayQueryProceed:
2761 case glslang::EOpRayQueryGetIntersectionType:
2762 case glslang::EOpRayQueryGetRayTMin:
2763 case glslang::EOpRayQueryGetRayFlags:
2764 case glslang::EOpRayQueryGetIntersectionT:
2765 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2766 case glslang::EOpRayQueryGetIntersectionInstanceId:
2767 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2768 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2769 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2770 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2771 case glslang::EOpRayQueryGetIntersectionFrontFace:
2772 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
2773 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2774 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2775 case glslang::EOpRayQueryGetWorldRayDirection:
2776 case glslang::EOpRayQueryGetWorldRayOrigin:
2777 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2778 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2779 builder.addExtension("SPV_KHR_ray_query");
2780 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
2781 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002782 case glslang::EOpCooperativeMatrixLoad:
2783 case glslang::EOpCooperativeMatrixStore:
2784 noReturnValue = true;
2785 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002786 case glslang::EOpBeginInvocationInterlock:
2787 case glslang::EOpEndInvocationInterlock:
2788 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2789 noReturnValue = true;
2790 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002791#endif
Chao Chen3c366992018-09-19 11:41:59 -07002792
Jeff Bolz04d73732019-05-31 13:06:01 -05002793 case glslang::EOpDebugPrintf:
2794 noReturnValue = true;
2795 break;
2796
John Kessenich140f3df2015-06-26 16:58:36 -06002797 default:
2798 break;
2799 }
2800
2801 //
2802 // See if it maps to a regular operation.
2803 //
John Kessenich140f3df2015-06-26 16:58:36 -06002804 if (binOp != glslang::EOpNull) {
2805 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2806 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2807 assert(left && right);
2808
2809 builder.clearAccessChain();
2810 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002811 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002812
2813 builder.clearAccessChain();
2814 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002815 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002816
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002817 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002818 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002819 TranslateNoContractionDecoration(node->getType().getQualifier()),
2820 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002821 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002822 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002823 left->getType().getBasicType(), reduceComparison);
2824
2825 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002826 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002827 builder.clearAccessChain();
2828 builder.setAccessChainRValue(result);
2829
2830 return false;
2831 }
2832
John Kessenich426394d2015-07-23 10:22:48 -06002833 //
2834 // Create the list of operands.
2835 //
John Kessenich140f3df2015-06-26 16:58:36 -06002836 glslang::TIntermSequence& glslangOperands = node->getSequence();
2837 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002838 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002839 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002840 // special case l-value operands; there are just a few
2841 bool lvalue = false;
2842 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002843 case glslang::EOpModf:
2844 if (arg == 1)
2845 lvalue = true;
2846 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002847
Torosdagli06c2eee2020-03-19 11:09:57 -04002848 case glslang::EOpRayQueryInitialize:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002849 case glslang::EOpRayQueryTerminate:
2850 case glslang::EOpRayQueryConfirmIntersection:
2851 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04002852 case glslang::EOpRayQueryGenerateIntersection:
2853 case glslang::EOpRayQueryGetIntersectionType:
2854 case glslang::EOpRayQueryGetIntersectionT:
2855 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2856 case glslang::EOpRayQueryGetIntersectionInstanceId:
2857 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2858 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2859 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2860 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2861 case glslang::EOpRayQueryGetIntersectionFrontFace:
2862 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2863 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2864 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2865 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2866 if (arg == 0)
2867 lvalue = true;
2868 break;
2869
John Kesseniche5eee8f2019-10-18 01:03:11 -06002870 case glslang::EOpAtomicAdd:
2871 case glslang::EOpAtomicMin:
2872 case glslang::EOpAtomicMax:
2873 case glslang::EOpAtomicAnd:
2874 case glslang::EOpAtomicOr:
2875 case glslang::EOpAtomicXor:
2876 case glslang::EOpAtomicExchange:
2877 case glslang::EOpAtomicCompSwap:
2878 if (arg == 0)
2879 lvalue = true;
2880 break;
2881
John Kessenicha28f7a72019-08-06 07:00:58 -06002882#ifndef GLSLANG_WEB
2883 case glslang::EOpFrexp:
2884 if (arg == 1)
2885 lvalue = true;
2886 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002887 case glslang::EOpInterpolateAtSample:
2888 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002889 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002890 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002891 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002892
2893 // Does it need a swizzle inversion? If so, evaluation is inverted;
2894 // operate first on the swizzle base, then apply the swizzle.
John Kessenichbbbd9a22020-03-03 07:21:37 -07002895 // That is, we transform
2896 //
2897 // interpolate(v.zy) -> interpolate(v).zy
2898 //
John Kessenichecba76f2017-01-06 00:34:48 -07002899 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002900 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
John Kessenich8985fc92020-03-03 10:25:07 -07002901 invertedType = convertGlslangToSpvType(
2902 glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
John Kessenich8c8505c2016-07-26 12:50:38 -06002903 }
Rex Xu7a26c172015-12-08 17:12:09 +08002904 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002905 case glslang::EOpAtomicLoad:
2906 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002907 case glslang::EOpAtomicCounterAdd:
2908 case glslang::EOpAtomicCounterSubtract:
2909 case glslang::EOpAtomicCounterMin:
2910 case glslang::EOpAtomicCounterMax:
2911 case glslang::EOpAtomicCounterAnd:
2912 case glslang::EOpAtomicCounterOr:
2913 case glslang::EOpAtomicCounterXor:
2914 case glslang::EOpAtomicCounterExchange:
2915 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002916 if (arg == 0)
2917 lvalue = true;
2918 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002919 case glslang::EOpAddCarry:
2920 case glslang::EOpSubBorrow:
2921 if (arg == 2)
2922 lvalue = true;
2923 break;
2924 case glslang::EOpUMulExtended:
2925 case glslang::EOpIMulExtended:
2926 if (arg >= 2)
2927 lvalue = true;
2928 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002929 case glslang::EOpCooperativeMatrixLoad:
2930 if (arg == 0 || arg == 1)
2931 lvalue = true;
2932 break;
2933 case glslang::EOpCooperativeMatrixStore:
2934 if (arg == 1)
2935 lvalue = true;
2936 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002937#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002938 default:
2939 break;
2940 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002941 builder.clearAccessChain();
2942 if (invertedType != spv::NoType && arg == 0)
2943 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2944 else
2945 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002946
John Kessenichb9197c82019-08-11 07:41:45 -06002947#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002948 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2949 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2950
2951 if (arg == 1) {
2952 // fold "element" parameter into the access chain
2953 spv::Builder::AccessChain save = builder.getAccessChain();
2954 builder.clearAccessChain();
2955 glslangOperands[2]->traverse(this);
2956
2957 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2958
2959 builder.setAccessChain(save);
2960
2961 // Point to the first element of the array.
John Kessenich8985fc92020-03-03 10:25:07 -07002962 builder.accessChainPush(elementId,
2963 TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
2964 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002965
2966 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2967 unsigned int alignment = builder.getAccessChain().alignment;
2968
2969 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2970 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2971 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2972 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2973 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
John Kessenich8985fc92020-03-03 10:25:07 -07002974 if (builder.getStorageClass(builder.getAccessChain().base) ==
2975 spv::StorageClassPhysicalStorageBufferEXT) {
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002976 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2977 }
2978
2979 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2980
2981 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2982 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2983 }
2984
John Kessenich8985fc92020-03-03 10:25:07 -07002985 if (memoryAccess &
2986 (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2987 memoryAccessOperands.push_back(spv::IdImmediate(true,
2988 builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002989 }
2990 } else if (arg == 2) {
2991 continue;
2992 }
2993 }
John Kessenichb9197c82019-08-11 07:41:45 -06002994#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002995
John Kessenichbbbd9a22020-03-03 07:21:37 -07002996 // for l-values, pass the address, for r-values, pass the value
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002997 if (lvalue) {
John Kessenichbbbd9a22020-03-03 07:21:37 -07002998 if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
2999 // SPIR-V cannot represent an l-value containing a swizzle that doesn't
3000 // reduce to a simple access chain. So, we need a temporary vector to
3001 // receive the result, and must later swizzle that into the original
3002 // l-value.
Cody Northrop4d2298b2020-04-13 21:59:49 -06003003 complexLvalues.push_back(builder.getAccessChain());
John Kessenich435dd802020-06-30 01:27:08 -06003004 temporaryLvalues.push_back(builder.createVariable(
3005 spv::NoPrecision, spv::StorageClassFunction,
Cody Northrop4d2298b2020-04-13 21:59:49 -06003006 builder.accessChainGetInferredType(), "swizzleTemp"));
3007 operands.push_back(temporaryLvalues.back());
John Kessenichbbbd9a22020-03-03 07:21:37 -07003008 } else {
3009 operands.push_back(builder.accessChainGetLValue());
3010 }
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003011 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
3012 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
3013 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003014 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Torosdagli06c2eee2020-03-19 11:09:57 -04003015 glslang::TOperator glslangOp = node->getOp();
3016 if (arg == 1 &&
3017 (glslangOp == glslang::EOpRayQueryGetIntersectionType ||
3018 glslangOp == glslang::EOpRayQueryGetIntersectionT ||
3019 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceCustomIndex ||
3020 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceId ||
3021 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset ||
3022 glslangOp == glslang::EOpRayQueryGetIntersectionGeometryIndex ||
3023 glslangOp == glslang::EOpRayQueryGetIntersectionPrimitiveIndex ||
3024 glslangOp == glslang::EOpRayQueryGetIntersectionBarycentrics ||
3025 glslangOp == glslang::EOpRayQueryGetIntersectionFrontFace ||
3026 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayDirection ||
3027 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayOrigin ||
3028 glslangOp == glslang::EOpRayQueryGetIntersectionObjectToWorld ||
3029 glslangOp == glslang::EOpRayQueryGetIntersectionWorldToObject
3030 )) {
3031 bool cond = glslangOperands[arg]->getAsConstantUnion()->getConstArray()[0].getBConst();
3032 operands.push_back(builder.makeIntConstant(cond ? 1 : 0));
3033 }
3034 else {
3035 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
3036 }
3037
John Kesseniche485c7a2017-05-31 18:50:53 -06003038 }
John Kessenich140f3df2015-06-26 16:58:36 -06003039 }
John Kessenich426394d2015-07-23 10:22:48 -06003040
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003041 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06003042#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003043 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
3044 std::vector<spv::IdImmediate> idImmOps;
3045
3046 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3047 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3048 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3049 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3050 // get the pointee type
3051 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
3052 assert(builder.isCooperativeMatrixType(typeId));
3053 // do the op
3054 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
3055 // store the result to the pointer (out param 'm')
3056 builder.createStore(result, operands[0]);
3057 result = 0;
3058 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
3059 std::vector<spv::IdImmediate> idImmOps;
3060
3061 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3062 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
3063 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3064 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3065 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3066
3067 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
3068 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06003069 } else
3070#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06003071 if (atomic) {
3072 // Handle all atomics
John Kessenich8985fc92020-03-03 10:25:07 -07003073 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
3074 lvalueCoherentFlags);
Jeff Bolz04d73732019-05-31 13:06:01 -05003075 } else if (node->getOp() == glslang::EOpDebugPrintf) {
3076 if (!nonSemanticDebugPrintf) {
3077 nonSemanticDebugPrintf = builder.import("NonSemantic.DebugPrintf");
3078 }
3079 result = builder.createBuiltinCall(builder.makeVoidType(), nonSemanticDebugPrintf, spv::NonSemanticDebugPrintfDebugPrintf, operands);
3080 builder.addExtension(spv::E_SPV_KHR_non_semantic_info);
John Kesseniche5eee8f2019-10-18 01:03:11 -06003081 } else {
John Kessenich426394d2015-07-23 10:22:48 -06003082 // Pass through to generic operations.
3083 switch (glslangOperands.size()) {
3084 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06003085 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06003086 break;
3087 case 1:
John Kessenichead86222018-03-28 18:01:20 -06003088 {
3089 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06003090 TranslateNoContractionDecoration(node->getType().getQualifier()),
3091 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06003092 result = createUnaryOperation(
3093 node->getOp(), decorations,
3094 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003095 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06003096 }
John Kessenich426394d2015-07-23 10:22:48 -06003097 break;
3098 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06003099 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06003100 break;
3101 }
Cody Northrop4d2298b2020-04-13 21:59:49 -06003102
John Kessenichbbbd9a22020-03-03 07:21:37 -07003103 if (invertedType != spv::NoResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003104 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
Cody Northrop4d2298b2020-04-13 21:59:49 -06003105
3106 for (unsigned int i = 0; i < temporaryLvalues.size(); ++i) {
3107 builder.setAccessChain(complexLvalues[i]);
John Kessenich435dd802020-06-30 01:27:08 -06003108 builder.accessChainStore(builder.createLoad(temporaryLvalues[i], spv::NoPrecision));
John Kessenichbbbd9a22020-03-03 07:21:37 -07003109 }
John Kessenich140f3df2015-06-26 16:58:36 -06003110 }
3111
3112 if (noReturnValue)
3113 return false;
3114
3115 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04003116 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07003117 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06003118 } else {
3119 builder.clearAccessChain();
3120 builder.setAccessChainRValue(result);
3121 return false;
3122 }
3123}
3124
John Kessenich433e9ff2017-01-26 20:31:11 -07003125// This path handles both if-then-else and ?:
3126// The if-then-else has a node type of void, while
3127// ?: has either a void or a non-void node type
3128//
3129// Leaving the result, when not void:
3130// GLSL only has r-values as the result of a :?, but
3131// if we have an l-value, that can be more efficient if it will
3132// become the base of a complex r-value expression, because the
3133// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06003134bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
3135{
John Kessenich0c1e71a2019-01-10 18:23:06 +07003136 // see if OpSelect can handle it
3137 const auto isOpSelectable = [&]() {
3138 if (node->getBasicType() == glslang::EbtVoid)
3139 return false;
3140 // OpSelect can do all other types starting with SPV 1.4
3141 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
3142 // pre-1.4, only scalars and vectors can be handled
3143 if ((!node->getType().isScalar() && !node->getType().isVector()))
3144 return false;
3145 }
3146 return true;
3147 };
3148
John Kessenich4bee5312018-02-20 21:29:05 -07003149 // See if it simple and safe, or required, to execute both sides.
3150 // Crucially, side effects must be either semantically required or avoided,
3151 // and there are performance trade-offs.
3152 // Return true if required or a good idea (and safe) to execute both sides,
3153 // false otherwise.
3154 const auto bothSidesPolicy = [&]() -> bool {
3155 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07003156 if (node->getTrueBlock() == nullptr ||
3157 node->getFalseBlock() == nullptr)
3158 return false;
3159
John Kessenich4bee5312018-02-20 21:29:05 -07003160 // required? (unless we write additional code to look for side effects
3161 // and make performance trade-offs if none are present)
3162 if (!node->getShortCircuit())
3163 return true;
3164
3165 // if not required to execute both, decide based on performance/practicality...
3166
John Kessenich0c1e71a2019-01-10 18:23:06 +07003167 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07003168 return false;
3169
John Kessenich433e9ff2017-01-26 20:31:11 -07003170 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
3171 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
3172
3173 // return true if a single operand to ? : is okay for OpSelect
3174 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003175 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07003176 };
3177
3178 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
3179 operandOkay(node->getFalseBlock()->getAsTyped());
3180 };
3181
John Kessenich4bee5312018-02-20 21:29:05 -07003182 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
3183 // emit the condition before doing anything with selection
3184 node->getCondition()->traverse(this);
3185 spv::Id condition = accessChainLoad(node->getCondition()->getType());
3186
3187 // Find a way of executing both sides and selecting the right result.
3188 const auto executeBothSides = [&]() -> void {
3189 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07003190 node->getTrueBlock()->traverse(this);
3191 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3192 node->getFalseBlock()->traverse(this);
3193 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3194
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003195 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003196
John Kessenich4bee5312018-02-20 21:29:05 -07003197 // done if void
3198 if (node->getBasicType() == glslang::EbtVoid)
3199 return;
John Kesseniche434ad92017-03-30 10:09:28 -06003200
John Kessenich4bee5312018-02-20 21:29:05 -07003201 // emit code to select between trueValue and falseValue
3202
3203 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07003204 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07003205 // Emit OpSelect for this selection.
3206
3207 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07003208 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
3209 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07003210 condition = builder.smearScalar(spv::NoPrecision, condition,
3211 builder.makeVectorType(builder.makeBoolType(),
3212 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07003213 }
John Kessenich4bee5312018-02-20 21:29:05 -07003214
3215 // OpSelect
3216 result = builder.createTriOp(spv::OpSelect,
3217 convertGlslangToSpvType(node->getType()), condition,
3218 trueValue, falseValue);
3219
3220 builder.clearAccessChain();
3221 builder.setAccessChainRValue(result);
3222 } else {
3223 // We need control flow to select the result.
3224 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
John Kessenich435dd802020-06-30 01:27:08 -06003225 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()),
3226 spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich4bee5312018-02-20 21:29:05 -07003227
3228 // Selection control:
3229 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3230
3231 // make an "if" based on the value created by the condition
3232 spv::Builder::If ifBuilder(condition, control, builder);
3233
3234 // emit the "then" statement
3235 builder.createStore(trueValue, result);
3236 ifBuilder.makeBeginElse();
3237 // emit the "else" statement
3238 builder.createStore(falseValue, result);
3239
3240 // finish off the control flow
3241 ifBuilder.makeEndIf();
3242
3243 builder.clearAccessChain();
3244 builder.setAccessChainLValue(result);
3245 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003246 };
3247
John Kessenich4bee5312018-02-20 21:29:05 -07003248 // Execute the one side needed, as per the condition
3249 const auto executeOneSide = [&]() {
3250 // Always emit control flow.
John Kessenich435dd802020-06-30 01:27:08 -06003251 if (node->getBasicType() != glslang::EbtVoid) {
3252 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()), spv::StorageClassFunction,
3253 convertGlslangToSpvType(node->getType()));
3254 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003255
John Kessenich4bee5312018-02-20 21:29:05 -07003256 // Selection control:
3257 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3258
3259 // make an "if" based on the value created by the condition
3260 spv::Builder::If ifBuilder(condition, control, builder);
3261
3262 // emit the "then" statement
3263 if (node->getTrueBlock() != nullptr) {
3264 node->getTrueBlock()->traverse(this);
3265 if (result != spv::NoResult)
3266 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3267 }
3268
3269 if (node->getFalseBlock() != nullptr) {
3270 ifBuilder.makeBeginElse();
3271 // emit the "else" statement
3272 node->getFalseBlock()->traverse(this);
3273 if (result != spv::NoResult)
3274 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3275 }
3276
3277 // finish off the control flow
3278 ifBuilder.makeEndIf();
3279
3280 if (result != spv::NoResult) {
3281 builder.clearAccessChain();
3282 builder.setAccessChainLValue(result);
3283 }
3284 };
3285
3286 // Try for OpSelect (or a requirement to execute both sides)
3287 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003288 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3289 if (node->getType().getQualifier().isSpecConstant())
3290 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003291 executeBothSides();
3292 } else
3293 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003294
3295 return false;
3296}
3297
3298bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3299{
3300 // emit and get the condition before doing anything with switch
3301 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003302 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003303
Rex Xu57e65922017-07-04 23:23:40 +08003304 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003305 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003306
John Kessenich140f3df2015-06-26 16:58:36 -06003307 // browse the children to sort out code segments
3308 int defaultSegment = -1;
3309 std::vector<TIntermNode*> codeSegments;
3310 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3311 std::vector<int> caseValues;
3312 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3313 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3314 TIntermNode* child = *c;
3315 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003316 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003317 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003318 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich8985fc92020-03-03 10:25:07 -07003319 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()
3320 ->getConstArray()[0].getIConst());
John Kessenich140f3df2015-06-26 16:58:36 -06003321 } else
3322 codeSegments.push_back(child);
3323 }
3324
qining25262b32016-05-06 17:25:16 -04003325 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003326 // statements between the last case and the end of the switch statement
3327 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3328 (int)codeSegments.size() == defaultSegment)
3329 codeSegments.push_back(nullptr);
3330
3331 // make the switch statement
3332 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
John Kessenich8985fc92020-03-03 10:25:07 -07003333 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment,
3334 segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003335
3336 // emit all the code in the segments
3337 breakForLoop.push(false);
3338 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3339 builder.nextSwitchSegment(segmentBlocks, s);
3340 if (codeSegments[s])
3341 codeSegments[s]->traverse(this);
3342 else
3343 builder.addSwitchBreak();
3344 }
3345 breakForLoop.pop();
3346
3347 builder.endSwitch(segmentBlocks);
3348
3349 return false;
3350}
3351
3352void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3353{
3354 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003355 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003356
3357 builder.clearAccessChain();
3358 builder.setAccessChainRValue(constant);
3359}
3360
3361bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3362{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003363 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003364 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003365
3366 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003367 std::vector<unsigned int> operands;
3368 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003369
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003370 // Spec requires back edges to target header blocks, and every header block
3371 // must dominate its merge block. Make a header block first to ensure these
3372 // conditions are met. By definition, it will contain OpLoopMerge, followed
3373 // by a block-ending branch. But we don't want to put any other body/test
3374 // instructions in it, since the body/test may have arbitrary instructions,
3375 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003376 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003377 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003378 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003379 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003380 spv::Block& test = builder.makeNewBlock();
3381 builder.createBranch(&test);
3382
3383 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003384 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003385 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003386 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3387
3388 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003389 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003390 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003391 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003392 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003393 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003394
3395 builder.setBuildPoint(&blocks.continue_target);
3396 if (node->getTerminal())
3397 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003398 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003399 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003400 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003401 builder.createBranch(&blocks.body);
3402
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003403 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003404 builder.setBuildPoint(&blocks.body);
3405 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003406 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003407 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003408 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003409
3410 builder.setBuildPoint(&blocks.continue_target);
3411 if (node->getTerminal())
3412 node->getTerminal()->traverse(this);
3413 if (node->getTest()) {
3414 node->getTest()->traverse(this);
3415 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003416 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003417 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003418 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003419 // TODO: unless there was a break/return/discard instruction
3420 // somewhere in the body, this is an infinite loop, so we should
3421 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003422 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003423 }
John Kessenich140f3df2015-06-26 16:58:36 -06003424 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003425 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003426 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003427 return false;
3428}
3429
3430bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3431{
3432 if (node->getExpression())
3433 node->getExpression()->traverse(this);
3434
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003435 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003436
John Kessenich140f3df2015-06-26 16:58:36 -06003437 switch (node->getFlowOp()) {
3438 case glslang::EOpKill:
3439 builder.makeDiscard();
3440 break;
3441 case glslang::EOpBreak:
3442 if (breakForLoop.top())
3443 builder.createLoopExit();
3444 else
3445 builder.addSwitchBreak();
3446 break;
3447 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003448 builder.createLoopContinue();
3449 break;
3450 case glslang::EOpReturn:
John Kessenich435dd802020-06-30 01:27:08 -06003451 if (node->getExpression() != nullptr) {
John Kesseniched33e052016-10-06 12:59:51 -06003452 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3453 spv::Id returnId = accessChainLoad(glslangReturnType);
John Kessenich435dd802020-06-30 01:27:08 -06003454 if (builder.getTypeId(returnId) != currentFunction->getReturnType() ||
3455 TranslatePrecisionDecoration(glslangReturnType) != currentFunction->getReturnPrecision()) {
John Kesseniched33e052016-10-06 12:59:51 -06003456 builder.clearAccessChain();
John Kessenich435dd802020-06-30 01:27:08 -06003457 spv::Id copyId = builder.createVariable(currentFunction->getReturnPrecision(),
3458 spv::StorageClassFunction, currentFunction->getReturnType());
John Kesseniched33e052016-10-06 12:59:51 -06003459 builder.setAccessChainLValue(copyId);
3460 multiTypeStore(glslangReturnType, returnId);
John Kessenich435dd802020-06-30 01:27:08 -06003461 returnId = builder.createLoad(copyId, currentFunction->getReturnPrecision());
John Kesseniched33e052016-10-06 12:59:51 -06003462 }
3463 builder.makeReturn(false, returnId);
3464 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003465 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003466
3467 builder.clearAccessChain();
3468 break;
3469
John Kessenichb9197c82019-08-11 07:41:45 -06003470#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003471 case glslang::EOpDemote:
3472 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3473 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3474 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3475 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003476#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003477
John Kessenich140f3df2015-06-26 16:58:36 -06003478 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003479 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003480 break;
3481 }
3482
3483 return false;
3484}
3485
John Kessenich9c14f772019-06-17 08:38:35 -06003486spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003487{
qining25262b32016-05-06 17:25:16 -04003488 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003489 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003490 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003491 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003492 spv::Id result = createSpvConstant(*node);
3493 if (result != spv::NoResult)
3494 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003495 }
3496
3497 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003498 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003499 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3500 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003501
John Kessenichb9197c82019-08-11 07:41:45 -06003502 const bool contains16BitType = node->getType().contains16BitFloat() ||
3503 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003504 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003505 switch (storageClass) {
3506 case spv::StorageClassInput:
3507 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003508 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003509 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003510 break;
John Kessenich18310872018-05-14 22:08:53 -06003511 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003512 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003513 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3514 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003515 else
3516 builder.addCapability(spv::CapabilityStorageUniform16);
3517 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003518#ifndef GLSLANG_WEB
3519 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003520 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003521 builder.addCapability(spv::CapabilityStoragePushConstant16);
3522 break;
John Kessenich18310872018-05-14 22:08:53 -06003523 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003524 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003525 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003526 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3527 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003528#endif
John Kessenich18310872018-05-14 22:08:53 -06003529 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003530 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003531 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003532 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003533 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003534 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003535 }
3536 }
Rex Xuf89ad982017-04-07 23:22:33 +08003537
John Kessenichb9197c82019-08-11 07:41:45 -06003538 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003539 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003540 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003541 builder.addCapability(spv::CapabilityStoragePushConstant8);
3542 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003543 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003544 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003545 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003546 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003547 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003548 } else {
3549 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003550 }
3551 }
3552
John Kessenich140f3df2015-06-26 16:58:36 -06003553 const char* name = node->getName().c_str();
3554 if (glslang::IsAnonymous(name))
3555 name = "";
3556
Alejandro Piñeiroff6dcca2020-06-04 09:39:31 +02003557 spv::Id initializer = spv::NoResult;
3558
3559 if (node->getType().getQualifier().storage == glslang::EvqUniform &&
3560 !node->getConstArray().empty()) {
3561 int nextConst = 0;
3562 initializer = createSpvConstantFromConstUnionArray(node->getType(),
3563 node->getConstArray(),
3564 nextConst,
3565 false /* specConst */);
3566 }
3567
John Kessenich435dd802020-06-30 01:27:08 -06003568 return builder.createVariable(spv::NoPrecision, storageClass, spvType, name, initializer);
John Kessenich140f3df2015-06-26 16:58:36 -06003569}
3570
3571// Return type Id of the sampled type.
3572spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3573{
3574 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003575 case glslang::EbtInt: return builder.makeIntType(32);
3576 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003577 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003578#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003579 case glslang::EbtFloat16:
3580 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3581 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3582 return builder.makeFloatType(16);
3583#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003584 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003585 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003586 return builder.makeFloatType(32);
3587 }
3588}
3589
John Kessenich8c8505c2016-07-26 12:50:38 -06003590// If node is a swizzle operation, return the type that should be used if
3591// the swizzle base is first consumed by another operation, before the swizzle
3592// is applied.
3593spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3594{
John Kessenichecba76f2017-01-06 00:34:48 -07003595 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003596 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3597 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3598 else
3599 return spv::NoType;
3600}
3601
3602// When inverting a swizzle with a parent op, this function
3603// will apply the swizzle operation to a completed parent operation.
John Kessenich8985fc92020-03-03 10:25:07 -07003604spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
3605 spv::Id parentResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003606{
3607 std::vector<unsigned> swizzle;
3608 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3609 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3610}
3611
John Kessenich8c8505c2016-07-26 12:50:38 -06003612// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3613void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3614{
3615 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3616 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3617 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3618}
3619
John Kessenich3ac051e2015-12-20 11:29:16 -07003620// Convert from a glslang type to an SPV type, by calling into a
3621// recursive version of this function. This establishes the inherited
3622// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003623spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003624{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003625 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003626}
3627
3628// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003629// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003630// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003631spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003632 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3633 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003634{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003635 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003636
3637 switch (type.getBasicType()) {
3638 case glslang::EbtVoid:
3639 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003640 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003641 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003642 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003643 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3644 // a 32-bit int where non-0 means true.
3645 if (explicitLayout != glslang::ElpNone)
3646 spvType = builder.makeUintType(32);
3647 else
3648 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003649 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003650 case glslang::EbtInt:
3651 spvType = builder.makeIntType(32);
3652 break;
3653 case glslang::EbtUint:
3654 spvType = builder.makeUintType(32);
3655 break;
3656 case glslang::EbtFloat:
3657 spvType = builder.makeFloatType(32);
3658 break;
3659#ifndef GLSLANG_WEB
3660 case glslang::EbtDouble:
3661 spvType = builder.makeFloatType(64);
3662 break;
3663 case glslang::EbtFloat16:
3664 spvType = builder.makeFloatType(16);
3665 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003666 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003667 spvType = builder.makeIntType(8);
3668 break;
3669 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003670 spvType = builder.makeUintType(8);
3671 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003672 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003673 spvType = builder.makeIntType(16);
3674 break;
3675 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003676 spvType = builder.makeUintType(16);
3677 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003678 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003679 spvType = builder.makeIntType(64);
3680 break;
3681 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003682 spvType = builder.makeUintType(64);
3683 break;
John Kessenich426394d2015-07-23 10:22:48 -06003684 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003685 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003686 spvType = builder.makeUintType(32);
3687 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04003688 case glslang::EbtAccStruct:
3689 spvType = builder.makeAccelerationStructureType();
Chao Chenb50c02e2018-09-19 11:42:24 -07003690 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04003691 case glslang::EbtRayQuery:
3692 spvType = builder.makeRayQueryType();
3693 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003694 case glslang::EbtReference:
3695 {
3696 // Make the forward pointer, then recurse to convert the structure type, then
3697 // patch up the forward pointer with a real pointer type.
3698 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3699 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3700 forwardPointers[type.getReferentType()] = forwardId;
3701 }
3702 spvType = forwardPointers[type.getReferentType()];
3703 if (!forwardReferenceOnly) {
3704 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3705 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3706 forwardPointers[type.getReferentType()],
3707 referentType);
3708 }
3709 }
3710 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003711#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003712 case glslang::EbtSampler:
3713 {
3714 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003715 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003716 spvType = builder.makeSamplerType();
3717 } else {
3718 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003719 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3720 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3721 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3722 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003723 // already has both image and sampler, make the combined type
3724 spvType = builder.makeSampledImageType(spvType);
3725 }
John Kessenich55e7d112015-11-15 21:33:39 -07003726 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003727 }
John Kessenich140f3df2015-06-26 16:58:36 -06003728 break;
3729 case glslang::EbtStruct:
3730 case glslang::EbtBlock:
3731 {
3732 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003733 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003734
3735 // Try to share structs for different layouts, but not yet for other
3736 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003737 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003738 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003739 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003740 break;
3741
3742 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003743 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003744 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003745 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003746 }
3747 break;
Jeff Bolz04d73732019-05-31 13:06:01 -05003748 case glslang::EbtString:
3749 // no type used for OpString
3750 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003751 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003752 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003753 break;
3754 }
3755
3756 if (type.isMatrix())
3757 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3758 else {
3759 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3760 if (type.getVectorSize() > 1)
3761 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3762 }
3763
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003764 if (type.isCoopMat()) {
3765 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3766 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3767 if (type.getBasicType() == glslang::EbtFloat16)
3768 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003769 if (type.getBasicType() == glslang::EbtUint8 ||
3770 type.getBasicType() == glslang::EbtInt8) {
3771 builder.addCapability(spv::CapabilityInt8);
3772 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003773
3774 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3775 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3776 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3777
3778 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3779 }
3780
John Kessenich140f3df2015-06-26 16:58:36 -06003781 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003782 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3783
John Kessenichc9a80832015-09-12 12:17:44 -06003784 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003785 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003786 // We need to decorate array strides for types needing explicit layout, except blocks.
3787 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003788 // Use a dummy glslang type for querying internal strides of
3789 // arrays of arrays, but using just a one-dimensional array.
3790 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003791 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3792 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003793
3794 // Will compute the higher-order strides here, rather than making a whole
3795 // pile of types and doing repetitive recursion on their contents.
3796 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3797 }
John Kessenichf8842e52016-01-04 19:22:56 -07003798
3799 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003800 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003801 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003802 if (stride > 0)
3803 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003804 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003805 }
3806 } else {
3807 // single-dimensional array, and don't yet have stride
3808
John Kessenichf8842e52016-01-04 19:22:56 -07003809 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003810 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3811 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003812 }
John Kessenich31ed4832015-09-09 17:51:38 -06003813
John Kessenichead86222018-03-28 18:01:20 -06003814 // Do the outer dimension, which might not be known for a runtime-sized array.
3815 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3816 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003817 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003818 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003819#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003820 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003821 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003822 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3823 }
John Kessenichb9197c82019-08-11 07:41:45 -06003824#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003825 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003826 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003827 if (stride > 0)
3828 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003829 }
3830
3831 return spvType;
3832}
3833
John Kessenich0e737842017-03-24 18:38:16 -06003834// TODO: this functionality should exist at a higher level, in creating the AST
3835//
3836// Identify interface members that don't have their required extension turned on.
3837//
3838bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3839{
John Kessenicha28f7a72019-08-06 07:00:58 -06003840#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003841 auto& extensions = glslangIntermediate->getRequestedExtensions();
3842
Rex Xubcf291a2017-03-29 23:01:36 +08003843 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3844 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3845 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003846 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3847 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3848 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003849
3850 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3851 if (member.getFieldName() == "gl_ViewportMask" &&
3852 extensions.find("GL_NV_viewport_array2") == extensions.end())
3853 return true;
3854 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3855 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3856 return true;
3857 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3858 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3859 return true;
3860 }
3861#endif
John Kessenich0e737842017-03-24 18:38:16 -06003862
3863 return false;
3864};
3865
John Kessenich6090df02016-06-30 21:18:02 -06003866// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3867// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3868// Mutually recursive with convertGlslangToSpvType().
3869spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3870 const glslang::TTypeList* glslangMembers,
3871 glslang::TLayoutPacking explicitLayout,
3872 const glslang::TQualifier& qualifier)
3873{
3874 // Create a vector of struct types for SPIR-V to consume
3875 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07003876 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
3877 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003878 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003879 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3880 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3881 if (glslangMember.hiddenMember()) {
3882 ++memberDelta;
3883 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003884 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06003885 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003886 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003887 if (filterMember(glslangMember)) {
3888 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08003889 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003890 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003891 }
Roy05a5b532020-01-03 16:21:34 +08003892 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003893 }
John Kessenich6090df02016-06-30 21:18:02 -06003894 // modify just this child's view of the qualifier
3895 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3896 InheritQualifiers(memberQualifier, qualifier);
3897
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003898 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003899 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003900 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003901
3902 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003903 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3904 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003905
3906 // Make forward pointers for any pointer members, and create a list of members to
3907 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003908 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003909 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3910 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3911 }
3912 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003913 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3914 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003915 } else {
3916 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003917 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3918 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003919 }
John Kessenich6090df02016-06-30 21:18:02 -06003920 }
3921 }
3922
3923 // Make the SPIR-V type
3924 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003925 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003926 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3927
3928 // Decorate it
3929 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3930
John Kessenichd72f4882019-01-16 14:55:37 +07003931 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003932 auto it = deferredForwardPointers[i];
3933 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3934 }
3935
John Kessenich6090df02016-06-30 21:18:02 -06003936 return spvType;
3937}
3938
3939void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3940 const glslang::TTypeList* glslangMembers,
3941 glslang::TLayoutPacking explicitLayout,
3942 const glslang::TQualifier& qualifier,
3943 spv::Id spvType)
3944{
3945 // Name and decorate the non-hidden members
3946 int offset = -1;
3947 int locationOffset = 0; // for use within the members of this struct
3948 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3949 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3950 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003951 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08003952 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06003953 if (filterMember(glslangMember))
3954 continue;
3955 }
John Kessenich6090df02016-06-30 21:18:02 -06003956
3957 // modify just this child's view of the qualifier
3958 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3959 InheritQualifiers(memberQualifier, qualifier);
3960
3961 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003962 if (member < 0)
3963 continue;
3964
3965 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3966 builder.addMemberDecoration(spvType, member,
3967 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3968 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3969 // Add interpolation and auxiliary storage decorations only to
3970 // top-level members of Input and Output storage classes
3971 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3972 type.getQualifier().storage == glslang::EvqVaryingOut) {
3973 if (type.getBasicType() == glslang::EbtBlock ||
3974 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3975 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3976 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003977#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003978 addMeshNVDecoration(spvType, member, memberQualifier);
3979#endif
John Kessenich6090df02016-06-30 21:18:02 -06003980 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003981 }
3982 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003983
John Kessenichb9197c82019-08-11 07:41:45 -06003984#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003985 if (type.getBasicType() == glslang::EbtBlock &&
3986 qualifier.storage == glslang::EvqBuffer) {
3987 // Add memory decorations only to top-level members of shader storage block
3988 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003989 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003990 for (unsigned int i = 0; i < memory.size(); ++i)
3991 builder.addMemberDecoration(spvType, member, memory[i]);
3992 }
John Kessenichf8d1d742019-10-21 06:55:11 -06003993
John Kessenichb9197c82019-08-11 07:41:45 -06003994#endif
John Kessenich6090df02016-06-30 21:18:02 -06003995
John Kessenich5d610ee2018-03-07 18:05:55 -07003996 // Location assignment was already completed correctly by the front end,
3997 // just track whether a member needs to be decorated.
3998 // Ignore member locations if the container is an array, as that's
3999 // ill-specified and decisions have been made to not allow this.
4000 if (! type.isArray() && memberQualifier.hasLocation())
4001 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06004002
John Kessenich5d610ee2018-03-07 18:05:55 -07004003 if (qualifier.hasLocation()) // track for upcoming inheritance
4004 locationOffset += glslangIntermediate->computeTypeLocationSize(
4005 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06004006
John Kessenich5d610ee2018-03-07 18:05:55 -07004007 // component, XFB, others
4008 if (glslangMember.getQualifier().hasComponent())
4009 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
4010 glslangMember.getQualifier().layoutComponent);
4011 if (glslangMember.getQualifier().hasXfbOffset())
4012 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
4013 glslangMember.getQualifier().layoutXfbOffset);
4014 else if (explicitLayout != glslang::ElpNone) {
4015 // figure out what to do with offset, which is accumulating
4016 int nextOffset;
4017 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
4018 if (offset >= 0)
4019 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
4020 offset = nextOffset;
4021 }
John Kessenich6090df02016-06-30 21:18:02 -06004022
John Kessenich5d610ee2018-03-07 18:05:55 -07004023 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
4024 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
4025 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06004026
John Kessenich5d610ee2018-03-07 18:05:55 -07004027 // built-in variable decorations
4028 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
4029 if (builtIn != spv::BuiltInMax)
4030 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08004031
John Kessenichb9197c82019-08-11 07:41:45 -06004032#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06004033 // nonuniform
4034 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
4035
John Kessenichead86222018-03-28 18:01:20 -06004036 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
4037 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
4038 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
4039 memberQualifier.semanticName);
4040 }
4041
John Kessenich5d610ee2018-03-07 18:05:55 -07004042 if (builtIn == spv::BuiltInLayer) {
4043 // SPV_NV_viewport_array2 extension
4044 if (glslangMember.getQualifier().layoutViewportRelative){
4045 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
4046 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4047 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08004048 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004049 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
4050 builder.addMemberDecoration(spvType, member,
4051 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
4052 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
4053 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4054 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08004055 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004056 }
4057 if (glslangMember.getQualifier().layoutPassthrough) {
4058 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
4059 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
4060 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4061 }
chaoc771d89f2017-01-13 01:10:53 -08004062#endif
John Kessenich6090df02016-06-30 21:18:02 -06004063 }
4064
4065 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07004066 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
4067 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06004068}
4069
John Kessenich6c292d32016-02-15 20:58:50 -07004070// Turn the expression forming the array size into an id.
4071// This is not quite trivial, because of specialization constants.
4072// Sometimes, a raw constant is turned into an Id, and sometimes
4073// a specialization constant expression is.
4074spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
4075{
4076 // First, see if this is sized with a node, meaning a specialization constant:
4077 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
4078 if (specNode != nullptr) {
4079 builder.clearAccessChain();
4080 specNode->traverse(this);
4081 return accessChainLoad(specNode->getAsTyped()->getType());
4082 }
qining25262b32016-05-06 17:25:16 -04004083
John Kessenich6c292d32016-02-15 20:58:50 -07004084 // Otherwise, need a compile-time (front end) size, get it:
4085 int size = arraySizes.getDimSize(dim);
4086 assert(size > 0);
4087 return builder.makeUintConstant(size);
4088}
4089
John Kessenich103bef92016-02-08 21:38:15 -07004090// Wrap the builder's accessChainLoad to:
4091// - localize handling of RelaxedPrecision
4092// - use the SPIR-V inferred type instead of another conversion of the glslang type
4093// (avoids unnecessary work and possible type punning for structures)
4094// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07004095spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
4096{
John Kessenich103bef92016-02-08 21:38:15 -07004097 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004098
4099 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4100 coherentFlags |= TranslateCoherent(type);
4101
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004102 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004103 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004104
John Kessenich5611c6d2018-04-05 11:25:02 -06004105 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
John Kessenich8985fc92020-03-03 10:25:07 -07004106 TranslateNonUniformDecoration(type.getQualifier()),
4107 nominalTypeId,
4108 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
4109 TranslateMemoryScope(coherentFlags),
4110 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07004111
4112 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08004113 if (type.getBasicType() == glslang::EbtBool) {
4114 if (builder.isScalarType(nominalTypeId)) {
4115 // Conversion for bool
4116 spv::Id boolType = builder.makeBoolType();
4117 if (nominalTypeId != boolType)
4118 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
4119 } else if (builder.isVectorType(nominalTypeId)) {
4120 // Conversion for bvec
4121 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4122 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
4123 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07004124 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
4125 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004126 }
4127 }
John Kessenich103bef92016-02-08 21:38:15 -07004128
4129 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07004130}
4131
Rex Xu27253232016-02-23 17:51:09 +08004132// Wrap the builder's accessChainStore to:
4133// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06004134//
4135// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08004136void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
4137{
4138 // Need to convert to abstract types when necessary
4139 if (type.getBasicType() == glslang::EbtBool) {
4140 spv::Id nominalTypeId = builder.accessChainGetInferredType();
4141
4142 if (builder.isScalarType(nominalTypeId)) {
4143 // Conversion for bool
4144 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06004145 if (nominalTypeId != boolType) {
4146 // keep these outside arguments, for determinant order-of-evaluation
4147 spv::Id one = builder.makeUintConstant(1);
4148 spv::Id zero = builder.makeUintConstant(0);
4149 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
4150 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06004151 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08004152 } else if (builder.isVectorType(nominalTypeId)) {
4153 // Conversion for bvec
4154 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4155 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06004156 if (nominalTypeId != bvecType) {
4157 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06004158 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
4159 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
4160 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06004161 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06004162 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
4163 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004164 }
4165 }
4166
Jeff Bolz36831c92018-09-05 10:11:41 -05004167 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4168 coherentFlags |= TranslateCoherent(type);
4169
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004170 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004171 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004172
Jeff Bolz36831c92018-09-05 10:11:41 -05004173 builder.accessChainStore(rvalue,
John Kessenich8985fc92020-03-03 10:25:07 -07004174 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
4175 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004176 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08004177}
4178
John Kessenich4bf71552016-09-02 11:20:21 -06004179// For storing when types match at the glslang level, but not might match at the
4180// SPIR-V level.
4181//
4182// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004183// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004184// as in a member-decorated way.
4185//
4186// NOTE: This function can handle any store request; if it's not special it
4187// simplifies to a simple OpStore.
4188//
4189// Implicitly uses the existing builder.accessChain as the storage target.
4190void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4191{
John Kessenichb3e24e42016-09-11 12:33:43 -06004192 // we only do the complex path here if it's an aggregate
4193 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004194 accessChainStore(type, rValue);
4195 return;
4196 }
4197
John Kessenichb3e24e42016-09-11 12:33:43 -06004198 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004199 spv::Id rType = builder.getTypeId(rValue);
4200 spv::Id lValue = builder.accessChainGetLValue();
4201 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4202 if (lType == rType) {
4203 accessChainStore(type, rValue);
4204 return;
4205 }
4206
John Kessenichb3e24e42016-09-11 12:33:43 -06004207 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004208 // where the two types were the same type in GLSL. This requires member
4209 // by member copy, recursively.
4210
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004211 // SPIR-V 1.4 added an instruction to do help do this.
4212 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4213 // However, bool in uniform space is changed to int, so
4214 // OpCopyLogical does not work for that.
4215 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4216 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4217 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4218 if (lBool == rBool) {
4219 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4220 accessChainStore(type, logicalCopy);
4221 return;
4222 }
4223 }
4224
John Kessenichb3e24e42016-09-11 12:33:43 -06004225 // If an array, copy element by element.
4226 if (type.isArray()) {
4227 glslang::TType glslangElementType(type, 0);
4228 spv::Id elementRType = builder.getContainedTypeId(rType);
4229 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4230 // get the source member
4231 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004232
John Kessenichb3e24e42016-09-11 12:33:43 -06004233 // set up the target storage
4234 builder.clearAccessChain();
4235 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004236 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4237 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004238
John Kessenichb3e24e42016-09-11 12:33:43 -06004239 // store the member
4240 multiTypeStore(glslangElementType, elementRValue);
4241 }
4242 } else {
4243 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004244
John Kessenichb3e24e42016-09-11 12:33:43 -06004245 // loop over structure members
4246 const glslang::TTypeList& members = *type.getStruct();
4247 for (int m = 0; m < (int)members.size(); ++m) {
4248 const glslang::TType& glslangMemberType = *members[m].type;
4249
4250 // get the source member
4251 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4252 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4253
4254 // set up the target storage
4255 builder.clearAccessChain();
4256 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004257 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4258 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004259
4260 // store the member
4261 multiTypeStore(glslangMemberType, memberRValue);
4262 }
John Kessenich4bf71552016-09-02 11:20:21 -06004263 }
4264}
4265
John Kessenichf85e8062015-12-19 13:57:10 -07004266// Decide whether or not this type should be
4267// decorated with offsets and strides, and if so
4268// whether std140 or std430 rules should be applied.
4269glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004270{
John Kessenichf85e8062015-12-19 13:57:10 -07004271 // has to be a block
4272 if (type.getBasicType() != glslang::EbtBlock)
4273 return glslang::ElpNone;
4274
Chao Chen3c366992018-09-19 11:41:59 -07004275 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004276 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004277 type.getQualifier().storage != glslang::EvqBuffer &&
4278 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004279 return glslang::ElpNone;
4280
4281 // return the layout to use
4282 switch (type.getQualifier().layoutPacking) {
4283 case glslang::ElpStd140:
4284 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004285 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004286 return type.getQualifier().layoutPacking;
4287 default:
4288 return glslang::ElpNone;
4289 }
John Kessenich31ed4832015-09-09 17:51:38 -06004290}
4291
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004292// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004293int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4294 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004295{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004296 int size;
John Kessenich49987892015-12-29 17:11:44 -07004297 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004298 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4299 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004300
4301 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004302}
4303
John Kessenich49987892015-12-29 17:11:44 -07004304// 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 -07004305// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004306int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4307 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004308{
John Kessenich49987892015-12-29 17:11:44 -07004309 glslang::TType elementType;
4310 elementType.shallowCopy(matrixType);
4311 elementType.clearArraySizes();
4312
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004313 int size;
John Kessenich49987892015-12-29 17:11:44 -07004314 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004315 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4316 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004317
4318 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004319}
4320
John Kessenich5e4b1242015-08-06 22:53:06 -06004321// Given a member type of a struct, realign the current offset for it, and compute
4322// the next (not yet aligned) offset for the next member, which will get aligned
4323// on the next call.
4324// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4325// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4326// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004327void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4328 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004329{
4330 // this will get a positive value when deemed necessary
4331 nextOffset = -1;
4332
John Kessenich5e4b1242015-08-06 22:53:06 -06004333 // override anything in currentOffset with user-set offset
4334 if (memberType.getQualifier().hasOffset())
4335 currentOffset = memberType.getQualifier().layoutOffset;
4336
4337 // It could be that current linker usage in glslang updated all the layoutOffset,
4338 // in which case the following code does not matter. But, that's not quite right
4339 // once cross-compilation unit GLSL validation is done, as the original user
4340 // settings are needed in layoutOffset, and then the following will come into play.
4341
John Kessenichf85e8062015-12-19 13:57:10 -07004342 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004343 if (! memberType.getQualifier().hasOffset())
4344 currentOffset = -1;
4345
4346 return;
4347 }
4348
John Kessenichf85e8062015-12-19 13:57:10 -07004349 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004350 if (currentOffset < 0)
4351 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004352
John Kessenich5e4b1242015-08-06 22:53:06 -06004353 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4354 // but possibly not yet correctly aligned.
4355
4356 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004357 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004358 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4359 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004360
4361 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004362 // TODO: make this consistent in early phases of code:
4363 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4364 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4365 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004366 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004367 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004368 int dummySize;
4369 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4370 if (componentAlignment <= 4)
4371 memberAlignment = componentAlignment;
4372 }
4373
4374 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004375 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004376
4377 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004378 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4379 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004380 glslang::RoundToPow2(currentOffset, 16);
4381
John Kessenich5e4b1242015-08-06 22:53:06 -06004382 nextOffset = currentOffset + memberSize;
4383}
4384
David Netoa901ffe2016-06-08 14:11:40 +01004385void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004386{
David Netoa901ffe2016-06-08 14:11:40 +01004387 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4388 switch (glslangBuiltIn)
4389 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004390 case glslang::EbvPointSize:
4391#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004392 case glslang::EbvClipDistance:
4393 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004394 case glslang::EbvViewportMaskNV:
4395 case glslang::EbvSecondaryPositionNV:
4396 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004397 case glslang::EbvPositionPerViewNV:
4398 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004399 case glslang::EbvTaskCountNV:
4400 case glslang::EbvPrimitiveCountNV:
4401 case glslang::EbvPrimitiveIndicesNV:
4402 case glslang::EbvClipDistancePerViewNV:
4403 case glslang::EbvCullDistancePerViewNV:
4404 case glslang::EbvLayerPerViewNV:
4405 case glslang::EbvMeshViewCountNV:
4406 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004407#endif
David Netoa901ffe2016-06-08 14:11:40 +01004408 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4409 // Alternately, we could just call this for any glslang built-in, since the
4410 // capability already guards against duplicates.
4411 TranslateBuiltInDecoration(glslangBuiltIn, false);
4412 break;
4413 default:
4414 // Capabilities were already generated when the struct was declared.
4415 break;
4416 }
John Kessenichebb50532016-05-16 19:22:05 -06004417}
4418
John Kessenich6fccb3c2016-09-19 16:01:41 -06004419bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004420{
John Kessenicheee9d532016-09-19 18:09:30 -06004421 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004422}
4423
John Kessenichd41993d2017-09-10 15:21:05 -06004424// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004425// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4426// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004427bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004428{
John Kessenich6a14f782017-12-04 02:48:10 -07004429 assert(qualifier == glslang::EvqIn ||
4430 qualifier == glslang::EvqOut ||
4431 qualifier == glslang::EvqInOut ||
rdbd8edfd82020-06-02 08:30:07 +02004432 qualifier == glslang::EvqUniform ||
John Kessenich6a14f782017-12-04 02:48:10 -07004433 qualifier == glslang::EvqConstReadOnly);
rdbd8edfd82020-06-02 08:30:07 +02004434 return qualifier != glslang::EvqConstReadOnly &&
4435 qualifier != glslang::EvqUniform;
John Kessenichd41993d2017-09-10 15:21:05 -06004436}
4437
4438// Is parameter pass-by-original?
4439bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4440 bool implicitThisParam)
4441{
4442 if (implicitThisParam) // implicit this
4443 return true;
4444 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004445 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004446 return paramType.containsOpaque() || // sampler, etc.
4447 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4448}
4449
John Kessenich140f3df2015-06-26 16:58:36 -06004450// Make all the functions, skeletally, without actually visiting their bodies.
4451void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4452{
John Kessenich8985fc92020-03-03 10:25:07 -07004453 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4454 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004455 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4456 if (paramPrecision != spv::NoPrecision)
4457 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004458 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004459 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004460 // Original and non-writable params pass the pointer directly and
4461 // use restrict/aliased, others are stored to a pointer in Function
4462 // memory and use RestrictPointer/AliasedPointer.
4463 if (originalParam(type.getQualifier().storage, type, false) ||
4464 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004465 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4466 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004467 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004468 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4469 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004470 }
4471 }
John Kessenichfad62972017-07-18 02:35:46 -06004472 };
4473
John Kessenich140f3df2015-06-26 16:58:36 -06004474 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4475 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004476 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004477 continue;
4478
4479 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004480 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004481 //
qining25262b32016-05-06 17:25:16 -04004482 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004483 // function. What it is an address of varies:
4484 //
John Kessenich4bf71552016-09-02 11:20:21 -06004485 // - "in" parameters not marked as "const" can be written to without modifying the calling
4486 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004487 //
4488 // - "const in" parameters can just be the r-value, as no writes need occur.
4489 //
John Kessenich4bf71552016-09-02 11:20:21 -06004490 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4491 // 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 -06004492
4493 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004494 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004495 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4496
John Kessenich155d3512019-08-08 23:29:20 -06004497#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004498 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4499 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004500#else
4501 bool implicitThis = false;
4502#endif
John Kessenich37789792017-03-21 23:56:40 -06004503
John Kessenichfad62972017-07-18 02:35:46 -06004504 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004505 for (int p = 0; p < (int)parameters.size(); ++p) {
4506 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4507 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004508 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004509 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004510 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004511 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4512 else
John Kessenich4bf71552016-09-02 11:20:21 -06004513 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004514 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004515 paramTypes.push_back(typeId);
4516 }
4517
4518 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004519 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4520 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004521 glslFunction->getName().c_str(), paramTypes,
4522 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004523 if (implicitThis)
4524 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004525
4526 // Track function to emit/call later
4527 functionMap[glslFunction->getName().c_str()] = function;
4528
4529 // Set the parameter id's
4530 for (int p = 0; p < (int)parameters.size(); ++p) {
4531 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4532 // give a name too
4533 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004534
4535 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004536 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004537 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004538 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004539 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004540 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004541 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004542 }
4543 }
4544}
4545
4546// Process all the initializers, while skipping the functions and link objects
4547void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4548{
4549 builder.setBuildPoint(shaderEntry->getLastBlock());
4550 for (int i = 0; i < (int)initializers.size(); ++i) {
4551 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004552 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4553 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004554
4555 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004556 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004557 initializer->traverse(this);
4558 }
4559 }
4560}
4561
4562// Process all the functions, while skipping initializers.
4563void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4564{
4565 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4566 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004567 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004568 node->traverse(this);
4569 }
4570}
4571
4572void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4573{
qining25262b32016-05-06 17:25:16 -04004574 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004575 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004576 currentFunction = functionMap[node->getName().c_str()];
4577 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004578 builder.setBuildPoint(functionBlock);
4579}
4580
John Kessenich8985fc92020-03-03 10:25:07 -07004581void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4582 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004583{
Rex Xufc618912015-09-09 16:42:49 +08004584 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004585
4586 glslang::TSampler sampler = {};
4587 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004588#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004589 bool f16ShadowCompare = false;
4590#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004591 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004592 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4593 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004594#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004595 f16ShadowCompare = sampler.shadow &&
4596 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004597#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004598 }
4599
John Kessenich140f3df2015-06-26 16:58:36 -06004600 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4601 builder.clearAccessChain();
4602 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004603
John Kessenicha28f7a72019-08-06 07:00:58 -06004604#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004605 // Special case l-value operands
4606 bool lvalue = false;
4607 switch (node.getOp()) {
4608 case glslang::EOpImageAtomicAdd:
4609 case glslang::EOpImageAtomicMin:
4610 case glslang::EOpImageAtomicMax:
4611 case glslang::EOpImageAtomicAnd:
4612 case glslang::EOpImageAtomicOr:
4613 case glslang::EOpImageAtomicXor:
4614 case glslang::EOpImageAtomicExchange:
4615 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004616 case glslang::EOpImageAtomicLoad:
4617 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004618 if (i == 0)
4619 lvalue = true;
4620 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004621 case glslang::EOpSparseImageLoad:
4622 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4623 lvalue = true;
4624 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004625 case glslang::EOpSparseTexture:
4626 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4627 lvalue = true;
4628 break;
4629 case glslang::EOpSparseTextureClamp:
4630 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4631 lvalue = true;
4632 break;
4633 case glslang::EOpSparseTextureLod:
4634 case glslang::EOpSparseTextureOffset:
4635 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4636 lvalue = true;
4637 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004638 case glslang::EOpSparseTextureFetch:
4639 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4640 lvalue = true;
4641 break;
4642 case glslang::EOpSparseTextureFetchOffset:
4643 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4644 lvalue = true;
4645 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004646 case glslang::EOpSparseTextureLodOffset:
4647 case glslang::EOpSparseTextureGrad:
4648 case glslang::EOpSparseTextureOffsetClamp:
4649 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4650 lvalue = true;
4651 break;
4652 case glslang::EOpSparseTextureGradOffset:
4653 case glslang::EOpSparseTextureGradClamp:
4654 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4655 lvalue = true;
4656 break;
4657 case glslang::EOpSparseTextureGradOffsetClamp:
4658 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4659 lvalue = true;
4660 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004661 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004662 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4663 lvalue = true;
4664 break;
4665 case glslang::EOpSparseTextureGatherOffset:
4666 case glslang::EOpSparseTextureGatherOffsets:
4667 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4668 lvalue = true;
4669 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004670 case glslang::EOpSparseTextureGatherLod:
4671 if (i == 3)
4672 lvalue = true;
4673 break;
4674 case glslang::EOpSparseTextureGatherLodOffset:
4675 case glslang::EOpSparseTextureGatherLodOffsets:
4676 if (i == 4)
4677 lvalue = true;
4678 break;
Rex Xu129799a2017-07-05 17:23:28 +08004679 case glslang::EOpSparseImageLoadLod:
4680 if (i == 3)
4681 lvalue = true;
4682 break;
Chao Chen3a137962018-09-19 11:41:27 -07004683 case glslang::EOpImageSampleFootprintNV:
4684 if (i == 4)
4685 lvalue = true;
4686 break;
4687 case glslang::EOpImageSampleFootprintClampNV:
4688 case glslang::EOpImageSampleFootprintLodNV:
4689 if (i == 5)
4690 lvalue = true;
4691 break;
4692 case glslang::EOpImageSampleFootprintGradNV:
4693 if (i == 6)
4694 lvalue = true;
4695 break;
4696 case glslang::EOpImageSampleFootprintGradClampNV:
4697 if (i == 7)
4698 lvalue = true;
4699 break;
Rex Xufc618912015-09-09 16:42:49 +08004700 default:
4701 break;
4702 }
4703
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004704 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004705 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004706 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4707 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4708 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004709#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004710 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004711 }
4712}
4713
John Kessenichfc51d282015-08-19 13:34:18 -06004714void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004715{
John Kessenichfc51d282015-08-19 13:34:18 -06004716 builder.clearAccessChain();
4717 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004718 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004719}
John Kessenich140f3df2015-06-26 16:58:36 -06004720
John Kessenichfc51d282015-08-19 13:34:18 -06004721spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4722{
John Kesseniche485c7a2017-05-31 18:50:53 -06004723 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004724 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004725
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004726 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004727
John Kessenichfc51d282015-08-19 13:34:18 -06004728 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004729
John Kessenichf43c7392019-03-31 10:51:57 -06004730 const glslang::TType &imageType = node->getAsAggregate()
4731 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4732 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004733 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004734#ifdef GLSLANG_WEB
4735 const bool f16ShadowCompare = false;
4736#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004737 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004738 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4739 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004740#endif
4741
John Kessenichf43c7392019-03-31 10:51:57 -06004742 const auto signExtensionMask = [&]() {
4743 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4744 if (sampler.type == glslang::EbtUint)
4745 return spv::ImageOperandsZeroExtendMask;
4746 else if (sampler.type == glslang::EbtInt)
4747 return spv::ImageOperandsSignExtendMask;
4748 }
4749 return spv::ImageOperandsMaskNone;
4750 };
4751
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004752 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4753
John Kessenichfc51d282015-08-19 13:34:18 -06004754 std::vector<spv::Id> arguments;
4755 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004756 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004757 else
4758 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenich12c155f2020-06-30 07:52:05 -06004759 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
John Kessenichfc51d282015-08-19 13:34:18 -06004760
4761 spv::Builder::TextureParameters params = { };
4762 params.sampler = arguments[0];
4763
Rex Xu04db3f52015-09-16 11:44:02 +08004764 glslang::TCrackedTextureOp cracked;
4765 node->crackTexture(sampler, cracked);
4766
amhagan05506bb2017-06-13 16:53:02 -04004767 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004768
John Kessenichfc51d282015-08-19 13:34:18 -06004769 // Check for queries
4770 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004771 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4772 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004773 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004774
John Kessenichfc51d282015-08-19 13:34:18 -06004775 switch (node->getOp()) {
4776 case glslang::EOpImageQuerySize:
4777 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004778 if (arguments.size() > 1) {
4779 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004780 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004781 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004782 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004783#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004784 case glslang::EOpImageQuerySamples:
4785 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004786 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004787 case glslang::EOpTextureQueryLod:
4788 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004789 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004790 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004791 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004792 case glslang::EOpSparseTexelsResident:
4793 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004794#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004795 default:
4796 assert(0);
4797 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004798 }
John Kessenich140f3df2015-06-26 16:58:36 -06004799 }
4800
LoopDawg4425f242018-02-18 11:40:01 -07004801 int components = node->getType().getVectorSize();
4802
4803 if (node->getOp() == glslang::EOpTextureFetch) {
4804 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4805 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4806 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4807 // here around e.g. which ones return scalars or other types.
4808 components = 4;
4809 }
4810
4811 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4812
4813 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4814
Rex Xufc618912015-09-09 16:42:49 +08004815 // Check for image functions other than queries
4816 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004817 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004818 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004819 spv::IdImmediate image = { true, *(opIt++) };
4820 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004821
4822 // Handle subpass operations
4823 // TODO: GLSL should change to have the "MS" only on the type rather than the
4824 // built-in function.
4825 if (cracked.subpass) {
4826 // add on the (0,0) coordinate
4827 spv::Id zero = builder.makeIntConstant(0);
4828 std::vector<spv::Id> comps;
4829 comps.push_back(zero);
4830 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004831 spv::IdImmediate coord = { true,
4832 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4833 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004834 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4835 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004836 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004837 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4838 }
4839 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004840 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004841 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004842 spv::IdImmediate imageOperand = { true, *(opIt++) };
4843 operands.push_back(imageOperand);
4844 }
John Kessenich6c292d32016-02-15 20:58:50 -07004845 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004846 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4847 builder.setPrecision(result, precision);
4848 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004849 }
4850
John Kessenich149afc32018-08-14 13:31:43 -06004851 spv::IdImmediate coord = { true, *(opIt++) };
4852 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004853 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004854 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004855 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004856 mask = mask | spv::ImageOperandsSampleMask;
4857 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004858 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004859 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4860 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004861 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004862 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004863 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4864 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004865 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004866 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004867 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4868 operands.push_back(imageOperands);
4869 }
4870 if (mask & spv::ImageOperandsSampleMask) {
4871 spv::IdImmediate imageOperand = { true, *opIt++ };
4872 operands.push_back(imageOperand);
4873 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004874 if (mask & spv::ImageOperandsLodMask) {
4875 spv::IdImmediate imageOperand = { true, *opIt++ };
4876 operands.push_back(imageOperand);
4877 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004878 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004879 spv::IdImmediate imageOperand = { true,
4880 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004881 operands.push_back(imageOperand);
4882 }
4883
John Kessenich149afc32018-08-14 13:31:43 -06004884 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004885 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004886
John Kessenich149afc32018-08-14 13:31:43 -06004887 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004888 builder.setPrecision(result[0], precision);
4889
4890 // If needed, add a conversion constructor to the proper size.
4891 if (components != node->getType().getVectorSize())
4892 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4893
4894 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004895 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004896
Jeff Bolz36831c92018-09-05 10:11:41 -05004897 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004898 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004899 spv::IdImmediate texel = { true, *(opIt + 1) };
4900 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004901 } else {
4902 spv::IdImmediate texel = { true, *opIt };
4903 operands.push_back(texel);
4904 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004905
4906 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004907 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004908 mask = mask | spv::ImageOperandsSampleMask;
4909 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004910 if (cracked.lod) {
4911 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4912 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4913 mask = mask | spv::ImageOperandsLodMask;
4914 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004915 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4916 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004917 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004918 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004919 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4920 operands.push_back(imageOperands);
4921 }
4922 if (mask & spv::ImageOperandsSampleMask) {
4923 spv::IdImmediate imageOperand = { true, *opIt++ };
4924 operands.push_back(imageOperand);
4925 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004926 if (mask & spv::ImageOperandsLodMask) {
4927 spv::IdImmediate imageOperand = { true, *opIt++ };
4928 operands.push_back(imageOperand);
4929 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004930 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004931 spv::IdImmediate imageOperand = { true,
4932 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004933 operands.push_back(imageOperand);
4934 }
4935
John Kessenich56bab042015-09-16 10:54:31 -06004936 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004937 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004938 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004939 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004940 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4941 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004942 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004943 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004944 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4945
Jeff Bolz36831c92018-09-05 10:11:41 -05004946 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004947 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004948 mask = mask | spv::ImageOperandsSampleMask;
4949 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004950 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004951 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4952 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4953
Jeff Bolz36831c92018-09-05 10:11:41 -05004954 mask = mask | spv::ImageOperandsLodMask;
4955 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004956 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4957 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004958 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004959 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004960 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004961 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004962 }
4963 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004964 spv::IdImmediate imageOperand = { true, *opIt++ };
4965 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004966 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004967 if (mask & spv::ImageOperandsLodMask) {
4968 spv::IdImmediate imageOperand = { true, *opIt++ };
4969 operands.push_back(imageOperand);
4970 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004971 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07004972 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
4973 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004974 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004975 }
4976
4977 // Create the return type that was a special structure
4978 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004979 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004980 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4981 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4982
4983 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4984
4985 // Decode the return type
4986 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4987 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004988 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004989 // Process image atomic operations
4990
4991 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4992 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004993 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004994 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004995 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004996
Jeff Bolz36831c92018-09-05 10:11:41 -05004997 spv::Id resultTypeId;
4998 // imageAtomicStore has a void return type so base the pointer type on
4999 // the type of the value operand.
5000 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08005001 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05005002 } else {
5003 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
5004 }
John Kessenich56bab042015-09-16 10:54:31 -06005005 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Jeff Bolz39ffdaf2020-03-09 10:48:12 -05005006 if (imageType.getQualifier().nonUniform) {
5007 builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
5008 }
Rex Xufc618912015-09-09 16:42:49 +08005009
5010 std::vector<spv::Id> operands;
5011 operands.push_back(pointer);
5012 for (; opIt != arguments.end(); ++opIt)
5013 operands.push_back(*opIt);
5014
John Kessenich8985fc92020-03-03 10:25:07 -07005015 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
5016 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08005017 }
5018 }
5019
John Kessenicha28f7a72019-08-06 07:00:58 -06005020#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04005021 // Check for fragment mask functions other than queries
5022 if (cracked.fragMask) {
5023 assert(sampler.ms);
5024
5025 auto opIt = arguments.begin();
5026 std::vector<spv::Id> operands;
5027
5028 // Extract the image if necessary
5029 if (builder.isSampledImage(params.sampler))
5030 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
5031
5032 operands.push_back(params.sampler);
5033 ++opIt;
5034
5035 if (sampler.isSubpass()) {
5036 // add on the (0,0) coordinate
5037 spv::Id zero = builder.makeIntConstant(0);
5038 std::vector<spv::Id> comps;
5039 comps.push_back(zero);
5040 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07005041 operands.push_back(builder.makeCompositeConstant(
5042 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04005043 }
5044
5045 for (; opIt != arguments.end(); ++opIt)
5046 operands.push_back(*opIt);
5047
5048 spv::Op fragMaskOp = spv::OpNop;
5049 if (node->getOp() == glslang::EOpFragmentMaskFetch)
5050 fragMaskOp = spv::OpFragmentMaskFetchAMD;
5051 else if (node->getOp() == glslang::EOpFragmentFetch)
5052 fragMaskOp = spv::OpFragmentFetchAMD;
5053
5054 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
5055 builder.addCapability(spv::CapabilityFragmentMaskAMD);
5056 return builder.createOp(fragMaskOp, resultType(), operands);
5057 }
5058#endif
5059
Rex Xufc618912015-09-09 16:42:49 +08005060 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08005061 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07005062 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005063 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08005064
John Kessenichfc51d282015-08-19 13:34:18 -06005065 // check for bias argument
5066 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08005067 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005068 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08005069 if (cracked.gather)
5070 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08005071
5072 if (f16ShadowCompare)
5073 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005074 if (cracked.offset)
5075 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08005076 else if (cracked.offsets)
5077 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005078 if (cracked.grad)
5079 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08005080 if (cracked.lodClamp)
5081 ++nonBiasArgCount;
5082 if (sparse)
5083 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07005084 if (imageFootprint)
5085 //Following three extra arguments
5086 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5087 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06005088 if ((int)arguments.size() > nonBiasArgCount)
5089 bias = true;
5090 }
5091
John Kessenicha5c33d62016-06-02 23:45:21 -06005092 // See if the sampler param should really be just the SPV image part
5093 if (cracked.fetch) {
5094 // a fetch needs to have the image extracted first
5095 if (builder.isSampledImage(params.sampler))
5096 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
5097 }
5098
John Kessenicha28f7a72019-08-06 07:00:58 -06005099#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08005100 if (cracked.gather) {
5101 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
5102 if (bias || cracked.lod ||
5103 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
5104 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08005105 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08005106 }
5107 }
5108#endif
5109
John Kessenichfc51d282015-08-19 13:34:18 -06005110 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07005111
John Kessenichfc51d282015-08-19 13:34:18 -06005112 params.coords = arguments[1];
5113 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07005114 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07005115
5116 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08005117 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005118 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08005119 ++extraArgs;
5120 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07005121 params.Dref = arguments[2];
5122 ++extraArgs;
5123 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06005124 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06005125 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06005126 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06005127 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06005128 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005129 dRefComp = builder.getNumComponents(params.coords) - 1;
5130 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07005131 params.Dref = builder.createCompositeExtract(params.coords,
5132 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06005133 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005134
5135 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06005136 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005137 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06005138 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06005139 } else if (glslangIntermediate->getStage() != EShLangFragment &&
5140 !(glslangIntermediate->getStage() == EShLangCompute &&
5141 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07005142 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
5143 noImplicitLod = true;
5144 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005145
5146 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005147 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005148 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08005149 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005150 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005151
5152 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06005153 if (cracked.grad) {
5154 params.gradX = arguments[2 + extraArgs];
5155 params.gradY = arguments[3 + extraArgs];
5156 extraArgs += 2;
5157 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005158
5159 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07005160 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06005161 params.offset = arguments[2 + extraArgs];
5162 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005163 } else if (cracked.offsets) {
5164 params.offsets = arguments[2 + extraArgs];
5165 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005166 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005167
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005168#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005169 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005170 if (cracked.lodClamp) {
5171 params.lodClamp = arguments[2 + extraArgs];
5172 ++extraArgs;
5173 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005174 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005175 if (sparse) {
5176 params.texelOut = arguments[2 + extraArgs];
5177 ++extraArgs;
5178 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005179 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005180 if (cracked.gather && ! sampler.shadow) {
5181 // default component is 0, if missing, otherwise an argument
5182 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005183 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005184 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005185 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005186 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005187 }
Chao Chen3a137962018-09-19 11:41:27 -07005188 spv::Id resultStruct = spv::NoResult;
5189 if (imageFootprint) {
5190 //Following three extra arguments
5191 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5192 params.granularity = arguments[2 + extraArgs];
5193 params.coarse = arguments[3 + extraArgs];
5194 resultStruct = arguments[4 + extraArgs];
5195 extraArgs += 3;
5196 }
5197#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005198 // bias
5199 if (bias) {
5200 params.bias = arguments[2 + extraArgs];
5201 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005202 }
John Kessenichfc51d282015-08-19 13:34:18 -06005203
John Kessenicha28f7a72019-08-06 07:00:58 -06005204#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005205 if (imageFootprint) {
5206 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5207 builder.addCapability(spv::CapabilityImageFootprintNV);
5208
5209
5210 //resultStructType(OpenGL type) contains 5 elements:
5211 //struct gl_TextureFootprint2DNV {
5212 // uvec2 anchor;
5213 // uvec2 offset;
5214 // uvec2 mask;
5215 // uint lod;
5216 // uint granularity;
5217 //};
5218 //or
5219 //struct gl_TextureFootprint3DNV {
5220 // uvec3 anchor;
5221 // uvec3 offset;
5222 // uvec2 mask;
5223 // uint lod;
5224 // uint granularity;
5225 //};
5226 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5227 assert(builder.isStructType(resultStructType));
5228
5229 //resType (SPIR-V type) contains 6 elements:
5230 //Member 0 must be a Boolean type scalar(LOD),
5231 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5232 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5233 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5234 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5235 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5236 std::vector<spv::Id> members;
5237 members.push_back(resultType());
5238 for (int i = 0; i < 5; i++) {
5239 members.push_back(builder.getContainedTypeId(resultStructType, i));
5240 }
5241 spv::Id resType = builder.makeStructType(members, "ResType");
5242
5243 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005244 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5245 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005246
5247 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5248 for (int i = 0; i < 5; i++) {
5249 builder.clearAccessChain();
5250 builder.setAccessChainLValue(resultStruct);
5251
5252 //Accessing to a struct we created, no coherent flag is set
5253 spv::Builder::AccessChain::CoherentFlags flags;
5254 flags.clear();
5255
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005256 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005257 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
5258 i+1));
Chao Chen3a137962018-09-19 11:41:27 -07005259 }
5260 return builder.createCompositeExtract(res, resultType(), 0);
5261 }
5262#endif
5263
John Kessenich65336482016-06-16 14:06:26 -06005264 // projective component (might not to move)
5265 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5266 // are divided by the last component of P."
5267 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5268 // unused components will appear after all used components."
5269 if (cracked.proj) {
5270 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5271 int projTargetComp;
5272 switch (sampler.dim) {
5273 case glslang::Esd1D: projTargetComp = 1; break;
5274 case glslang::Esd2D: projTargetComp = 2; break;
5275 case glslang::EsdRect: projTargetComp = 2; break;
5276 default: projTargetComp = projSourceComp; break;
5277 }
5278 // copy the projective coordinate if we have to
5279 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005280 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005281 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005282 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005283 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005284 }
5285 }
5286
John Kessenichf8d1d742019-10-21 06:55:11 -06005287#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005288 // nonprivate
5289 if (imageType.getQualifier().nonprivate) {
5290 params.nonprivate = true;
5291 }
5292
5293 // volatile
5294 if (imageType.getQualifier().volatil) {
5295 params.volatil = true;
5296 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005297#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005298
St0fFa1184dd2018-04-09 21:08:14 +02005299 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005300 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5301 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005302 );
LoopDawg4425f242018-02-18 11:40:01 -07005303
5304 if (components != node->getType().getVectorSize())
5305 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5306
5307 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005308}
5309
5310spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5311{
5312 // Grab the function's pointer from the previously created function
5313 spv::Function* function = functionMap[node->getName().c_str()];
5314 if (! function)
5315 return 0;
5316
5317 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5318 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5319
5320 // See comments in makeFunctions() for details about the semantics for parameter passing.
5321 //
5322 // These imply we need a four step process:
5323 // 1. Evaluate the arguments
5324 // 2. Allocate and make copies of in, out, and inout arguments
5325 // 3. Make the call
5326 // 4. Copy back the results
5327
John Kessenichd3ed90b2018-05-04 11:43:03 -06005328 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005329 std::vector<spv::Builder::AccessChain> lValues;
5330 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005331 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005332 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005333 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005334 // build l-value
5335 builder.clearAccessChain();
5336 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005337 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005338 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005339 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005340 // save l-value
5341 lValues.push_back(builder.getAccessChain());
5342 } else {
5343 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005344 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005345 }
5346 }
5347
5348 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5349 // copy the original into that space.
5350 //
5351 // Also, build up the list of actual arguments to pass in for the call
5352 int lValueCount = 0;
5353 int rValueCount = 0;
5354 std::vector<spv::Id> spvArgs;
5355 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5356 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005357 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005358 builder.setAccessChain(lValues[lValueCount]);
5359 arg = builder.accessChainGetLValue();
5360 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005361 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005362 // need space to hold the copy
John Kessenich435dd802020-06-30 01:27:08 -06005363 arg = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction,
John Kessenich8985fc92020-03-03 10:25:07 -07005364 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005365 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5366 // need to copy the input into output space
5367 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005368 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005369 builder.clearAccessChain();
5370 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005371 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005372 }
5373 ++lValueCount;
5374 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005375 // process r-value, which involves a copy for a type mismatch
John Kessenich4df10332020-06-26 08:37:06 -06005376 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a]) ||
John Kessenich435dd802020-06-30 01:27:08 -06005377 TranslatePrecisionDecoration(*argTypes[a]) != function->getParamPrecision(a))
John Kessenich4df10332020-06-26 08:37:06 -06005378 {
John Kessenich435dd802020-06-30 01:27:08 -06005379 spv::Id argCopy = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction, function->getParamType(a), "arg");
John Kessenichd3ed90b2018-05-04 11:43:03 -06005380 builder.clearAccessChain();
5381 builder.setAccessChainLValue(argCopy);
5382 multiTypeStore(*argTypes[a], rValues[rValueCount]);
John Kessenich435dd802020-06-30 01:27:08 -06005383 arg = builder.createLoad(argCopy, function->getParamPrecision(a));
John Kessenichd3ed90b2018-05-04 11:43:03 -06005384 } else
5385 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005386 ++rValueCount;
5387 }
5388 spvArgs.push_back(arg);
5389 }
5390
5391 // 3. Make the call.
5392 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005393 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005394
5395 // 4. Copy back out an "out" arguments.
5396 lValueCount = 0;
5397 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005398 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005399 ++lValueCount;
5400 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005401 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
John Kessenich435dd802020-06-30 01:27:08 -06005402 spv::Id copy = builder.createLoad(spvArgs[a], spv::NoPrecision);
John Kessenich140f3df2015-06-26 16:58:36 -06005403 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005404 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005405 }
5406 ++lValueCount;
5407 }
5408 }
5409
5410 return result;
5411}
5412
5413// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005414spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005415 spv::Id typeId, spv::Id left, spv::Id right,
5416 glslang::TBasicType typeProxy, bool reduceComparison)
5417{
John Kessenich66011cb2018-03-06 16:12:04 -07005418 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5419 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005420 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005421
5422 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005423 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005424 bool comparison = false;
5425
5426 switch (op) {
5427 case glslang::EOpAdd:
5428 case glslang::EOpAddAssign:
5429 if (isFloat)
5430 binOp = spv::OpFAdd;
5431 else
5432 binOp = spv::OpIAdd;
5433 break;
5434 case glslang::EOpSub:
5435 case glslang::EOpSubAssign:
5436 if (isFloat)
5437 binOp = spv::OpFSub;
5438 else
5439 binOp = spv::OpISub;
5440 break;
5441 case glslang::EOpMul:
5442 case glslang::EOpMulAssign:
5443 if (isFloat)
5444 binOp = spv::OpFMul;
5445 else
5446 binOp = spv::OpIMul;
5447 break;
5448 case glslang::EOpVectorTimesScalar:
5449 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005450 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005451 if (builder.isVector(right))
5452 std::swap(left, right);
5453 assert(builder.isScalar(right));
5454 needMatchingVectors = false;
5455 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005456 } else if (isFloat)
5457 binOp = spv::OpFMul;
5458 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005459 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005460 break;
5461 case glslang::EOpVectorTimesMatrix:
5462 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005463 binOp = spv::OpVectorTimesMatrix;
5464 break;
5465 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005466 binOp = spv::OpMatrixTimesVector;
5467 break;
5468 case glslang::EOpMatrixTimesScalar:
5469 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005470 binOp = spv::OpMatrixTimesScalar;
5471 break;
5472 case glslang::EOpMatrixTimesMatrix:
5473 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005474 binOp = spv::OpMatrixTimesMatrix;
5475 break;
5476 case glslang::EOpOuterProduct:
5477 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005478 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005479 break;
5480
5481 case glslang::EOpDiv:
5482 case glslang::EOpDivAssign:
5483 if (isFloat)
5484 binOp = spv::OpFDiv;
5485 else if (isUnsigned)
5486 binOp = spv::OpUDiv;
5487 else
5488 binOp = spv::OpSDiv;
5489 break;
5490 case glslang::EOpMod:
5491 case glslang::EOpModAssign:
5492 if (isFloat)
5493 binOp = spv::OpFMod;
5494 else if (isUnsigned)
5495 binOp = spv::OpUMod;
5496 else
5497 binOp = spv::OpSMod;
5498 break;
5499 case glslang::EOpRightShift:
5500 case glslang::EOpRightShiftAssign:
5501 if (isUnsigned)
5502 binOp = spv::OpShiftRightLogical;
5503 else
5504 binOp = spv::OpShiftRightArithmetic;
5505 break;
5506 case glslang::EOpLeftShift:
5507 case glslang::EOpLeftShiftAssign:
5508 binOp = spv::OpShiftLeftLogical;
5509 break;
5510 case glslang::EOpAnd:
5511 case glslang::EOpAndAssign:
5512 binOp = spv::OpBitwiseAnd;
5513 break;
5514 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005515 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005516 binOp = spv::OpLogicalAnd;
5517 break;
5518 case glslang::EOpInclusiveOr:
5519 case glslang::EOpInclusiveOrAssign:
5520 binOp = spv::OpBitwiseOr;
5521 break;
5522 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005523 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005524 binOp = spv::OpLogicalOr;
5525 break;
5526 case glslang::EOpExclusiveOr:
5527 case glslang::EOpExclusiveOrAssign:
5528 binOp = spv::OpBitwiseXor;
5529 break;
5530 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005531 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005532 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005533 break;
5534
Ian Romanickb3bd4022019-01-21 08:57:25 -08005535 case glslang::EOpAbsDifference:
5536 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5537 break;
5538
5539 case glslang::EOpAddSaturate:
5540 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5541 break;
5542
5543 case glslang::EOpSubSaturate:
5544 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5545 break;
5546
5547 case glslang::EOpAverage:
5548 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5549 break;
5550
5551 case glslang::EOpAverageRounded:
5552 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5553 break;
5554
5555 case glslang::EOpMul32x16:
5556 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5557 break;
5558
John Kessenich140f3df2015-06-26 16:58:36 -06005559 case glslang::EOpLessThan:
5560 case glslang::EOpGreaterThan:
5561 case glslang::EOpLessThanEqual:
5562 case glslang::EOpGreaterThanEqual:
5563 case glslang::EOpEqual:
5564 case glslang::EOpNotEqual:
5565 case glslang::EOpVectorEqual:
5566 case glslang::EOpVectorNotEqual:
5567 comparison = true;
5568 break;
5569 default:
5570 break;
5571 }
5572
John Kessenich7c1aa102015-10-15 13:29:11 -06005573 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005574 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005575 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005576 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5577 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005578 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005579
5580 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005581 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005582 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005583
qining25262b32016-05-06 17:25:16 -04005584 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005585 decorations.addNoContraction(builder, result);
5586 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005587 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005588 }
5589
5590 if (! comparison)
5591 return 0;
5592
John Kessenich7c1aa102015-10-15 13:29:11 -06005593 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005594
John Kessenich4583b612016-08-07 19:14:22 -06005595 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005596 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5597 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005598 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005599 return result;
5600 }
John Kessenich140f3df2015-06-26 16:58:36 -06005601
5602 switch (op) {
5603 case glslang::EOpLessThan:
5604 if (isFloat)
5605 binOp = spv::OpFOrdLessThan;
5606 else if (isUnsigned)
5607 binOp = spv::OpULessThan;
5608 else
5609 binOp = spv::OpSLessThan;
5610 break;
5611 case glslang::EOpGreaterThan:
5612 if (isFloat)
5613 binOp = spv::OpFOrdGreaterThan;
5614 else if (isUnsigned)
5615 binOp = spv::OpUGreaterThan;
5616 else
5617 binOp = spv::OpSGreaterThan;
5618 break;
5619 case glslang::EOpLessThanEqual:
5620 if (isFloat)
5621 binOp = spv::OpFOrdLessThanEqual;
5622 else if (isUnsigned)
5623 binOp = spv::OpULessThanEqual;
5624 else
5625 binOp = spv::OpSLessThanEqual;
5626 break;
5627 case glslang::EOpGreaterThanEqual:
5628 if (isFloat)
5629 binOp = spv::OpFOrdGreaterThanEqual;
5630 else if (isUnsigned)
5631 binOp = spv::OpUGreaterThanEqual;
5632 else
5633 binOp = spv::OpSGreaterThanEqual;
5634 break;
5635 case glslang::EOpEqual:
5636 case glslang::EOpVectorEqual:
5637 if (isFloat)
5638 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005639 else if (isBool)
5640 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005641 else
5642 binOp = spv::OpIEqual;
5643 break;
5644 case glslang::EOpNotEqual:
5645 case glslang::EOpVectorNotEqual:
5646 if (isFloat)
Graeme Leese65ce5662020-06-05 13:32:51 +01005647 binOp = spv::OpFUnordNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005648 else if (isBool)
5649 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005650 else
5651 binOp = spv::OpINotEqual;
5652 break;
5653 default:
5654 break;
5655 }
5656
qining25262b32016-05-06 17:25:16 -04005657 if (binOp != spv::OpNop) {
5658 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005659 decorations.addNoContraction(builder, result);
5660 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005661 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005662 }
John Kessenich140f3df2015-06-26 16:58:36 -06005663
5664 return 0;
5665}
5666
John Kessenich04bb8a02015-12-12 12:28:14 -07005667//
5668// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5669// These can be any of:
5670//
5671// matrix * scalar
5672// scalar * matrix
5673// matrix * matrix linear algebraic
5674// matrix * vector
5675// vector * matrix
5676// matrix * matrix componentwise
5677// matrix op matrix op in {+, -, /}
5678// matrix op scalar op in {+, -, /}
5679// scalar op matrix op in {+, -, /}
5680//
John Kessenichead86222018-03-28 18:01:20 -06005681spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5682 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005683{
5684 bool firstClass = true;
5685
5686 // First, handle first-class matrix operations (* and matrix/scalar)
5687 switch (op) {
5688 case spv::OpFDiv:
5689 if (builder.isMatrix(left) && builder.isScalar(right)) {
5690 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005691 spv::Id resultType = builder.getTypeId(right);
5692 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005693 op = spv::OpMatrixTimesScalar;
5694 } else
5695 firstClass = false;
5696 break;
5697 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005698 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005699 std::swap(left, right);
5700 assert(builder.isScalar(right));
5701 break;
5702 case spv::OpVectorTimesMatrix:
5703 assert(builder.isVector(left));
5704 assert(builder.isMatrix(right));
5705 break;
5706 case spv::OpMatrixTimesVector:
5707 assert(builder.isMatrix(left));
5708 assert(builder.isVector(right));
5709 break;
5710 case spv::OpMatrixTimesMatrix:
5711 assert(builder.isMatrix(left));
5712 assert(builder.isMatrix(right));
5713 break;
5714 default:
5715 firstClass = false;
5716 break;
5717 }
5718
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005719 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5720 firstClass = true;
5721
qining25262b32016-05-06 17:25:16 -04005722 if (firstClass) {
5723 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005724 decorations.addNoContraction(builder, result);
5725 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005726 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005727 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005728
LoopDawg592860c2016-06-09 08:57:35 -06005729 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005730 // The result type of all of them is the same type as the (a) matrix operand.
5731 // The algorithm is to:
5732 // - break the matrix(es) into vectors
5733 // - smear any scalar to a vector
5734 // - do vector operations
5735 // - make a matrix out the vector results
5736 switch (op) {
5737 case spv::OpFAdd:
5738 case spv::OpFSub:
5739 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005740 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005741 case spv::OpFMul:
5742 {
5743 // one time set up...
5744 bool leftMat = builder.isMatrix(left);
5745 bool rightMat = builder.isMatrix(right);
5746 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5747 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5748 spv::Id scalarType = builder.getScalarTypeId(typeId);
5749 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5750 std::vector<spv::Id> results;
5751 spv::Id smearVec = spv::NoResult;
5752 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005753 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005754 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005755 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005756
5757 // do each vector op
5758 for (unsigned int c = 0; c < numCols; ++c) {
5759 std::vector<unsigned int> indexes;
5760 indexes.push_back(c);
5761 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5762 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005763 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005764 decorations.addNoContraction(builder, result);
5765 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005766 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005767 }
5768
5769 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005770 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005771 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005772 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005773 }
5774 default:
5775 assert(0);
5776 return spv::NoResult;
5777 }
5778}
5779
John Kessenichead86222018-03-28 18:01:20 -06005780spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005781 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005782{
5783 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005784 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005785 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005786 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5787 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005788
5789 switch (op) {
5790 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005791 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005792 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005793 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005794 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005795 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005796 unaryOp = spv::OpSNegate;
5797 break;
5798
5799 case glslang::EOpLogicalNot:
5800 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005801 unaryOp = spv::OpLogicalNot;
5802 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005803 case glslang::EOpBitwiseNot:
5804 unaryOp = spv::OpNot;
5805 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005806
John Kessenich140f3df2015-06-26 16:58:36 -06005807 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005808 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005809 break;
5810 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005811 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005812 break;
5813 case glslang::EOpTranspose:
5814 unaryOp = spv::OpTranspose;
5815 break;
5816
5817 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005818 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005819 break;
5820 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005821 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005822 break;
5823 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005824 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005825 break;
5826 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005827 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005828 break;
5829 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005830 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005831 break;
5832 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005833 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005834 break;
5835 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005836 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005837 break;
5838 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005839 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005840 break;
5841
5842 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005843 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005844 break;
5845 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005846 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005847 break;
5848 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005849 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005850 break;
5851 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005852 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005853 break;
5854 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005855 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005856 break;
5857 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005858 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005859 break;
5860
5861 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005862 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005863 break;
5864 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005865 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005866 break;
5867
5868 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005869 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005870 break;
5871 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005872 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005873 break;
5874 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005875 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005876 break;
5877 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005878 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005879 break;
5880 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005881 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005882 break;
5883 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005884 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005885 break;
5886
5887 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005888 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005889 break;
5890 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005891 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005892 break;
5893 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005894 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005895 break;
5896 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005897 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005898 break;
5899 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005900 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005901 break;
5902 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005903 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005904 break;
5905
5906 case glslang::EOpIsNan:
5907 unaryOp = spv::OpIsNan;
5908 break;
5909 case glslang::EOpIsInf:
5910 unaryOp = spv::OpIsInf;
5911 break;
LoopDawg592860c2016-06-09 08:57:35 -06005912 case glslang::EOpIsFinite:
5913 unaryOp = spv::OpIsFinite;
5914 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005915
Rex Xucbc426e2015-12-15 16:03:10 +08005916 case glslang::EOpFloatBitsToInt:
5917 case glslang::EOpFloatBitsToUint:
5918 case glslang::EOpIntBitsToFloat:
5919 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005920 case glslang::EOpDoubleBitsToInt64:
5921 case glslang::EOpDoubleBitsToUint64:
5922 case glslang::EOpInt64BitsToDouble:
5923 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005924 case glslang::EOpFloat16BitsToInt16:
5925 case glslang::EOpFloat16BitsToUint16:
5926 case glslang::EOpInt16BitsToFloat16:
5927 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005928 unaryOp = spv::OpBitcast;
5929 break;
5930
John Kessenich140f3df2015-06-26 16:58:36 -06005931 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005932 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005933 break;
5934 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005935 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005936 break;
5937 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005938 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005939 break;
5940 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005941 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005942 break;
5943 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005944 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005945 break;
5946 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005947 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005948 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005949#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005950 case glslang::EOpPackSnorm4x8:
5951 libCall = spv::GLSLstd450PackSnorm4x8;
5952 break;
5953 case glslang::EOpUnpackSnorm4x8:
5954 libCall = spv::GLSLstd450UnpackSnorm4x8;
5955 break;
5956 case glslang::EOpPackUnorm4x8:
5957 libCall = spv::GLSLstd450PackUnorm4x8;
5958 break;
5959 case glslang::EOpUnpackUnorm4x8:
5960 libCall = spv::GLSLstd450UnpackUnorm4x8;
5961 break;
5962 case glslang::EOpPackDouble2x32:
5963 libCall = spv::GLSLstd450PackDouble2x32;
5964 break;
5965 case glslang::EOpUnpackDouble2x32:
5966 libCall = spv::GLSLstd450UnpackDouble2x32;
5967 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005968#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005969
Rex Xu8ff43de2016-04-22 16:51:45 +08005970 case glslang::EOpPackInt2x32:
5971 case glslang::EOpUnpackInt2x32:
5972 case glslang::EOpPackUint2x32:
5973 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005974 case glslang::EOpPack16:
5975 case glslang::EOpPack32:
5976 case glslang::EOpPack64:
5977 case glslang::EOpUnpack32:
5978 case glslang::EOpUnpack16:
5979 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005980 case glslang::EOpPackInt2x16:
5981 case glslang::EOpUnpackInt2x16:
5982 case glslang::EOpPackUint2x16:
5983 case glslang::EOpUnpackUint2x16:
5984 case glslang::EOpPackInt4x16:
5985 case glslang::EOpUnpackInt4x16:
5986 case glslang::EOpPackUint4x16:
5987 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005988 case glslang::EOpPackFloat2x16:
5989 case glslang::EOpUnpackFloat2x16:
5990 unaryOp = spv::OpBitcast;
5991 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005992
John Kessenich140f3df2015-06-26 16:58:36 -06005993 case glslang::EOpDPdx:
5994 unaryOp = spv::OpDPdx;
5995 break;
5996 case glslang::EOpDPdy:
5997 unaryOp = spv::OpDPdy;
5998 break;
5999 case glslang::EOpFwidth:
6000 unaryOp = spv::OpFwidth;
6001 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006002
John Kessenich140f3df2015-06-26 16:58:36 -06006003 case glslang::EOpAny:
6004 unaryOp = spv::OpAny;
6005 break;
6006 case glslang::EOpAll:
6007 unaryOp = spv::OpAll;
6008 break;
6009
6010 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06006011 if (isFloat)
6012 libCall = spv::GLSLstd450FAbs;
6013 else
6014 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06006015 break;
6016 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06006017 if (isFloat)
6018 libCall = spv::GLSLstd450FSign;
6019 else
6020 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06006021 break;
6022
John Kessenicha28f7a72019-08-06 07:00:58 -06006023#ifndef GLSLANG_WEB
6024 case glslang::EOpDPdxFine:
6025 unaryOp = spv::OpDPdxFine;
6026 break;
6027 case glslang::EOpDPdyFine:
6028 unaryOp = spv::OpDPdyFine;
6029 break;
6030 case glslang::EOpFwidthFine:
6031 unaryOp = spv::OpFwidthFine;
6032 break;
6033 case glslang::EOpDPdxCoarse:
6034 unaryOp = spv::OpDPdxCoarse;
6035 break;
6036 case glslang::EOpDPdyCoarse:
6037 unaryOp = spv::OpDPdyCoarse;
6038 break;
6039 case glslang::EOpFwidthCoarse:
6040 unaryOp = spv::OpFwidthCoarse;
6041 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04006042 case glslang::EOpRayQueryProceed:
6043 unaryOp = spv::OpRayQueryProceedKHR;
6044 break;
6045 case glslang::EOpRayQueryGetRayTMin:
6046 unaryOp = spv::OpRayQueryGetRayTMinKHR;
6047 break;
6048 case glslang::EOpRayQueryGetRayFlags:
6049 unaryOp = spv::OpRayQueryGetRayFlagsKHR;
6050 break;
6051 case glslang::EOpRayQueryGetWorldRayOrigin:
6052 unaryOp = spv::OpRayQueryGetWorldRayOriginKHR;
6053 break;
6054 case glslang::EOpRayQueryGetWorldRayDirection:
6055 unaryOp = spv::OpRayQueryGetWorldRayDirectionKHR;
6056 break;
6057 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
6058 unaryOp = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
6059 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006060 case glslang::EOpInterpolateAtCentroid:
6061 if (typeProxy == glslang::EbtFloat16)
6062 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6063 libCall = spv::GLSLstd450InterpolateAtCentroid;
6064 break;
John Kessenichfc51d282015-08-19 13:34:18 -06006065 case glslang::EOpAtomicCounterIncrement:
6066 case glslang::EOpAtomicCounterDecrement:
6067 case glslang::EOpAtomicCounter:
6068 {
6069 // Handle all of the atomics in one place, in createAtomicOperation()
6070 std::vector<spv::Id> operands;
6071 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006072 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06006073 }
6074
John Kessenichfc51d282015-08-19 13:34:18 -06006075 case glslang::EOpBitFieldReverse:
6076 unaryOp = spv::OpBitReverse;
6077 break;
6078 case glslang::EOpBitCount:
6079 unaryOp = spv::OpBitCount;
6080 break;
6081 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006082 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006083 break;
6084 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006085 if (isUnsigned)
6086 libCall = spv::GLSLstd450FindUMsb;
6087 else
6088 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006089 break;
6090
Ian Romanickb3bd4022019-01-21 08:57:25 -08006091 case glslang::EOpCountLeadingZeros:
6092 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6093 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6094 unaryOp = spv::OpUCountLeadingZerosINTEL;
6095 break;
6096
6097 case glslang::EOpCountTrailingZeros:
6098 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6099 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6100 unaryOp = spv::OpUCountTrailingZerosINTEL;
6101 break;
6102
Rex Xu574ab042016-04-14 16:53:07 +08006103 case glslang::EOpBallot:
6104 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006105 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006106 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08006107 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08006108 case glslang::EOpMinInvocations:
6109 case glslang::EOpMaxInvocations:
6110 case glslang::EOpAddInvocations:
6111 case glslang::EOpMinInvocationsNonUniform:
6112 case glslang::EOpMaxInvocationsNonUniform:
6113 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006114 case glslang::EOpMinInvocationsInclusiveScan:
6115 case glslang::EOpMaxInvocationsInclusiveScan:
6116 case glslang::EOpAddInvocationsInclusiveScan:
6117 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6118 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6119 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6120 case glslang::EOpMinInvocationsExclusiveScan:
6121 case glslang::EOpMaxInvocationsExclusiveScan:
6122 case glslang::EOpAddInvocationsExclusiveScan:
6123 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6124 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6125 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08006126 {
6127 std::vector<spv::Id> operands;
6128 operands.push_back(operand);
6129 return createInvocationsOperation(op, typeId, operands, typeProxy);
6130 }
John Kessenich66011cb2018-03-06 16:12:04 -07006131 case glslang::EOpSubgroupAll:
6132 case glslang::EOpSubgroupAny:
6133 case glslang::EOpSubgroupAllEqual:
6134 case glslang::EOpSubgroupBroadcastFirst:
6135 case glslang::EOpSubgroupBallot:
6136 case glslang::EOpSubgroupInverseBallot:
6137 case glslang::EOpSubgroupBallotBitCount:
6138 case glslang::EOpSubgroupBallotInclusiveBitCount:
6139 case glslang::EOpSubgroupBallotExclusiveBitCount:
6140 case glslang::EOpSubgroupBallotFindLSB:
6141 case glslang::EOpSubgroupBallotFindMSB:
6142 case glslang::EOpSubgroupAdd:
6143 case glslang::EOpSubgroupMul:
6144 case glslang::EOpSubgroupMin:
6145 case glslang::EOpSubgroupMax:
6146 case glslang::EOpSubgroupAnd:
6147 case glslang::EOpSubgroupOr:
6148 case glslang::EOpSubgroupXor:
6149 case glslang::EOpSubgroupInclusiveAdd:
6150 case glslang::EOpSubgroupInclusiveMul:
6151 case glslang::EOpSubgroupInclusiveMin:
6152 case glslang::EOpSubgroupInclusiveMax:
6153 case glslang::EOpSubgroupInclusiveAnd:
6154 case glslang::EOpSubgroupInclusiveOr:
6155 case glslang::EOpSubgroupInclusiveXor:
6156 case glslang::EOpSubgroupExclusiveAdd:
6157 case glslang::EOpSubgroupExclusiveMul:
6158 case glslang::EOpSubgroupExclusiveMin:
6159 case glslang::EOpSubgroupExclusiveMax:
6160 case glslang::EOpSubgroupExclusiveAnd:
6161 case glslang::EOpSubgroupExclusiveOr:
6162 case glslang::EOpSubgroupExclusiveXor:
6163 case glslang::EOpSubgroupQuadSwapHorizontal:
6164 case glslang::EOpSubgroupQuadSwapVertical:
6165 case glslang::EOpSubgroupQuadSwapDiagonal: {
6166 std::vector<spv::Id> operands;
6167 operands.push_back(operand);
6168 return createSubgroupOperation(op, typeId, operands, typeProxy);
6169 }
Rex Xu9d93a232016-05-05 12:30:44 +08006170 case glslang::EOpMbcnt:
6171 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6172 libCall = spv::MbcntAMD;
6173 break;
6174
6175 case glslang::EOpCubeFaceIndex:
6176 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6177 libCall = spv::CubeFaceIndexAMD;
6178 break;
6179
6180 case glslang::EOpCubeFaceCoord:
6181 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6182 libCall = spv::CubeFaceCoordAMD;
6183 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006184 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006185 unaryOp = spv::OpGroupNonUniformPartitionNV;
6186 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006187 case glslang::EOpConstructReference:
6188 unaryOp = spv::OpBitcast;
6189 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006190#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006191
6192 case glslang::EOpCopyObject:
6193 unaryOp = spv::OpCopyObject;
6194 break;
6195
John Kessenich140f3df2015-06-26 16:58:36 -06006196 default:
6197 return 0;
6198 }
6199
6200 spv::Id id;
6201 if (libCall >= 0) {
6202 std::vector<spv::Id> args;
6203 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006204 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006205 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006206 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006207 }
John Kessenich140f3df2015-06-26 16:58:36 -06006208
John Kessenichb9197c82019-08-11 07:41:45 -06006209 decorations.addNoContraction(builder, id);
6210 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006211 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006212}
6213
John Kessenich7a53f762016-01-20 11:19:27 -07006214// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006215spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6216 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006217{
6218 // Handle unary operations vector by vector.
6219 // The result type is the same type as the original type.
6220 // The algorithm is to:
6221 // - break the matrix into vectors
6222 // - apply the operation to each vector
6223 // - make a matrix out the vector results
6224
6225 // get the types sorted out
6226 int numCols = builder.getNumColumns(operand);
6227 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006228 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6229 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006230 std::vector<spv::Id> results;
6231
6232 // do each vector op
6233 for (int c = 0; c < numCols; ++c) {
6234 std::vector<unsigned int> indexes;
6235 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006236 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6237 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006238 decorations.addNoContraction(builder, destVec);
6239 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006240 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006241 }
6242
6243 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006244 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006245 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006246 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006247}
6248
John Kessenichad7645f2018-06-04 19:11:25 -06006249// For converting integers where both the bitwidth and the signedness could
6250// change, but only do the width change here. The caller is still responsible
6251// for the signedness conversion.
6252spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006253{
John Kessenichad7645f2018-06-04 19:11:25 -06006254 // Get the result type width, based on the type to convert to.
6255 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006256 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006257 case glslang::EOpConvInt16ToUint8:
6258 case glslang::EOpConvIntToUint8:
6259 case glslang::EOpConvInt64ToUint8:
6260 case glslang::EOpConvUint16ToInt8:
6261 case glslang::EOpConvUintToInt8:
6262 case glslang::EOpConvUint64ToInt8:
6263 width = 8;
6264 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006265 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006266 case glslang::EOpConvIntToUint16:
6267 case glslang::EOpConvInt64ToUint16:
6268 case glslang::EOpConvUint8ToInt16:
6269 case glslang::EOpConvUintToInt16:
6270 case glslang::EOpConvUint64ToInt16:
6271 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006272 break;
6273 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006274 case glslang::EOpConvInt16ToUint:
6275 case glslang::EOpConvInt64ToUint:
6276 case glslang::EOpConvUint8ToInt:
6277 case glslang::EOpConvUint16ToInt:
6278 case glslang::EOpConvUint64ToInt:
6279 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006280 break;
6281 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006282 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006283 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006284 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006285 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006286 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006287 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006288 break;
6289
6290 default:
6291 assert(false && "Default missing");
6292 break;
6293 }
6294
John Kessenichad7645f2018-06-04 19:11:25 -06006295 // Get the conversion operation and result type,
6296 // based on the target width, but the source type.
6297 spv::Id type = spv::NoType;
6298 spv::Op convOp = spv::OpNop;
6299 switch(op) {
6300 case glslang::EOpConvInt8ToUint16:
6301 case glslang::EOpConvInt8ToUint:
6302 case glslang::EOpConvInt8ToUint64:
6303 case glslang::EOpConvInt16ToUint8:
6304 case glslang::EOpConvInt16ToUint:
6305 case glslang::EOpConvInt16ToUint64:
6306 case glslang::EOpConvIntToUint8:
6307 case glslang::EOpConvIntToUint16:
6308 case glslang::EOpConvIntToUint64:
6309 case glslang::EOpConvInt64ToUint8:
6310 case glslang::EOpConvInt64ToUint16:
6311 case glslang::EOpConvInt64ToUint:
6312 convOp = spv::OpSConvert;
6313 type = builder.makeIntType(width);
6314 break;
6315 default:
6316 convOp = spv::OpUConvert;
6317 type = builder.makeUintType(width);
6318 break;
6319 }
6320
John Kessenich66011cb2018-03-06 16:12:04 -07006321 if (vectorSize > 0)
6322 type = builder.makeVectorType(type, vectorSize);
6323
John Kessenichad7645f2018-06-04 19:11:25 -06006324 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006325}
6326
John Kessenichead86222018-03-28 18:01:20 -06006327spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6328 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006329{
6330 spv::Op convOp = spv::OpNop;
6331 spv::Id zero = 0;
6332 spv::Id one = 0;
6333
6334 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6335
6336 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006337 case glslang::EOpConvIntToBool:
6338 case glslang::EOpConvUintToBool:
6339 zero = builder.makeUintConstant(0);
6340 zero = makeSmearedConstant(zero, vectorSize);
6341 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006342 case glslang::EOpConvFloatToBool:
6343 zero = builder.makeFloatConstant(0.0F);
6344 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006345 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006346 case glslang::EOpConvBoolToFloat:
6347 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006348 zero = builder.makeFloatConstant(0.0F);
6349 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006350 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006351
John Kessenich140f3df2015-06-26 16:58:36 -06006352 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006353 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006354#ifndef GLSLANG_WEB
6355 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006356 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006357 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006358 } else
6359#endif
6360 {
6361 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006362 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006363 }
Rex Xucabbb782017-03-24 13:41:14 +08006364
John Kessenich140f3df2015-06-26 16:58:36 -06006365 convOp = spv::OpSelect;
6366 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006367
John Kessenich140f3df2015-06-26 16:58:36 -06006368 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006369 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006370#ifndef GLSLANG_WEB
6371 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006372 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006373 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006374 } else
6375#endif
6376 {
6377 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006378 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006379 }
Rex Xucabbb782017-03-24 13:41:14 +08006380
John Kessenich140f3df2015-06-26 16:58:36 -06006381 convOp = spv::OpSelect;
6382 break;
6383
John Kessenich66011cb2018-03-06 16:12:04 -07006384 case glslang::EOpConvInt8ToFloat16:
6385 case glslang::EOpConvInt8ToFloat:
6386 case glslang::EOpConvInt8ToDouble:
6387 case glslang::EOpConvInt16ToFloat16:
6388 case glslang::EOpConvInt16ToFloat:
6389 case glslang::EOpConvInt16ToDouble:
6390 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006391 case glslang::EOpConvIntToFloat:
6392 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006393 case glslang::EOpConvInt64ToFloat:
6394 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006395 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006396 convOp = spv::OpConvertSToF;
6397 break;
6398
John Kessenich66011cb2018-03-06 16:12:04 -07006399 case glslang::EOpConvUint8ToFloat16:
6400 case glslang::EOpConvUint8ToFloat:
6401 case glslang::EOpConvUint8ToDouble:
6402 case glslang::EOpConvUint16ToFloat16:
6403 case glslang::EOpConvUint16ToFloat:
6404 case glslang::EOpConvUint16ToDouble:
6405 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006406 case glslang::EOpConvUintToFloat:
6407 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006408 case glslang::EOpConvUint64ToFloat:
6409 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006410 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006411 convOp = spv::OpConvertUToF;
6412 break;
6413
John Kessenich66011cb2018-03-06 16:12:04 -07006414 case glslang::EOpConvFloat16ToInt8:
6415 case glslang::EOpConvFloatToInt8:
6416 case glslang::EOpConvDoubleToInt8:
6417 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006418 case glslang::EOpConvFloatToInt16:
6419 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006420 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006421 case glslang::EOpConvFloatToInt:
6422 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006423 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006424 case glslang::EOpConvFloatToInt64:
6425 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006426 convOp = spv::OpConvertFToS;
6427 break;
6428
John Kessenich66011cb2018-03-06 16:12:04 -07006429 case glslang::EOpConvUint8ToInt8:
6430 case glslang::EOpConvInt8ToUint8:
6431 case glslang::EOpConvUint16ToInt16:
6432 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006433 case glslang::EOpConvUintToInt:
6434 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006435 case glslang::EOpConvUint64ToInt64:
6436 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006437 if (builder.isInSpecConstCodeGenMode()) {
6438 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006439#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006440 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6441 zero = builder.makeUint8Constant(0);
6442 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006443 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006444 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6445 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006446 } else
6447#endif
6448 {
Rex Xucabbb782017-03-24 13:41:14 +08006449 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006450 }
qining189b2032016-04-12 23:16:20 -04006451 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006452 // Use OpIAdd, instead of OpBitcast to do the conversion when
6453 // generating for OpSpecConstantOp instruction.
6454 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6455 }
6456 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006457 convOp = spv::OpBitcast;
6458 break;
6459
John Kessenich66011cb2018-03-06 16:12:04 -07006460 case glslang::EOpConvFloat16ToUint8:
6461 case glslang::EOpConvFloatToUint8:
6462 case glslang::EOpConvDoubleToUint8:
6463 case glslang::EOpConvFloat16ToUint16:
6464 case glslang::EOpConvFloatToUint16:
6465 case glslang::EOpConvDoubleToUint16:
6466 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006467 case glslang::EOpConvFloatToUint:
6468 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006469 case glslang::EOpConvFloatToUint64:
6470 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006471 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006472 convOp = spv::OpConvertFToU;
6473 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006474
John Kessenich39697cd2019-08-08 10:35:51 -06006475#ifndef GLSLANG_WEB
6476 case glslang::EOpConvInt8ToBool:
6477 case glslang::EOpConvUint8ToBool:
6478 zero = builder.makeUint8Constant(0);
6479 zero = makeSmearedConstant(zero, vectorSize);
6480 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6481 case glslang::EOpConvInt16ToBool:
6482 case glslang::EOpConvUint16ToBool:
6483 zero = builder.makeUint16Constant(0);
6484 zero = makeSmearedConstant(zero, vectorSize);
6485 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6486 case glslang::EOpConvInt64ToBool:
6487 case glslang::EOpConvUint64ToBool:
6488 zero = builder.makeUint64Constant(0);
6489 zero = makeSmearedConstant(zero, vectorSize);
6490 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6491 case glslang::EOpConvDoubleToBool:
6492 zero = builder.makeDoubleConstant(0.0);
6493 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006494 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006495 case glslang::EOpConvFloat16ToBool:
6496 zero = builder.makeFloat16Constant(0.0F);
6497 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006498 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006499 case glslang::EOpConvBoolToDouble:
6500 convOp = spv::OpSelect;
6501 zero = builder.makeDoubleConstant(0.0);
6502 one = builder.makeDoubleConstant(1.0);
6503 break;
6504 case glslang::EOpConvBoolToFloat16:
6505 convOp = spv::OpSelect;
6506 zero = builder.makeFloat16Constant(0.0F);
6507 one = builder.makeFloat16Constant(1.0F);
6508 break;
6509 case glslang::EOpConvBoolToInt8:
6510 zero = builder.makeInt8Constant(0);
6511 one = builder.makeInt8Constant(1);
6512 convOp = spv::OpSelect;
6513 break;
6514 case glslang::EOpConvBoolToUint8:
6515 zero = builder.makeUint8Constant(0);
6516 one = builder.makeUint8Constant(1);
6517 convOp = spv::OpSelect;
6518 break;
6519 case glslang::EOpConvBoolToInt16:
6520 zero = builder.makeInt16Constant(0);
6521 one = builder.makeInt16Constant(1);
6522 convOp = spv::OpSelect;
6523 break;
6524 case glslang::EOpConvBoolToUint16:
6525 zero = builder.makeUint16Constant(0);
6526 one = builder.makeUint16Constant(1);
6527 convOp = spv::OpSelect;
6528 break;
6529 case glslang::EOpConvDoubleToFloat:
6530 case glslang::EOpConvFloatToDouble:
6531 case glslang::EOpConvDoubleToFloat16:
6532 case glslang::EOpConvFloat16ToDouble:
6533 case glslang::EOpConvFloatToFloat16:
6534 case glslang::EOpConvFloat16ToFloat:
6535 convOp = spv::OpFConvert;
6536 if (builder.isMatrixType(destType))
6537 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6538 break;
6539
John Kessenich66011cb2018-03-06 16:12:04 -07006540 case glslang::EOpConvInt8ToInt16:
6541 case glslang::EOpConvInt8ToInt:
6542 case glslang::EOpConvInt8ToInt64:
6543 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006544 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006545 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006546 case glslang::EOpConvIntToInt8:
6547 case glslang::EOpConvIntToInt16:
6548 case glslang::EOpConvIntToInt64:
6549 case glslang::EOpConvInt64ToInt8:
6550 case glslang::EOpConvInt64ToInt16:
6551 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006552 convOp = spv::OpSConvert;
6553 break;
6554
John Kessenich66011cb2018-03-06 16:12:04 -07006555 case glslang::EOpConvUint8ToUint16:
6556 case glslang::EOpConvUint8ToUint:
6557 case glslang::EOpConvUint8ToUint64:
6558 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006559 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006560 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006561 case glslang::EOpConvUintToUint8:
6562 case glslang::EOpConvUintToUint16:
6563 case glslang::EOpConvUintToUint64:
6564 case glslang::EOpConvUint64ToUint8:
6565 case glslang::EOpConvUint64ToUint16:
6566 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006567 convOp = spv::OpUConvert;
6568 break;
6569
John Kessenich66011cb2018-03-06 16:12:04 -07006570 case glslang::EOpConvInt8ToUint16:
6571 case glslang::EOpConvInt8ToUint:
6572 case glslang::EOpConvInt8ToUint64:
6573 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006574 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006575 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006576 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006577 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006578 case glslang::EOpConvIntToUint64:
6579 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006580 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006581 case glslang::EOpConvInt64ToUint:
6582 case glslang::EOpConvUint8ToInt16:
6583 case glslang::EOpConvUint8ToInt:
6584 case glslang::EOpConvUint8ToInt64:
6585 case glslang::EOpConvUint16ToInt8:
6586 case glslang::EOpConvUint16ToInt:
6587 case glslang::EOpConvUint16ToInt64:
6588 case glslang::EOpConvUintToInt8:
6589 case glslang::EOpConvUintToInt16:
6590 case glslang::EOpConvUintToInt64:
6591 case glslang::EOpConvUint64ToInt8:
6592 case glslang::EOpConvUint64ToInt16:
6593 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006594 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006595 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006596
6597 if (builder.isInSpecConstCodeGenMode()) {
6598 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006599 switch(op) {
6600 case glslang::EOpConvInt16ToUint8:
6601 case glslang::EOpConvIntToUint8:
6602 case glslang::EOpConvInt64ToUint8:
6603 case glslang::EOpConvUint16ToInt8:
6604 case glslang::EOpConvUintToInt8:
6605 case glslang::EOpConvUint64ToInt8:
6606 zero = builder.makeUint8Constant(0);
6607 break;
6608 case glslang::EOpConvInt8ToUint16:
6609 case glslang::EOpConvIntToUint16:
6610 case glslang::EOpConvInt64ToUint16:
6611 case glslang::EOpConvUint8ToInt16:
6612 case glslang::EOpConvUintToInt16:
6613 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006614 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006615 break;
6616 case glslang::EOpConvInt8ToUint:
6617 case glslang::EOpConvInt16ToUint:
6618 case glslang::EOpConvInt64ToUint:
6619 case glslang::EOpConvUint8ToInt:
6620 case glslang::EOpConvUint16ToInt:
6621 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006622 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006623 break;
6624 case glslang::EOpConvInt8ToUint64:
6625 case glslang::EOpConvInt16ToUint64:
6626 case glslang::EOpConvIntToUint64:
6627 case glslang::EOpConvUint8ToInt64:
6628 case glslang::EOpConvUint16ToInt64:
6629 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006630 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006631 break;
6632 default:
6633 assert(false && "Default missing");
6634 break;
6635 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006636 zero = makeSmearedConstant(zero, vectorSize);
6637 // Use OpIAdd, instead of OpBitcast to do the conversion when
6638 // generating for OpSpecConstantOp instruction.
6639 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6640 }
6641 // For normal run-time conversion instruction, use OpBitcast.
6642 convOp = spv::OpBitcast;
6643 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006644 case glslang::EOpConvUint64ToPtr:
6645 convOp = spv::OpConvertUToPtr;
6646 break;
6647 case glslang::EOpConvPtrToUint64:
6648 convOp = spv::OpConvertPtrToU;
6649 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006650 case glslang::EOpConvPtrToUvec2:
6651 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006652 if (builder.isVector(operand))
6653 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6654 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006655 convOp = spv::OpBitcast;
6656 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006657#endif
6658
John Kessenich140f3df2015-06-26 16:58:36 -06006659 default:
6660 break;
6661 }
6662
6663 spv::Id result = 0;
6664 if (convOp == spv::OpNop)
6665 return result;
6666
6667 if (convOp == spv::OpSelect) {
6668 zero = makeSmearedConstant(zero, vectorSize);
6669 one = makeSmearedConstant(one, vectorSize);
6670 result = builder.createTriOp(convOp, destType, operand, one, zero);
6671 } else
6672 result = builder.createUnaryOp(convOp, destType, operand);
6673
John Kessenichead86222018-03-28 18:01:20 -06006674 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006675 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006676 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006677}
6678
6679spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6680{
6681 if (vectorSize == 0)
6682 return constant;
6683
6684 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6685 std::vector<spv::Id> components;
6686 for (int c = 0; c < vectorSize; ++c)
6687 components.push_back(constant);
6688 return builder.makeCompositeConstant(vectorTypeId, components);
6689}
6690
John Kessenich426394d2015-07-23 10:22:48 -06006691// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006692spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6693 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6694 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006695{
6696 spv::Op opCode = spv::OpNop;
6697
6698 switch (op) {
6699 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006700 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006701 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006702 opCode = spv::OpAtomicIAdd;
Vikram Kushwaha79b93922020-07-19 15:45:01 -07006703 if (typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble) {
6704 opCode = spv::OpAtomicFAddEXT;
6705 builder.addExtension(spv::E_SPV_EXT_shader_atomic_float_add);
6706 if (typeProxy == glslang::EbtFloat)
6707 builder.addCapability(spv::CapabilityAtomicFloat32AddEXT);
6708 else
6709 builder.addCapability(spv::CapabilityAtomicFloat64AddEXT);
6710 }
John Kessenich426394d2015-07-23 10:22:48 -06006711 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006712 case glslang::EOpAtomicCounterSubtract:
6713 opCode = spv::OpAtomicISub;
6714 break;
John Kessenich426394d2015-07-23 10:22:48 -06006715 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006716 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006717 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006718 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6719 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006720 break;
6721 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006722 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006723 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006724 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6725 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006726 break;
6727 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006728 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006729 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006730 opCode = spv::OpAtomicAnd;
6731 break;
6732 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006733 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006734 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006735 opCode = spv::OpAtomicOr;
6736 break;
6737 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006738 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006739 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006740 opCode = spv::OpAtomicXor;
6741 break;
6742 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006743 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006744 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006745 opCode = spv::OpAtomicExchange;
6746 break;
6747 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006748 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006749 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006750 opCode = spv::OpAtomicCompareExchange;
6751 break;
6752 case glslang::EOpAtomicCounterIncrement:
6753 opCode = spv::OpAtomicIIncrement;
6754 break;
6755 case glslang::EOpAtomicCounterDecrement:
6756 opCode = spv::OpAtomicIDecrement;
6757 break;
6758 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006759 case glslang::EOpImageAtomicLoad:
6760 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006761 opCode = spv::OpAtomicLoad;
6762 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006763 case glslang::EOpAtomicStore:
6764 case glslang::EOpImageAtomicStore:
6765 opCode = spv::OpAtomicStore;
6766 break;
John Kessenich426394d2015-07-23 10:22:48 -06006767 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006768 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006769 break;
6770 }
6771
Rex Xue8fe8b02017-09-26 15:42:56 +08006772 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6773 builder.addCapability(spv::CapabilityInt64Atomics);
6774
John Kessenich426394d2015-07-23 10:22:48 -06006775 // Sort out the operands
6776 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006777 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006778 // - compare-exchange swaps the value and comparator
6779 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006780 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006781 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6782 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6783 spv::Id scopeId;
6784 if (glslangIntermediate->usingVulkanMemoryModel()) {
6785 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6786 } else {
6787 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6788 }
6789 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006790 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6791 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006792 spv::MemorySemanticsVolatileMask :
6793 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006794 spv::Id semanticsId2 = semanticsId;
6795
6796 pointerId = operands[0];
6797 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6798 // no additional operands
6799 } else if (opCode == spv::OpAtomicCompareExchange) {
6800 compareId = operands[1];
6801 valueId = operands[2];
6802 if (operands.size() > 3) {
6803 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006804 semanticsId = builder.makeUintConstant(
6805 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6806 semanticsId2 = builder.makeUintConstant(
6807 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006808 }
6809 } else if (opCode == spv::OpAtomicLoad) {
6810 if (operands.size() > 1) {
6811 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006812 semanticsId = builder.makeUintConstant(
6813 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006814 }
6815 } else {
6816 // atomic store or RMW
6817 valueId = operands[1];
6818 if (operands.size() > 2) {
6819 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006820 semanticsId = builder.makeUintConstant
6821 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006822 }
Rex Xu04db3f52015-09-16 11:44:02 +08006823 }
John Kessenich426394d2015-07-23 10:22:48 -06006824
Jeff Bolz36831c92018-09-05 10:11:41 -05006825 // Check for capabilities
6826 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006827 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6828 spv::MemorySemanticsMakeVisibleKHRMask |
6829 spv::MemorySemanticsOutputMemoryKHRMask |
6830 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006831 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6832 }
John Kessenich426394d2015-07-23 10:22:48 -06006833
Jeff Bolz36831c92018-09-05 10:11:41 -05006834 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6835 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6836 }
John Kessenich48d6e792017-10-06 21:21:48 -06006837
Jeff Bolz36831c92018-09-05 10:11:41 -05006838 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6839 spvAtomicOperands.push_back(pointerId);
6840 spvAtomicOperands.push_back(scopeId);
6841 spvAtomicOperands.push_back(semanticsId);
6842 if (opCode == spv::OpAtomicCompareExchange) {
6843 spvAtomicOperands.push_back(semanticsId2);
6844 spvAtomicOperands.push_back(valueId);
6845 spvAtomicOperands.push_back(compareId);
6846 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6847 spvAtomicOperands.push_back(valueId);
6848 }
John Kessenich48d6e792017-10-06 21:21:48 -06006849
Jeff Bolz36831c92018-09-05 10:11:41 -05006850 if (opCode == spv::OpAtomicStore) {
6851 builder.createNoResultOp(opCode, spvAtomicOperands);
6852 return 0;
6853 } else {
6854 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6855
6856 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6857 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6858 if (op == glslang::EOpAtomicCounterDecrement)
6859 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6860
6861 return resultId;
6862 }
John Kessenich426394d2015-07-23 10:22:48 -06006863}
6864
John Kessenich91cef522016-05-05 16:45:40 -06006865// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07006866spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
6867 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006868{
John Kessenich66011cb2018-03-06 16:12:04 -07006869 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6870 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006871
Rex Xu51596642016-09-21 18:56:12 +08006872 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006873 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006874 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6875
chaocf200da82016-12-20 12:44:35 -08006876 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6877 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006878 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6879 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006880 } else if (op == glslang::EOpAnyInvocation ||
6881 op == glslang::EOpAllInvocations ||
6882 op == glslang::EOpAllInvocationsEqual) {
6883 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6884 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006885 } else {
6886 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006887 if (op == glslang::EOpMinInvocationsNonUniform ||
6888 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006889 op == glslang::EOpAddInvocationsNonUniform ||
6890 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6891 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6892 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6893 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6894 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6895 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006896 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006897
Rex Xu430ef402016-10-14 17:22:23 +08006898 switch (op) {
6899 case glslang::EOpMinInvocations:
6900 case glslang::EOpMaxInvocations:
6901 case glslang::EOpAddInvocations:
6902 case glslang::EOpMinInvocationsNonUniform:
6903 case glslang::EOpMaxInvocationsNonUniform:
6904 case glslang::EOpAddInvocationsNonUniform:
6905 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006906 break;
6907 case glslang::EOpMinInvocationsInclusiveScan:
6908 case glslang::EOpMaxInvocationsInclusiveScan:
6909 case glslang::EOpAddInvocationsInclusiveScan:
6910 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6911 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6912 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6913 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006914 break;
6915 case glslang::EOpMinInvocationsExclusiveScan:
6916 case glslang::EOpMaxInvocationsExclusiveScan:
6917 case glslang::EOpAddInvocationsExclusiveScan:
6918 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6919 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6920 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6921 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006922 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006923 default:
6924 break;
Rex Xu430ef402016-10-14 17:22:23 +08006925 }
John Kessenich149afc32018-08-14 13:31:43 -06006926 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6927 spvGroupOperands.push_back(scope);
6928 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006929 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006930 spvGroupOperands.push_back(groupOp);
6931 }
Rex Xu51596642016-09-21 18:56:12 +08006932 }
6933
John Kessenich149afc32018-08-14 13:31:43 -06006934 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6935 spv::IdImmediate op = { true, *opIt };
6936 spvGroupOperands.push_back(op);
6937 }
John Kessenich91cef522016-05-05 16:45:40 -06006938
6939 switch (op) {
6940 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006941 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006942 break;
John Kessenich91cef522016-05-05 16:45:40 -06006943 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006944 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006945 break;
John Kessenich91cef522016-05-05 16:45:40 -06006946 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006947 opCode = spv::OpSubgroupAllEqualKHR;
6948 break;
Rex Xu51596642016-09-21 18:56:12 +08006949 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006950 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006951 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006952 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006953 break;
6954 case glslang::EOpReadFirstInvocation:
6955 opCode = spv::OpSubgroupFirstInvocationKHR;
6956 break;
6957 case glslang::EOpBallot:
6958 {
6959 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6960 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6961 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6962 //
6963 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6964 //
6965 spv::Id uintType = builder.makeUintType(32);
6966 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6967 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6968
6969 std::vector<spv::Id> components;
6970 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6971 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6972
6973 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6974 return builder.createUnaryOp(spv::OpBitcast, typeId,
6975 builder.createCompositeConstruct(uvec2Type, components));
6976 }
6977
Rex Xu9d93a232016-05-05 12:30:44 +08006978 case glslang::EOpMinInvocations:
6979 case glslang::EOpMaxInvocations:
6980 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006981 case glslang::EOpMinInvocationsInclusiveScan:
6982 case glslang::EOpMaxInvocationsInclusiveScan:
6983 case glslang::EOpAddInvocationsInclusiveScan:
6984 case glslang::EOpMinInvocationsExclusiveScan:
6985 case glslang::EOpMaxInvocationsExclusiveScan:
6986 case glslang::EOpAddInvocationsExclusiveScan:
6987 if (op == glslang::EOpMinInvocations ||
6988 op == glslang::EOpMinInvocationsInclusiveScan ||
6989 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006990 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006991 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006992 else {
6993 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006994 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006995 else
Rex Xu51596642016-09-21 18:56:12 +08006996 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006997 }
Rex Xu430ef402016-10-14 17:22:23 +08006998 } else if (op == glslang::EOpMaxInvocations ||
6999 op == glslang::EOpMaxInvocationsInclusiveScan ||
7000 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08007001 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007002 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007003 else {
7004 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007005 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007006 else
Rex Xu51596642016-09-21 18:56:12 +08007007 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007008 }
7009 } else {
7010 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007011 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08007012 else
Rex Xu51596642016-09-21 18:56:12 +08007013 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08007014 }
7015
Rex Xu2bbbe062016-08-23 15:41:05 +08007016 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007017 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007018
7019 break;
Rex Xu9d93a232016-05-05 12:30:44 +08007020 case glslang::EOpMinInvocationsNonUniform:
7021 case glslang::EOpMaxInvocationsNonUniform:
7022 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08007023 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
7024 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
7025 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
7026 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
7027 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
7028 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
7029 if (op == glslang::EOpMinInvocationsNonUniform ||
7030 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
7031 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007032 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007033 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007034 else {
7035 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007036 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007037 else
Rex Xu51596642016-09-21 18:56:12 +08007038 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007039 }
7040 }
Rex Xu430ef402016-10-14 17:22:23 +08007041 else if (op == glslang::EOpMaxInvocationsNonUniform ||
7042 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
7043 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007044 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007045 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007046 else {
7047 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007048 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007049 else
Rex Xu51596642016-09-21 18:56:12 +08007050 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007051 }
7052 }
7053 else {
7054 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007055 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007056 else
Rex Xu51596642016-09-21 18:56:12 +08007057 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007058 }
7059
Rex Xu2bbbe062016-08-23 15:41:05 +08007060 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007061 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007062
7063 break;
John Kessenich91cef522016-05-05 16:45:40 -06007064 default:
7065 logger->missingFunctionality("invocation operation");
7066 return spv::NoResult;
7067 }
Rex Xu51596642016-09-21 18:56:12 +08007068
7069 assert(opCode != spv::OpNop);
7070 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06007071}
7072
Rex Xu2bbbe062016-08-23 15:41:05 +08007073// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06007074spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
7075 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08007076{
7077 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
7078 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08007079 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08007080 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07007081 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
7082 op == spv::OpGroupSMinNonUniformAMD ||
7083 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
7084 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08007085 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
7086
7087 // Handle group invocation operations scalar by scalar.
7088 // The result type is the same type as the original type.
7089 // The algorithm is to:
7090 // - break the vector into scalars
7091 // - apply the operation to each scalar
7092 // - make a vector out the scalar results
7093
7094 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08007095 int numComponents = builder.getNumComponents(operands[0]);
7096 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08007097 std::vector<spv::Id> results;
7098
7099 // do each scalar op
7100 for (int comp = 0; comp < numComponents; ++comp) {
7101 std::vector<unsigned int> indexes;
7102 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06007103 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
7104 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08007105 if (op == spv::OpSubgroupReadInvocationKHR) {
7106 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007107 spv::IdImmediate operand = { true, operands[1] };
7108 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08007109 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06007110 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7111 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08007112 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007113 spv::IdImmediate operand = { true, operands[1] };
7114 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08007115 } else {
John Kessenich149afc32018-08-14 13:31:43 -06007116 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7117 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06007118 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007119 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08007120 spvGroupOperands.push_back(scalar);
7121 }
Rex Xu2bbbe062016-08-23 15:41:05 +08007122
Rex Xub7072052016-09-26 15:53:40 +08007123 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08007124 }
7125
7126 // put the pieces together
7127 return builder.createCompositeConstruct(typeId, results);
7128}
Rex Xu2bbbe062016-08-23 15:41:05 +08007129
John Kessenich66011cb2018-03-06 16:12:04 -07007130// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06007131spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
7132 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07007133{
7134 // Add the required capabilities.
7135 switch (op) {
7136 case glslang::EOpSubgroupElect:
7137 builder.addCapability(spv::CapabilityGroupNonUniform);
7138 break;
7139 case glslang::EOpSubgroupAll:
7140 case glslang::EOpSubgroupAny:
7141 case glslang::EOpSubgroupAllEqual:
7142 builder.addCapability(spv::CapabilityGroupNonUniform);
7143 builder.addCapability(spv::CapabilityGroupNonUniformVote);
7144 break;
7145 case glslang::EOpSubgroupBroadcast:
7146 case glslang::EOpSubgroupBroadcastFirst:
7147 case glslang::EOpSubgroupBallot:
7148 case glslang::EOpSubgroupInverseBallot:
7149 case glslang::EOpSubgroupBallotBitExtract:
7150 case glslang::EOpSubgroupBallotBitCount:
7151 case glslang::EOpSubgroupBallotInclusiveBitCount:
7152 case glslang::EOpSubgroupBallotExclusiveBitCount:
7153 case glslang::EOpSubgroupBallotFindLSB:
7154 case glslang::EOpSubgroupBallotFindMSB:
7155 builder.addCapability(spv::CapabilityGroupNonUniform);
7156 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
7157 break;
7158 case glslang::EOpSubgroupShuffle:
7159 case glslang::EOpSubgroupShuffleXor:
7160 builder.addCapability(spv::CapabilityGroupNonUniform);
7161 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
7162 break;
7163 case glslang::EOpSubgroupShuffleUp:
7164 case glslang::EOpSubgroupShuffleDown:
7165 builder.addCapability(spv::CapabilityGroupNonUniform);
7166 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
7167 break;
7168 case glslang::EOpSubgroupAdd:
7169 case glslang::EOpSubgroupMul:
7170 case glslang::EOpSubgroupMin:
7171 case glslang::EOpSubgroupMax:
7172 case glslang::EOpSubgroupAnd:
7173 case glslang::EOpSubgroupOr:
7174 case glslang::EOpSubgroupXor:
7175 case glslang::EOpSubgroupInclusiveAdd:
7176 case glslang::EOpSubgroupInclusiveMul:
7177 case glslang::EOpSubgroupInclusiveMin:
7178 case glslang::EOpSubgroupInclusiveMax:
7179 case glslang::EOpSubgroupInclusiveAnd:
7180 case glslang::EOpSubgroupInclusiveOr:
7181 case glslang::EOpSubgroupInclusiveXor:
7182 case glslang::EOpSubgroupExclusiveAdd:
7183 case glslang::EOpSubgroupExclusiveMul:
7184 case glslang::EOpSubgroupExclusiveMin:
7185 case glslang::EOpSubgroupExclusiveMax:
7186 case glslang::EOpSubgroupExclusiveAnd:
7187 case glslang::EOpSubgroupExclusiveOr:
7188 case glslang::EOpSubgroupExclusiveXor:
7189 builder.addCapability(spv::CapabilityGroupNonUniform);
7190 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
7191 break;
7192 case glslang::EOpSubgroupClusteredAdd:
7193 case glslang::EOpSubgroupClusteredMul:
7194 case glslang::EOpSubgroupClusteredMin:
7195 case glslang::EOpSubgroupClusteredMax:
7196 case glslang::EOpSubgroupClusteredAnd:
7197 case glslang::EOpSubgroupClusteredOr:
7198 case glslang::EOpSubgroupClusteredXor:
7199 builder.addCapability(spv::CapabilityGroupNonUniform);
7200 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7201 break;
7202 case glslang::EOpSubgroupQuadBroadcast:
7203 case glslang::EOpSubgroupQuadSwapHorizontal:
7204 case glslang::EOpSubgroupQuadSwapVertical:
7205 case glslang::EOpSubgroupQuadSwapDiagonal:
7206 builder.addCapability(spv::CapabilityGroupNonUniform);
7207 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7208 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007209 case glslang::EOpSubgroupPartitionedAdd:
7210 case glslang::EOpSubgroupPartitionedMul:
7211 case glslang::EOpSubgroupPartitionedMin:
7212 case glslang::EOpSubgroupPartitionedMax:
7213 case glslang::EOpSubgroupPartitionedAnd:
7214 case glslang::EOpSubgroupPartitionedOr:
7215 case glslang::EOpSubgroupPartitionedXor:
7216 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7217 case glslang::EOpSubgroupPartitionedInclusiveMul:
7218 case glslang::EOpSubgroupPartitionedInclusiveMin:
7219 case glslang::EOpSubgroupPartitionedInclusiveMax:
7220 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7221 case glslang::EOpSubgroupPartitionedInclusiveOr:
7222 case glslang::EOpSubgroupPartitionedInclusiveXor:
7223 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7224 case glslang::EOpSubgroupPartitionedExclusiveMul:
7225 case glslang::EOpSubgroupPartitionedExclusiveMin:
7226 case glslang::EOpSubgroupPartitionedExclusiveMax:
7227 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7228 case glslang::EOpSubgroupPartitionedExclusiveOr:
7229 case glslang::EOpSubgroupPartitionedExclusiveXor:
7230 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7231 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7232 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007233 default: assert(0 && "Unhandled subgroup operation!");
7234 }
7235
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007236
7237 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7238 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007239 const bool isBool = typeProxy == glslang::EbtBool;
7240
7241 spv::Op opCode = spv::OpNop;
7242
7243 // Figure out which opcode to use.
7244 switch (op) {
7245 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7246 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7247 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7248 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7249 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7250 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7251 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7252 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7253 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7254 case glslang::EOpSubgroupBallotBitCount:
7255 case glslang::EOpSubgroupBallotInclusiveBitCount:
7256 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7257 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7258 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7259 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7260 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7261 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7262 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7263 case glslang::EOpSubgroupAdd:
7264 case glslang::EOpSubgroupInclusiveAdd:
7265 case glslang::EOpSubgroupExclusiveAdd:
7266 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007267 case glslang::EOpSubgroupPartitionedAdd:
7268 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7269 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007270 if (isFloat) {
7271 opCode = spv::OpGroupNonUniformFAdd;
7272 } else {
7273 opCode = spv::OpGroupNonUniformIAdd;
7274 }
7275 break;
7276 case glslang::EOpSubgroupMul:
7277 case glslang::EOpSubgroupInclusiveMul:
7278 case glslang::EOpSubgroupExclusiveMul:
7279 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007280 case glslang::EOpSubgroupPartitionedMul:
7281 case glslang::EOpSubgroupPartitionedInclusiveMul:
7282 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007283 if (isFloat) {
7284 opCode = spv::OpGroupNonUniformFMul;
7285 } else {
7286 opCode = spv::OpGroupNonUniformIMul;
7287 }
7288 break;
7289 case glslang::EOpSubgroupMin:
7290 case glslang::EOpSubgroupInclusiveMin:
7291 case glslang::EOpSubgroupExclusiveMin:
7292 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007293 case glslang::EOpSubgroupPartitionedMin:
7294 case glslang::EOpSubgroupPartitionedInclusiveMin:
7295 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007296 if (isFloat) {
7297 opCode = spv::OpGroupNonUniformFMin;
7298 } else if (isUnsigned) {
7299 opCode = spv::OpGroupNonUniformUMin;
7300 } else {
7301 opCode = spv::OpGroupNonUniformSMin;
7302 }
7303 break;
7304 case glslang::EOpSubgroupMax:
7305 case glslang::EOpSubgroupInclusiveMax:
7306 case glslang::EOpSubgroupExclusiveMax:
7307 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007308 case glslang::EOpSubgroupPartitionedMax:
7309 case glslang::EOpSubgroupPartitionedInclusiveMax:
7310 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007311 if (isFloat) {
7312 opCode = spv::OpGroupNonUniformFMax;
7313 } else if (isUnsigned) {
7314 opCode = spv::OpGroupNonUniformUMax;
7315 } else {
7316 opCode = spv::OpGroupNonUniformSMax;
7317 }
7318 break;
7319 case glslang::EOpSubgroupAnd:
7320 case glslang::EOpSubgroupInclusiveAnd:
7321 case glslang::EOpSubgroupExclusiveAnd:
7322 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007323 case glslang::EOpSubgroupPartitionedAnd:
7324 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7325 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007326 if (isBool) {
7327 opCode = spv::OpGroupNonUniformLogicalAnd;
7328 } else {
7329 opCode = spv::OpGroupNonUniformBitwiseAnd;
7330 }
7331 break;
7332 case glslang::EOpSubgroupOr:
7333 case glslang::EOpSubgroupInclusiveOr:
7334 case glslang::EOpSubgroupExclusiveOr:
7335 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007336 case glslang::EOpSubgroupPartitionedOr:
7337 case glslang::EOpSubgroupPartitionedInclusiveOr:
7338 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007339 if (isBool) {
7340 opCode = spv::OpGroupNonUniformLogicalOr;
7341 } else {
7342 opCode = spv::OpGroupNonUniformBitwiseOr;
7343 }
7344 break;
7345 case glslang::EOpSubgroupXor:
7346 case glslang::EOpSubgroupInclusiveXor:
7347 case glslang::EOpSubgroupExclusiveXor:
7348 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007349 case glslang::EOpSubgroupPartitionedXor:
7350 case glslang::EOpSubgroupPartitionedInclusiveXor:
7351 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007352 if (isBool) {
7353 opCode = spv::OpGroupNonUniformLogicalXor;
7354 } else {
7355 opCode = spv::OpGroupNonUniformBitwiseXor;
7356 }
7357 break;
7358 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7359 case glslang::EOpSubgroupQuadSwapHorizontal:
7360 case glslang::EOpSubgroupQuadSwapVertical:
7361 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7362 default: assert(0 && "Unhandled subgroup operation!");
7363 }
7364
John Kessenich149afc32018-08-14 13:31:43 -06007365 // get the right Group Operation
7366 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007367 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007368 default:
7369 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007370 case glslang::EOpSubgroupBallotBitCount:
7371 case glslang::EOpSubgroupAdd:
7372 case glslang::EOpSubgroupMul:
7373 case glslang::EOpSubgroupMin:
7374 case glslang::EOpSubgroupMax:
7375 case glslang::EOpSubgroupAnd:
7376 case glslang::EOpSubgroupOr:
7377 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007378 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007379 break;
7380 case glslang::EOpSubgroupBallotInclusiveBitCount:
7381 case glslang::EOpSubgroupInclusiveAdd:
7382 case glslang::EOpSubgroupInclusiveMul:
7383 case glslang::EOpSubgroupInclusiveMin:
7384 case glslang::EOpSubgroupInclusiveMax:
7385 case glslang::EOpSubgroupInclusiveAnd:
7386 case glslang::EOpSubgroupInclusiveOr:
7387 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007388 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007389 break;
7390 case glslang::EOpSubgroupBallotExclusiveBitCount:
7391 case glslang::EOpSubgroupExclusiveAdd:
7392 case glslang::EOpSubgroupExclusiveMul:
7393 case glslang::EOpSubgroupExclusiveMin:
7394 case glslang::EOpSubgroupExclusiveMax:
7395 case glslang::EOpSubgroupExclusiveAnd:
7396 case glslang::EOpSubgroupExclusiveOr:
7397 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007398 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007399 break;
7400 case glslang::EOpSubgroupClusteredAdd:
7401 case glslang::EOpSubgroupClusteredMul:
7402 case glslang::EOpSubgroupClusteredMin:
7403 case glslang::EOpSubgroupClusteredMax:
7404 case glslang::EOpSubgroupClusteredAnd:
7405 case glslang::EOpSubgroupClusteredOr:
7406 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007407 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007408 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007409 case glslang::EOpSubgroupPartitionedAdd:
7410 case glslang::EOpSubgroupPartitionedMul:
7411 case glslang::EOpSubgroupPartitionedMin:
7412 case glslang::EOpSubgroupPartitionedMax:
7413 case glslang::EOpSubgroupPartitionedAnd:
7414 case glslang::EOpSubgroupPartitionedOr:
7415 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007416 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007417 break;
7418 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7419 case glslang::EOpSubgroupPartitionedInclusiveMul:
7420 case glslang::EOpSubgroupPartitionedInclusiveMin:
7421 case glslang::EOpSubgroupPartitionedInclusiveMax:
7422 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7423 case glslang::EOpSubgroupPartitionedInclusiveOr:
7424 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007425 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007426 break;
7427 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7428 case glslang::EOpSubgroupPartitionedExclusiveMul:
7429 case glslang::EOpSubgroupPartitionedExclusiveMin:
7430 case glslang::EOpSubgroupPartitionedExclusiveMax:
7431 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7432 case glslang::EOpSubgroupPartitionedExclusiveOr:
7433 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007434 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007435 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007436 }
7437
John Kessenich149afc32018-08-14 13:31:43 -06007438 // build the instruction
7439 std::vector<spv::IdImmediate> spvGroupOperands;
7440
7441 // Every operation begins with the Execution Scope operand.
7442 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7443 spvGroupOperands.push_back(executionScope);
7444
7445 // Next, for all operations that use a Group Operation, push that as an operand.
7446 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007447 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007448 spvGroupOperands.push_back(groupOperand);
7449 }
7450
John Kessenich66011cb2018-03-06 16:12:04 -07007451 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007452 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7453 spv::IdImmediate operand = { true, *opIt };
7454 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007455 }
7456
7457 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007458 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007459 switch (op) {
7460 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007461 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7462 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7463 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7464 }
7465 if (directionId != spv::NoResult) {
7466 spv::IdImmediate direction = { true, directionId };
7467 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007468 }
7469
7470 return builder.createOp(opCode, typeId, spvGroupOperands);
7471}
7472
John Kessenich8985fc92020-03-03 10:25:07 -07007473spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7474 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007475{
John Kessenich66011cb2018-03-06 16:12:04 -07007476 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7477 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007478
John Kessenich140f3df2015-06-26 16:58:36 -06007479 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007480 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007481 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007482 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007483 spv::Id typeId0 = 0;
7484 if (consumedOperands > 0)
7485 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007486 spv::Id typeId1 = 0;
7487 if (consumedOperands > 1)
7488 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007489 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007490
7491 switch (op) {
7492 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007493 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007494 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007495 else if (isUnsigned)
7496 libCall = spv::GLSLstd450UMin;
7497 else
7498 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007499 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007500 break;
7501 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007502 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007503 break;
7504 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007505 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007506 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007507 else if (isUnsigned)
7508 libCall = spv::GLSLstd450UMax;
7509 else
7510 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007511 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007512 break;
7513 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007514 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007515 break;
7516 case glslang::EOpDot:
7517 opCode = spv::OpDot;
7518 break;
7519 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007520 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007521 break;
7522
7523 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007524 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007525 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007526 else if (isUnsigned)
7527 libCall = spv::GLSLstd450UClamp;
7528 else
7529 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007530 builder.promoteScalar(precision, operands.front(), operands[1]);
7531 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007532 break;
7533 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007534 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7535 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007536 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007537 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007538 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007539 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007540 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007541 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007542 break;
7543 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007544 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007545 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007546 break;
7547 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007548 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007549 builder.promoteScalar(precision, operands[0], operands[2]);
7550 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007551 break;
7552
7553 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007554 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007555 break;
7556 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007557 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007558 break;
7559 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007560 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007561 break;
7562 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007563 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007564 break;
7565 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007566 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007567 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007568 case glslang::EOpBarrier:
7569 {
7570 // This is for the extended controlBarrier function, with four operands.
7571 // The unextended barrier() goes through createNoArgOperation.
7572 assert(operands.size() == 4);
7573 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7574 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7575 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007576 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7577 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007578 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7579 spv::MemorySemanticsMakeVisibleKHRMask |
7580 spv::MemorySemanticsOutputMemoryKHRMask |
7581 spv::MemorySemanticsVolatileMask)) {
7582 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7583 }
John Kessenich8985fc92020-03-03 10:25:07 -07007584 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7585 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007586 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7587 }
7588 return 0;
7589 }
7590 break;
7591 case glslang::EOpMemoryBarrier:
7592 {
7593 // This is for the extended memoryBarrier function, with three operands.
7594 // The unextended memoryBarrier() goes through createNoArgOperation.
7595 assert(operands.size() == 3);
7596 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7597 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7598 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7599 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7600 spv::MemorySemanticsMakeVisibleKHRMask |
7601 spv::MemorySemanticsOutputMemoryKHRMask |
7602 spv::MemorySemanticsVolatileMask)) {
7603 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7604 }
7605 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7606 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7607 }
7608 return 0;
7609 }
7610 break;
7611
John Kessenicha28f7a72019-08-06 07:00:58 -06007612#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007613 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007614 if (typeProxy == glslang::EbtFloat16)
7615 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007616 libCall = spv::GLSLstd450InterpolateAtSample;
7617 break;
7618 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007619 if (typeProxy == glslang::EbtFloat16)
7620 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007621 libCall = spv::GLSLstd450InterpolateAtOffset;
7622 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007623 case glslang::EOpAddCarry:
7624 opCode = spv::OpIAddCarry;
7625 typeId = builder.makeStructResultType(typeId0, typeId0);
7626 consumedOperands = 2;
7627 break;
7628 case glslang::EOpSubBorrow:
7629 opCode = spv::OpISubBorrow;
7630 typeId = builder.makeStructResultType(typeId0, typeId0);
7631 consumedOperands = 2;
7632 break;
7633 case glslang::EOpUMulExtended:
7634 opCode = spv::OpUMulExtended;
7635 typeId = builder.makeStructResultType(typeId0, typeId0);
7636 consumedOperands = 2;
7637 break;
7638 case glslang::EOpIMulExtended:
7639 opCode = spv::OpSMulExtended;
7640 typeId = builder.makeStructResultType(typeId0, typeId0);
7641 consumedOperands = 2;
7642 break;
7643 case glslang::EOpBitfieldExtract:
7644 if (isUnsigned)
7645 opCode = spv::OpBitFieldUExtract;
7646 else
7647 opCode = spv::OpBitFieldSExtract;
7648 break;
7649 case glslang::EOpBitfieldInsert:
7650 opCode = spv::OpBitFieldInsert;
7651 break;
7652
7653 case glslang::EOpFma:
7654 libCall = spv::GLSLstd450Fma;
7655 break;
7656 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007657 {
7658 libCall = spv::GLSLstd450FrexpStruct;
7659 assert(builder.isPointerType(typeId1));
7660 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007661 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007662 if (width == 16)
7663 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7664 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007665 if (builder.getNumComponents(operands[0]) == 1)
7666 frexpIntType = builder.makeIntegerType(width, true);
7667 else
John Kessenich8985fc92020-03-03 10:25:07 -07007668 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7669 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007670 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7671 consumedOperands = 1;
7672 }
John Kessenich55e7d112015-11-15 21:33:39 -07007673 break;
7674 case glslang::EOpLdexp:
7675 libCall = spv::GLSLstd450Ldexp;
7676 break;
7677
Rex Xu574ab042016-04-14 16:53:07 +08007678 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007679 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007680
John Kessenich66011cb2018-03-06 16:12:04 -07007681 case glslang::EOpSubgroupBroadcast:
7682 case glslang::EOpSubgroupBallotBitExtract:
7683 case glslang::EOpSubgroupShuffle:
7684 case glslang::EOpSubgroupShuffleXor:
7685 case glslang::EOpSubgroupShuffleUp:
7686 case glslang::EOpSubgroupShuffleDown:
7687 case glslang::EOpSubgroupClusteredAdd:
7688 case glslang::EOpSubgroupClusteredMul:
7689 case glslang::EOpSubgroupClusteredMin:
7690 case glslang::EOpSubgroupClusteredMax:
7691 case glslang::EOpSubgroupClusteredAnd:
7692 case glslang::EOpSubgroupClusteredOr:
7693 case glslang::EOpSubgroupClusteredXor:
7694 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007695 case glslang::EOpSubgroupPartitionedAdd:
7696 case glslang::EOpSubgroupPartitionedMul:
7697 case glslang::EOpSubgroupPartitionedMin:
7698 case glslang::EOpSubgroupPartitionedMax:
7699 case glslang::EOpSubgroupPartitionedAnd:
7700 case glslang::EOpSubgroupPartitionedOr:
7701 case glslang::EOpSubgroupPartitionedXor:
7702 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7703 case glslang::EOpSubgroupPartitionedInclusiveMul:
7704 case glslang::EOpSubgroupPartitionedInclusiveMin:
7705 case glslang::EOpSubgroupPartitionedInclusiveMax:
7706 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7707 case glslang::EOpSubgroupPartitionedInclusiveOr:
7708 case glslang::EOpSubgroupPartitionedInclusiveXor:
7709 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7710 case glslang::EOpSubgroupPartitionedExclusiveMul:
7711 case glslang::EOpSubgroupPartitionedExclusiveMin:
7712 case glslang::EOpSubgroupPartitionedExclusiveMax:
7713 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7714 case glslang::EOpSubgroupPartitionedExclusiveOr:
7715 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007716 return createSubgroupOperation(op, typeId, operands, typeProxy);
7717
Rex Xu9d93a232016-05-05 12:30:44 +08007718 case glslang::EOpSwizzleInvocations:
7719 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7720 libCall = spv::SwizzleInvocationsAMD;
7721 break;
7722 case glslang::EOpSwizzleInvocationsMasked:
7723 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7724 libCall = spv::SwizzleInvocationsMaskedAMD;
7725 break;
7726 case glslang::EOpWriteInvocation:
7727 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7728 libCall = spv::WriteInvocationAMD;
7729 break;
7730
7731 case glslang::EOpMin3:
7732 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7733 if (isFloat)
7734 libCall = spv::FMin3AMD;
7735 else {
7736 if (isUnsigned)
7737 libCall = spv::UMin3AMD;
7738 else
7739 libCall = spv::SMin3AMD;
7740 }
7741 break;
7742 case glslang::EOpMax3:
7743 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7744 if (isFloat)
7745 libCall = spv::FMax3AMD;
7746 else {
7747 if (isUnsigned)
7748 libCall = spv::UMax3AMD;
7749 else
7750 libCall = spv::SMax3AMD;
7751 }
7752 break;
7753 case glslang::EOpMid3:
7754 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7755 if (isFloat)
7756 libCall = spv::FMid3AMD;
7757 else {
7758 if (isUnsigned)
7759 libCall = spv::UMid3AMD;
7760 else
7761 libCall = spv::SMid3AMD;
7762 }
7763 break;
7764
7765 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007766 if (typeProxy == glslang::EbtFloat16)
7767 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007768 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7769 libCall = spv::InterpolateAtVertexAMD;
7770 break;
Chao Chen3c366992018-09-19 11:41:59 -07007771
Daniel Kochdb32b242020-03-17 20:42:47 -04007772 case glslang::EOpReportIntersection:
Chao Chenb50c02e2018-09-19 11:42:24 -07007773 typeId = builder.makeBoolType();
Daniel Kochdb32b242020-03-17 20:42:47 -04007774 opCode = spv::OpReportIntersectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007775 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04007776 case glslang::EOpTrace:
Daniel Kochdb32b242020-03-17 20:42:47 -04007777 builder.createNoResultOp(spv::OpTraceRayKHR, operands);
Ashwin Leleff1783d2018-10-22 16:41:44 -07007778 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04007779 case glslang::EOpExecuteCallable:
Daniel Kochdb32b242020-03-17 20:42:47 -04007780 builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007781 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007782
7783 case glslang::EOpRayQueryInitialize:
Torosdagli06c2eee2020-03-19 11:09:57 -04007784 builder.createNoResultOp(spv::OpRayQueryInitializeKHR, operands);
7785 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007786 case glslang::EOpRayQueryTerminate:
Torosdagli06c2eee2020-03-19 11:09:57 -04007787 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operands);
7788 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007789 case glslang::EOpRayQueryGenerateIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007790 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR, operands);
7791 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007792 case glslang::EOpRayQueryConfirmIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007793 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operands);
7794 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007795 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04007796 typeId = builder.makeBoolType();
7797 opCode = spv::OpRayQueryProceedKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007798 break;
7799 case glslang::EOpRayQueryGetIntersectionType:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007800 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007801 opCode = spv::OpRayQueryGetIntersectionTypeKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007802 break;
7803 case glslang::EOpRayQueryGetRayTMin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007804 typeId = builder.makeFloatType(32);
7805 opCode = spv::OpRayQueryGetRayTMinKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007806 break;
7807 case glslang::EOpRayQueryGetRayFlags:
Torosdagli06c2eee2020-03-19 11:09:57 -04007808 typeId = builder.makeIntType(32);
7809 opCode = spv::OpRayQueryGetRayFlagsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007810 break;
7811 case glslang::EOpRayQueryGetIntersectionT:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007812 typeId = builder.makeFloatType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007813 opCode = spv::OpRayQueryGetIntersectionTKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007814 break;
7815 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007816 typeId = builder.makeIntType(32);
7817 opCode = spv::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007818 break;
7819 case glslang::EOpRayQueryGetIntersectionInstanceId:
Torosdagli06c2eee2020-03-19 11:09:57 -04007820 typeId = builder.makeIntType(32);
7821 opCode = spv::OpRayQueryGetIntersectionInstanceIdKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007822 break;
7823 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
Torosdagli06c2eee2020-03-19 11:09:57 -04007824 typeId = builder.makeIntType(32);
7825 opCode = spv::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007826 break;
7827 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007828 typeId = builder.makeIntType(32);
7829 opCode = spv::OpRayQueryGetIntersectionGeometryIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007830 break;
7831 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007832 typeId = builder.makeIntType(32);
7833 opCode = spv::OpRayQueryGetIntersectionPrimitiveIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007834 break;
7835 case glslang::EOpRayQueryGetIntersectionBarycentrics:
Torosdagli06c2eee2020-03-19 11:09:57 -04007836 typeId = builder.makeVectorType(builder.makeFloatType(32), 2);
7837 opCode = spv::OpRayQueryGetIntersectionBarycentricsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007838 break;
7839 case glslang::EOpRayQueryGetIntersectionFrontFace:
Torosdagli06c2eee2020-03-19 11:09:57 -04007840 typeId = builder.makeBoolType();
7841 opCode = spv::OpRayQueryGetIntersectionFrontFaceKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007842 break;
7843 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
Torosdagli06c2eee2020-03-19 11:09:57 -04007844 typeId = builder.makeBoolType();
7845 opCode = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007846 break;
7847 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007848 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7849 opCode = spv::OpRayQueryGetIntersectionObjectRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007850 break;
7851 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007852 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7853 opCode = spv::OpRayQueryGetIntersectionObjectRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007854 break;
7855 case glslang::EOpRayQueryGetWorldRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007856 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7857 opCode = spv::OpRayQueryGetWorldRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007858 break;
7859 case glslang::EOpRayQueryGetWorldRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007860 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7861 opCode = spv::OpRayQueryGetWorldRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007862 break;
7863 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
Torosdagli06c2eee2020-03-19 11:09:57 -04007864 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007865 opCode = spv::OpRayQueryGetIntersectionObjectToWorldKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007866 break;
7867 case glslang::EOpRayQueryGetIntersectionWorldToObject:
Torosdagli06c2eee2020-03-19 11:09:57 -04007868 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007869 opCode = spv::OpRayQueryGetIntersectionWorldToObjectKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007870 break;
Chao Chen3c366992018-09-19 11:41:59 -07007871 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7872 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7873 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007874 case glslang::EOpCooperativeMatrixMulAdd:
7875 opCode = spv::OpCooperativeMatrixMulAddNV;
7876 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007877#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007878 default:
7879 return 0;
7880 }
7881
7882 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007883 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007884 // Use an extended instruction from the standard library.
7885 // Construct the call arguments, without modifying the original operands vector.
7886 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7887 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007888 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007889 } else if (opCode == spv::OpDot && !isFloat) {
7890 // int dot(int, int)
7891 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7892 const int componentCount = builder.getNumComponents(operands[0]);
7893 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7894 builder.setPrecision(mulOp, precision);
7895 id = builder.createCompositeExtract(mulOp, typeId, 0);
7896 for (int i = 1; i < componentCount; ++i) {
7897 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07007898 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01007899 }
John Kessenich2359bd02015-12-06 19:29:11 -07007900 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007901 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007902 case 0:
7903 // should all be handled by visitAggregate and createNoArgOperation
7904 assert(0);
7905 return 0;
7906 case 1:
7907 // should all be handled by createUnaryOperation
7908 assert(0);
7909 return 0;
7910 case 2:
7911 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7912 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007913 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007914 // anything 3 or over doesn't have l-value operands, so all should be consumed
7915 assert(consumedOperands == operands.size());
7916 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007917 break;
7918 }
7919 }
7920
John Kessenichb9197c82019-08-11 07:41:45 -06007921#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007922 // Decode the return types that were structures
7923 switch (op) {
7924 case glslang::EOpAddCarry:
7925 case glslang::EOpSubBorrow:
7926 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7927 id = builder.createCompositeExtract(id, typeId0, 0);
7928 break;
7929 case glslang::EOpUMulExtended:
7930 case glslang::EOpIMulExtended:
7931 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7932 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7933 break;
7934 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007935 {
7936 assert(operands.size() == 2);
7937 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7938 // "exp" is floating-point type (from HLSL intrinsic)
7939 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7940 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7941 builder.createStore(member1, operands[1]);
7942 } else
7943 // "exp" is integer type (from GLSL built-in function)
7944 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7945 id = builder.createCompositeExtract(id, typeId0, 0);
7946 }
John Kessenich55e7d112015-11-15 21:33:39 -07007947 break;
7948 default:
7949 break;
7950 }
John Kessenichb9197c82019-08-11 07:41:45 -06007951#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007952
John Kessenich32cfd492016-02-02 12:37:46 -07007953 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007954}
7955
Rex Xu9d93a232016-05-05 12:30:44 +08007956// Intrinsics with no arguments (or no return value, and no precision).
7957spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007958{
Jeff Bolz36831c92018-09-05 10:11:41 -05007959 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07007960 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
7961 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007962
7963 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007964 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007965 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007966 if (glslangIntermediate->usingVulkanMemoryModel()) {
7967 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7968 spv::MemorySemanticsOutputMemoryKHRMask |
7969 spv::MemorySemanticsAcquireReleaseMask);
7970 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7971 } else {
7972 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7973 }
John Kessenich82979362017-12-11 04:02:24 -07007974 } else {
7975 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7976 spv::MemorySemanticsWorkgroupMemoryMask |
7977 spv::MemorySemanticsAcquireReleaseMask);
7978 }
John Kessenich140f3df2015-06-26 16:58:36 -06007979 return 0;
7980 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007981 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7982 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007983 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007984 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007985 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7986 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007987 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007988 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007989 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7990 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007991 return 0;
7992 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007993 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7994 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007995 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007996#ifndef GLSLANG_WEB
7997 case glslang::EOpMemoryBarrierAtomicCounter:
7998 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7999 spv::MemorySemanticsAcquireReleaseMask);
8000 return 0;
8001 case glslang::EOpMemoryBarrierImage:
8002 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
8003 spv::MemorySemanticsAcquireReleaseMask);
8004 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06008005 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07008006 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07008007 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07008008 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008009 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07008010 case glslang::EOpDeviceMemoryBarrier:
8011 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
8012 spv::MemorySemanticsImageMemoryMask |
8013 spv::MemorySemanticsAcquireReleaseMask);
8014 return 0;
8015 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
8016 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
8017 spv::MemorySemanticsImageMemoryMask |
8018 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008019 return 0;
8020 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07008021 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8022 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008023 return 0;
8024 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07008025 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8026 spv::MemorySemanticsWorkgroupMemoryMask |
8027 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008028 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07008029 case glslang::EOpSubgroupBarrier:
8030 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8031 spv::MemorySemanticsAcquireReleaseMask);
8032 return spv::NoResult;
8033 case glslang::EOpSubgroupMemoryBarrier:
8034 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8035 spv::MemorySemanticsAcquireReleaseMask);
8036 return spv::NoResult;
8037 case glslang::EOpSubgroupMemoryBarrierBuffer:
8038 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
8039 spv::MemorySemanticsAcquireReleaseMask);
8040 return spv::NoResult;
8041 case glslang::EOpSubgroupMemoryBarrierImage:
8042 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
8043 spv::MemorySemanticsAcquireReleaseMask);
8044 return spv::NoResult;
8045 case glslang::EOpSubgroupMemoryBarrierShared:
8046 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8047 spv::MemorySemanticsAcquireReleaseMask);
8048 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06008049
8050 case glslang::EOpEmitVertex:
8051 builder.createNoResultOp(spv::OpEmitVertex);
8052 return 0;
8053 case glslang::EOpEndPrimitive:
8054 builder.createNoResultOp(spv::OpEndPrimitive);
8055 return 0;
8056
John Kessenich66011cb2018-03-06 16:12:04 -07008057 case glslang::EOpSubgroupElect: {
8058 std::vector<spv::Id> operands;
8059 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
8060 }
Rex Xu9d93a232016-05-05 12:30:44 +08008061 case glslang::EOpTime:
8062 {
8063 std::vector<spv::Id> args; // Dummy arguments
8064 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
8065 return builder.setPrecision(id, precision);
8066 }
Daniel Kochdb32b242020-03-17 20:42:47 -04008067 case glslang::EOpIgnoreIntersection:
8068 builder.createNoResultOp(spv::OpIgnoreIntersectionKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008069 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04008070 case glslang::EOpTerminateRay:
8071 builder.createNoResultOp(spv::OpTerminateRayKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008072 return 0;
Torosdagli06c2eee2020-03-19 11:09:57 -04008073 case glslang::EOpRayQueryInitialize:
8074 builder.createNoResultOp(spv::OpRayQueryInitializeKHR);
8075 return 0;
8076 case glslang::EOpRayQueryTerminate:
8077 builder.createNoResultOp(spv::OpRayQueryTerminateKHR);
8078 return 0;
8079 case glslang::EOpRayQueryGenerateIntersection:
8080 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR);
8081 return 0;
8082 case glslang::EOpRayQueryConfirmIntersection:
8083 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR);
8084 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05008085 case glslang::EOpBeginInvocationInterlock:
8086 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
8087 return 0;
8088 case glslang::EOpEndInvocationInterlock:
8089 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
8090 return 0;
8091
Jeff Bolzba6170b2019-07-01 09:23:23 -05008092 case glslang::EOpIsHelperInvocation:
8093 {
8094 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08008095 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
8096 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
8097 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05008098 }
8099
amhagan91fb0092019-07-10 21:14:38 -04008100 case glslang::EOpReadClockSubgroupKHR: {
8101 std::vector<spv::Id> args;
8102 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
8103 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8104 builder.addCapability(spv::CapabilityShaderClockKHR);
8105 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8106 }
8107
8108 case glslang::EOpReadClockDeviceKHR: {
8109 std::vector<spv::Id> args;
8110 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
8111 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8112 builder.addCapability(spv::CapabilityShaderClockKHR);
8113 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8114 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06008115#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008116 default:
John Kessenich155d3512019-08-08 23:29:20 -06008117 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008118 }
John Kessenich155d3512019-08-08 23:29:20 -06008119
8120 logger->missingFunctionality("unknown operation with no arguments");
8121
8122 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008123}
8124
8125spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
8126{
John Kessenich2f273362015-07-18 22:34:27 -06008127 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06008128 spv::Id id;
8129 if (symbolValues.end() != iter) {
8130 id = iter->second;
8131 return id;
8132 }
8133
8134 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06008135 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
Daniel Kochdb32b242020-03-17 20:42:47 -04008136 auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06008137 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06008138 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06008139 if (forcedType.second != spv::NoType)
8140 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06008141
Rex Xuc884b4a2016-06-29 15:03:44 +08008142 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008143 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
8144 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
8145 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06008146#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008147 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06008148 if (symbol->getQualifier().hasComponent())
8149 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
8150 if (symbol->getQualifier().hasIndex())
8151 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07008152#endif
John Kessenich6c292d32016-02-15 20:58:50 -07008153 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07008154 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06008155 // atomic counters use this:
8156 if (symbol->getQualifier().hasOffset())
8157 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008158 }
8159
scygan2c864272016-05-18 18:09:17 +02008160 if (symbol->getQualifier().hasLocation())
8161 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07008162 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07008163 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07008164 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06008165 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07008166 }
John Kessenich140f3df2015-06-26 16:58:36 -06008167 if (symbol->getQualifier().hasSet())
8168 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07008169 else if (IsDescriptorResource(symbol->getType())) {
8170 // default to 0
8171 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
8172 }
John Kessenich140f3df2015-06-26 16:58:36 -06008173 if (symbol->getQualifier().hasBinding())
8174 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06008175 else if (IsDescriptorResource(symbol->getType())) {
8176 // default to 0
8177 builder.addDecoration(id, spv::DecorationBinding, 0);
8178 }
John Kessenich6c292d32016-02-15 20:58:50 -07008179 if (symbol->getQualifier().hasAttachment())
8180 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06008181 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07008182 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07008183 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008184 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07008185 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
8186 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
8187 builder.addDecoration(id, spv::DecorationXfbStride, stride);
8188 }
8189 if (symbol->getQualifier().hasXfbOffset())
8190 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008191 }
8192
John Kessenichb9197c82019-08-11 07:41:45 -06008193 // add built-in variable decoration
8194 if (builtIn != spv::BuiltInMax) {
8195 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
8196 }
8197
8198#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08008199 if (symbol->getType().isImage()) {
8200 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07008201 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
8202 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08008203 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07008204 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08008205 }
8206
John Kessenich5611c6d2018-04-05 11:25:02 -06008207 // nonuniform
8208 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
8209
chaoc0ad6a4e2016-12-19 16:29:34 -08008210 if (builtIn == spv::BuiltInSampleMask) {
8211 spv::Decoration decoration;
8212 // GL_NV_sample_mask_override_coverage extension
8213 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08008214 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08008215 else
8216 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07008217 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08008218 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07008219 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08008220 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
8221 }
8222 }
chaoc771d89f2017-01-13 01:10:53 -08008223 else if (builtIn == spv::BuiltInLayer) {
8224 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06008225 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008226 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08008227 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
8228 builder.addExtension(spv::E_SPV_NV_viewport_array2);
8229 }
John Kessenichb41bff62017-08-11 13:07:17 -06008230 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008231 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
8232 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08008233 builder.addCapability(spv::CapabilityShaderStereoViewNV);
8234 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
8235 }
8236 }
8237
chaoc6e5acae2016-12-20 13:28:52 -08008238 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008239 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08008240 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08008241 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
8242 }
Chao Chen9eada4b2018-09-19 11:39:56 -07008243 if (symbol->getQualifier().pervertexNV) {
8244 builder.addDecoration(id, spv::DecorationPerVertexNV);
8245 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
8246 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
8247 }
chaoc0ad6a4e2016-12-19 16:29:34 -08008248
John Kessenich5d610ee2018-03-07 18:05:55 -07008249 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
8250 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
8251 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
8252 symbol->getType().getQualifier().semanticName);
8253 }
8254
John Kessenich7015bd62019-08-01 03:28:08 -06008255 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07008256 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
8257 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008258 }
John Kessenichb9197c82019-08-11 07:41:45 -06008259#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008260
John Kessenich140f3df2015-06-26 16:58:36 -06008261 return id;
8262}
8263
John Kessenicha28f7a72019-08-06 07:00:58 -06008264#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008265// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
8266void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
8267{
8268 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07008269 if (qualifier.perPrimitiveNV) {
8270 // Need to add capability/extension for fragment shader.
8271 // Mesh shader already adds this by default.
8272 if (glslangIntermediate->getStage() == EShLangFragment) {
8273 builder.addCapability(spv::CapabilityMeshShadingNV);
8274 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8275 }
Chao Chen3c366992018-09-19 11:41:59 -07008276 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008277 }
Chao Chen3c366992018-09-19 11:41:59 -07008278 if (qualifier.perViewNV)
8279 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
8280 if (qualifier.perTaskNV)
8281 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
8282 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07008283 if (qualifier.perPrimitiveNV) {
8284 // Need to add capability/extension for fragment shader.
8285 // Mesh shader already adds this by default.
8286 if (glslangIntermediate->getStage() == EShLangFragment) {
8287 builder.addCapability(spv::CapabilityMeshShadingNV);
8288 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8289 }
Chao Chen3c366992018-09-19 11:41:59 -07008290 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008291 }
Chao Chen3c366992018-09-19 11:41:59 -07008292 if (qualifier.perViewNV)
8293 builder.addDecoration(id, spv::DecorationPerViewNV);
8294 if (qualifier.perTaskNV)
8295 builder.addDecoration(id, spv::DecorationPerTaskNV);
8296 }
8297}
8298#endif
8299
John Kessenich55e7d112015-11-15 21:33:39 -07008300// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008301// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008302//
8303// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8304//
8305// Recursively walk the nodes. The nodes form a tree whose leaves are
8306// regular constants, which themselves are trees that createSpvConstant()
8307// recursively walks. So, this function walks the "top" of the tree:
8308// - emit specialization constant-building instructions for specConstant
8309// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008310spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008311{
John Kessenich7cc0e282016-03-20 00:46:02 -06008312 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008313
qining4f4bb812016-04-03 23:55:17 -04008314 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008315 if (! node.getQualifier().specConstant) {
8316 // hand off to the non-spec-constant path
8317 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8318 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008319 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8320 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8321 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008322 }
8323
8324 // We now know we have a specialization constant to build
8325
Ricardo Garcia232ba0d2020-06-03 15:52:55 +02008326 // Extra capabilities may be needed.
8327 if (node.getType().contains8BitInt())
8328 builder.addCapability(spv::CapabilityInt8);
8329 if (node.getType().contains16BitFloat())
8330 builder.addCapability(spv::CapabilityFloat16);
8331 if (node.getType().contains16BitInt())
8332 builder.addCapability(spv::CapabilityInt16);
8333 if (node.getType().contains64BitInt())
8334 builder.addCapability(spv::CapabilityInt64);
8335 if (node.getType().containsDouble())
8336 builder.addCapability(spv::CapabilityFloat64);
8337
John Kessenichd94c0032016-05-30 19:29:40 -06008338 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008339 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8340 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8341 std::vector<spv::Id> dimConstId;
8342 for (int dim = 0; dim < 3; ++dim) {
8343 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8344 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008345 if (specConst) {
8346 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8347 glslangIntermediate->getLocalSizeSpecId(dim));
8348 }
qining4f4bb812016-04-03 23:55:17 -04008349 }
8350 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8351 }
8352
8353 // An AST node labelled as specialization constant should be a symbol node.
8354 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8355 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008356 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008357 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008358 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8359 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8360 // will set the builder into spec constant op instruction generating mode.
8361 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008362 result = accessChainLoad(sub_tree->getType());
8363 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008364 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008365 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008366 } else {
8367 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008368 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008369 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008370 builder.addName(result, sn->getName().c_str());
8371 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008372 }
qining4f4bb812016-04-03 23:55:17 -04008373
8374 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8375 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008376 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008377 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008378}
8379
John Kessenich140f3df2015-06-26 16:58:36 -06008380// Use 'consts' as the flattened glslang source of scalar constants to recursively
8381// build the aggregate SPIR-V constant.
8382//
8383// If there are not enough elements present in 'consts', 0 will be substituted;
8384// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8385//
John Kessenich8985fc92020-03-03 10:25:07 -07008386spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8387 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008388{
8389 // vector of constants for SPIR-V
8390 std::vector<spv::Id> spvConsts;
8391
8392 // Type is used for struct and array constants
8393 spv::Id typeId = convertGlslangToSpvType(glslangType);
8394
8395 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008396 glslang::TType elementType(glslangType, 0);
8397 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008398 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008399 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008400 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008401 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008402 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008403 } else if (glslangType.isCoopMat()) {
8404 glslang::TType componentType(glslangType.getBasicType());
8405 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008406 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008407 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8408 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008409 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008410 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008411 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8412 bool zero = nextConst >= consts.size();
8413 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008414 case glslang::EbtInt:
8415 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8416 break;
8417 case glslang::EbtUint:
8418 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8419 break;
8420 case glslang::EbtFloat:
8421 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8422 break;
8423 case glslang::EbtBool:
8424 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8425 break;
8426#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008427 case glslang::EbtInt8:
8428 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8429 break;
8430 case glslang::EbtUint8:
8431 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8432 break;
8433 case glslang::EbtInt16:
8434 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8435 break;
8436 case glslang::EbtUint16:
8437 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8438 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008439 case glslang::EbtInt64:
8440 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8441 break;
8442 case glslang::EbtUint64:
8443 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8444 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008445 case glslang::EbtDouble:
8446 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8447 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008448 case glslang::EbtFloat16:
8449 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8450 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008451#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008452 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008453 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008454 break;
8455 }
8456 ++nextConst;
8457 }
8458 } else {
8459 // we have a non-aggregate (scalar) constant
8460 bool zero = nextConst >= consts.size();
8461 spv::Id scalar = 0;
8462 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008463 case glslang::EbtInt:
8464 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8465 break;
8466 case glslang::EbtUint:
8467 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8468 break;
8469 case glslang::EbtFloat:
8470 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8471 break;
8472 case glslang::EbtBool:
8473 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8474 break;
8475#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008476 case glslang::EbtInt8:
8477 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8478 break;
8479 case glslang::EbtUint8:
8480 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8481 break;
8482 case glslang::EbtInt16:
8483 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8484 break;
8485 case glslang::EbtUint16:
8486 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8487 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008488 case glslang::EbtInt64:
8489 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8490 break;
8491 case glslang::EbtUint64:
8492 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8493 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008494 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008495 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008496 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008497 case glslang::EbtFloat16:
8498 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8499 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008500 case glslang::EbtReference:
8501 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8502 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8503 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008504#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008505 case glslang::EbtString:
8506 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8507 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008508 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008509 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008510 break;
8511 }
8512 ++nextConst;
8513 return scalar;
8514 }
8515
8516 return builder.makeCompositeConstant(typeId, spvConsts);
8517}
8518
John Kessenich7c1aa102015-10-15 13:29:11 -06008519// Return true if the node is a constant or symbol whose reading has no
8520// non-trivial observable cost or effect.
8521bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8522{
8523 // don't know what this is
8524 if (node == nullptr)
8525 return false;
8526
8527 // a constant is safe
8528 if (node->getAsConstantUnion() != nullptr)
8529 return true;
8530
8531 // not a symbol means non-trivial
8532 if (node->getAsSymbolNode() == nullptr)
8533 return false;
8534
8535 // a symbol, depends on what's being read
8536 switch (node->getType().getQualifier().storage) {
8537 case glslang::EvqTemporary:
8538 case glslang::EvqGlobal:
8539 case glslang::EvqIn:
8540 case glslang::EvqInOut:
8541 case glslang::EvqConst:
8542 case glslang::EvqConstReadOnly:
8543 case glslang::EvqUniform:
8544 return true;
8545 default:
8546 return false;
8547 }
qining25262b32016-05-06 17:25:16 -04008548}
John Kessenich7c1aa102015-10-15 13:29:11 -06008549
8550// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008551// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008552// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008553// Return true if trivial.
8554bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8555{
8556 if (node == nullptr)
8557 return false;
8558
John Kessenich84cc15f2017-05-24 16:44:47 -06008559 // count non scalars as trivial, as well as anything coming from HLSL
8560 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008561 return true;
8562
John Kessenich7c1aa102015-10-15 13:29:11 -06008563 // symbols and constants are trivial
8564 if (isTrivialLeaf(node))
8565 return true;
8566
8567 // otherwise, it needs to be a simple operation or one or two leaf nodes
8568
8569 // not a simple operation
8570 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8571 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8572 if (binaryNode == nullptr && unaryNode == nullptr)
8573 return false;
8574
8575 // not on leaf nodes
8576 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8577 return false;
8578
8579 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8580 return false;
8581 }
8582
8583 switch (node->getAsOperator()->getOp()) {
8584 case glslang::EOpLogicalNot:
8585 case glslang::EOpConvIntToBool:
8586 case glslang::EOpConvUintToBool:
8587 case glslang::EOpConvFloatToBool:
8588 case glslang::EOpConvDoubleToBool:
8589 case glslang::EOpEqual:
8590 case glslang::EOpNotEqual:
8591 case glslang::EOpLessThan:
8592 case glslang::EOpGreaterThan:
8593 case glslang::EOpLessThanEqual:
8594 case glslang::EOpGreaterThanEqual:
8595 case glslang::EOpIndexDirect:
8596 case glslang::EOpIndexDirectStruct:
8597 case glslang::EOpLogicalXor:
8598 case glslang::EOpAny:
8599 case glslang::EOpAll:
8600 return true;
8601 default:
8602 return false;
8603 }
8604}
8605
8606// Emit short-circuiting code, where 'right' is never evaluated unless
8607// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008608spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8609 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008610{
8611 spv::Id boolTypeId = builder.makeBoolType();
8612
8613 // emit left operand
8614 builder.clearAccessChain();
8615 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008616 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008617
8618 // Operands to accumulate OpPhi operands
8619 std::vector<spv::Id> phiOperands;
8620 // accumulate left operand's phi information
8621 phiOperands.push_back(leftId);
8622 phiOperands.push_back(builder.getBuildPoint()->getId());
8623
8624 // Make the two kinds of operation symmetric with a "!"
8625 // || => emit "if (! left) result = right"
8626 // && => emit "if ( left) result = right"
8627 //
8628 // TODO: this runtime "not" for || could be avoided by adding functionality
8629 // to 'builder' to have an "else" without an "then"
8630 if (op == glslang::EOpLogicalOr)
8631 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8632
8633 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008634 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008635
8636 // emit right operand as the "then" part of the "if"
8637 builder.clearAccessChain();
8638 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008639 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008640
8641 // accumulate left operand's phi information
8642 phiOperands.push_back(rightId);
8643 phiOperands.push_back(builder.getBuildPoint()->getId());
8644
8645 // finish the "if"
8646 ifBuilder.makeEndIf();
8647
8648 // phi together the two results
8649 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8650}
8651
John Kessenicha28f7a72019-08-06 07:00:58 -06008652#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008653// Return type Id of the imported set of extended instructions corresponds to the name.
8654// Import this set if it has not been imported yet.
8655spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8656{
8657 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8658 return extBuiltinMap[name];
8659 else {
Rex Xu51596642016-09-21 18:56:12 +08008660 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008661 spv::Id extBuiltins = builder.import(name);
8662 extBuiltinMap[name] = extBuiltins;
8663 return extBuiltins;
8664 }
8665}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008666#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008667
John Kessenich140f3df2015-06-26 16:58:36 -06008668}; // end anonymous namespace
8669
8670namespace glslang {
8671
John Kessenich68d78fd2015-07-12 19:28:10 -06008672void GetSpirvVersion(std::string& version)
8673{
John Kessenich9e55f632015-07-15 10:03:39 -06008674 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008675 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008676 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008677 version = buf;
8678}
8679
John Kessenicha372a3e2017-11-02 22:32:14 -06008680// For low-order part of the generator's magic number. Bump up
8681// when there is a change in the style (e.g., if SSA form changes,
8682// or a different instruction sequence to do something gets used).
8683int GetSpirvGeneratorVersion()
8684{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008685 // return 1; // start
8686 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008687 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008688 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008689 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008690 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8691 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008692 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenich3641ff72020-06-10 07:38:31 -06008693 // return 8; // switch to new dead block eliminator; use OpUnreachable
Graeme Leese060882f2020-06-22 11:03:46 +01008694 // return 9; // don't include opaque function parameters in OpEntryPoint global's operand list
8695 return 10; // Generate OpFUnordNotEqual for != comparisons
John Kessenicha372a3e2017-11-02 22:32:14 -06008696}
8697
John Kessenich140f3df2015-06-26 16:58:36 -06008698// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008699void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008700{
8701 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008702 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008703 if (out.fail())
8704 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008705 for (int i = 0; i < (int)spirv.size(); ++i) {
8706 unsigned int word = spirv[i];
8707 out.write((const char*)&word, 4);
8708 }
8709 out.close();
8710}
8711
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008712// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008713void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008714{
Shahbaz Youssefi1ef2e252020-07-03 15:42:53 -04008715#if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008716 std::ofstream out;
8717 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008718 if (out.fail())
8719 printf("ERROR: Failed to open file: %s\n", baseName);
Ben Claytonfbe9a232020-06-17 11:17:19 +01008720 out << "\t// " <<
8721 GetSpirvGeneratorVersion() <<
8722 GLSLANG_VERSION_MAJOR << "." << GLSLANG_VERSION_MINOR << "." << GLSLANG_VERSION_PATCH <<
8723 GLSLANG_VERSION_FLAVOR << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008724 if (varName != nullptr) {
8725 out << "\t #pragma once" << std::endl;
8726 out << "const uint32_t " << varName << "[] = {" << std::endl;
8727 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008728 const int WORDS_PER_LINE = 8;
8729 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8730 out << "\t";
8731 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8732 const unsigned int word = spirv[i + j];
8733 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8734 if (i + j + 1 < (int)spirv.size()) {
8735 out << ",";
8736 }
8737 }
8738 out << std::endl;
8739 }
Flavio15017db2017-02-15 14:29:33 -08008740 if (varName != nullptr) {
8741 out << "};";
johnkslangf881f082020-08-04 02:13:50 -06008742 out << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008743 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008744 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008745#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008746}
8747
John Kessenich140f3df2015-06-26 16:58:36 -06008748//
8749// Set up the glslang traversal
8750//
John Kessenich4e11b612018-08-30 16:56:59 -06008751void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008752{
Lei Zhang17535f72016-05-04 15:55:59 -04008753 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008754 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008755}
8756
John Kessenich4e11b612018-08-30 16:56:59 -06008757void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008758 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008759{
John Kessenich140f3df2015-06-26 16:58:36 -06008760 TIntermNode* root = intermediate.getTreeRoot();
8761
8762 if (root == 0)
8763 return;
8764
John Kessenich4e11b612018-08-30 16:56:59 -06008765 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008766 if (options == nullptr)
8767 options = &defaultOptions;
8768
John Kessenich4e11b612018-08-30 16:56:59 -06008769 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008770
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008771 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008772 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008773 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008774 it.dumpSpv(spirv);
8775
GregFfb03a552018-03-29 11:49:14 -06008776#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008777 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8778 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008779 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008780 if ((prelegalization || options->optimizeSize) && !options->disableOptimizer) {
8781 SpirvToolsTransform(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008782 prelegalization = false;
8783 }
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008784 else if (options->stripDebugInfo) {
8785 // Strip debug info even if optimization is disabled.
8786 SpirvToolsStripDebugInfo(intermediate, spirv, logger);
8787 }
John Kessenich717c80a2018-08-23 15:17:10 -06008788
John Kessenich4e11b612018-08-30 16:56:59 -06008789 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008790 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008791
John Kessenich717c80a2018-08-23 15:17:10 -06008792 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008793 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008794
GregFcd1f1692017-09-21 18:40:22 -06008795#endif
8796
John Kessenich4e11b612018-08-30 16:56:59 -06008797 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008798}
8799
8800}; // end namespace glslang