blob: 1d153c0dee1deac7f4828b30e22adbe1af1e2a55 [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.
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02002311 builder.accessChainStore(result,
2312 TranslateNonUniformDecoration(node->getOperand()->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06002313 builder.clearAccessChain();
2314 if (node->getOp() == glslang::EOpPreIncrement ||
2315 node->getOp() == glslang::EOpPreDecrement)
2316 builder.setAccessChainRValue(result);
2317 else
2318 builder.setAccessChainRValue(operand);
2319 }
2320
2321 return false;
2322
John Kessenich155d3512019-08-08 23:29:20 -06002323#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002324 case glslang::EOpEmitStreamVertex:
2325 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2326 return false;
2327 case glslang::EOpEndStreamPrimitive:
2328 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2329 return false;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002330 case glslang::EOpRayQueryTerminate:
2331 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operand);
2332 return false;
2333 case glslang::EOpRayQueryConfirmIntersection:
2334 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operand);
2335 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002336#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002337
2338 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002339 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002340 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002341 }
John Kessenich140f3df2015-06-26 16:58:36 -06002342}
2343
Jeff Bolz53134492019-06-25 13:31:10 -05002344// Construct a composite object, recursively copying members if their types don't match
2345spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2346{
2347 for (int c = 0; c < (int)constituents.size(); ++c) {
2348 spv::Id& constituent = constituents[c];
2349 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2350 spv::Id rType = builder.getTypeId(constituent);
2351 if (lType != rType) {
2352 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2353 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2354 } else if (builder.isStructType(rType)) {
2355 std::vector<spv::Id> rTypeConstituents;
2356 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2357 for (int i = 0; i < numrTypeConstituents; ++i) {
John Kessenich8985fc92020-03-03 10:25:07 -07002358 rTypeConstituents.push_back(builder.createCompositeExtract(constituent,
2359 builder.getContainedTypeId(rType, i), i));
Jeff Bolz53134492019-06-25 13:31:10 -05002360 }
2361 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2362 } else {
2363 assert(builder.isArrayType(rType));
2364 std::vector<spv::Id> rTypeConstituents;
2365 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2366
2367 spv::Id elementRType = builder.getContainedTypeId(rType);
2368 for (int i = 0; i < numrTypeConstituents; ++i) {
2369 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2370 }
2371 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2372 }
2373 }
2374 }
2375 return builder.createCompositeConstruct(resultTypeId, constituents);
2376}
2377
John Kessenich140f3df2015-06-26 16:58:36 -06002378bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2379{
qining27e04a02016-04-14 16:40:20 -04002380 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2381 if (node->getType().getQualifier().isSpecConstant())
2382 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2383
John Kessenichfc51d282015-08-19 13:34:18 -06002384 spv::Id result = spv::NoResult;
Cody Northrop4d2298b2020-04-13 21:59:49 -06002385 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2386 std::vector<spv::Builder::AccessChain> complexLvalues; // for holding swizzling l-values too complex for
2387 // SPIR-V, for an out parameter
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02002388 std::vector<glslang::TQualifier> complexLValueQualifiers;
Cody Northrop4d2298b2020-04-13 21:59:49 -06002389 std::vector<spv::Id> temporaryLvalues; // temporaries to pass, as proxies for complexLValues
John Kessenichbbbd9a22020-03-03 07:21:37 -07002390
John Kessenich8985fc92020-03-03 10:25:07 -07002391 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2392 invertedType :
2393 convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002394
2395 // try texturing
2396 result = createImageTextureFunctionCall(node);
2397 if (result != spv::NoResult) {
2398 builder.clearAccessChain();
2399 builder.setAccessChainRValue(result);
2400
2401 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002402 }
2403#ifndef GLSLANG_WEB
2404 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002405 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002406 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002407 // "imageStore" is a special case, which has no result
2408 return false;
2409 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002410#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002411
John Kessenich140f3df2015-06-26 16:58:36 -06002412 glslang::TOperator binOp = glslang::EOpNull;
2413 bool reduceComparison = true;
2414 bool isMatrix = false;
2415 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002416 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002417
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002418 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2419
John Kessenich140f3df2015-06-26 16:58:36 -06002420 assert(node->getOp());
2421
John Kessenichf6640762016-08-01 19:44:00 -06002422 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002423
2424 switch (node->getOp()) {
2425 case glslang::EOpSequence:
2426 {
2427 if (preVisit)
2428 ++sequenceDepth;
2429 else
2430 --sequenceDepth;
2431
2432 if (sequenceDepth == 1) {
2433 // If this is the parent node of all the functions, we want to see them
2434 // early, so all call points have actual SPIR-V functions to reference.
2435 // In all cases, still let the traverser visit the children for us.
2436 makeFunctions(node->getAsAggregate()->getSequence());
2437
John Kessenich6fccb3c2016-09-19 16:01:41 -06002438 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002439 // anything else gets there, so visit out of order, doing them all now.
2440 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2441
John Kessenich6a60c2f2016-12-08 21:01:59 -07002442 // 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 -06002443 // so do them manually.
2444 visitFunctions(node->getAsAggregate()->getSequence());
2445
2446 return false;
2447 }
2448
2449 return true;
2450 }
2451 case glslang::EOpLinkerObjects:
2452 {
2453 if (visit == glslang::EvPreVisit)
2454 linkageOnly = true;
2455 else
2456 linkageOnly = false;
2457
2458 return true;
2459 }
2460 case glslang::EOpComma:
2461 {
2462 // processing from left to right naturally leaves the right-most
2463 // lying around in the access chain
2464 glslang::TIntermSequence& glslangOperands = node->getSequence();
2465 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2466 glslangOperands[i]->traverse(this);
2467
2468 return false;
2469 }
2470 case glslang::EOpFunction:
2471 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002472 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002473 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002474 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002475 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002476 } else {
2477 handleFunctionEntry(node);
2478 }
2479 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002480 if (inEntryPoint)
2481 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002482 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002483 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002484 }
2485
2486 return true;
2487 case glslang::EOpParameters:
2488 // Parameters will have been consumed by EOpFunction processing, but not
2489 // the body, so we still visited the function node's children, making this
2490 // child redundant.
2491 return false;
2492 case glslang::EOpFunctionCall:
2493 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002494 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002495 if (node->isUserDefined())
2496 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07002497 if (result) {
2498 builder.clearAccessChain();
2499 builder.setAccessChainRValue(result);
2500 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002501 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002502
2503 return false;
2504 }
2505 case glslang::EOpConstructMat2x2:
2506 case glslang::EOpConstructMat2x3:
2507 case glslang::EOpConstructMat2x4:
2508 case glslang::EOpConstructMat3x2:
2509 case glslang::EOpConstructMat3x3:
2510 case glslang::EOpConstructMat3x4:
2511 case glslang::EOpConstructMat4x2:
2512 case glslang::EOpConstructMat4x3:
2513 case glslang::EOpConstructMat4x4:
2514 case glslang::EOpConstructDMat2x2:
2515 case glslang::EOpConstructDMat2x3:
2516 case glslang::EOpConstructDMat2x4:
2517 case glslang::EOpConstructDMat3x2:
2518 case glslang::EOpConstructDMat3x3:
2519 case glslang::EOpConstructDMat3x4:
2520 case glslang::EOpConstructDMat4x2:
2521 case glslang::EOpConstructDMat4x3:
2522 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002523 case glslang::EOpConstructIMat2x2:
2524 case glslang::EOpConstructIMat2x3:
2525 case glslang::EOpConstructIMat2x4:
2526 case glslang::EOpConstructIMat3x2:
2527 case glslang::EOpConstructIMat3x3:
2528 case glslang::EOpConstructIMat3x4:
2529 case glslang::EOpConstructIMat4x2:
2530 case glslang::EOpConstructIMat4x3:
2531 case glslang::EOpConstructIMat4x4:
2532 case glslang::EOpConstructUMat2x2:
2533 case glslang::EOpConstructUMat2x3:
2534 case glslang::EOpConstructUMat2x4:
2535 case glslang::EOpConstructUMat3x2:
2536 case glslang::EOpConstructUMat3x3:
2537 case glslang::EOpConstructUMat3x4:
2538 case glslang::EOpConstructUMat4x2:
2539 case glslang::EOpConstructUMat4x3:
2540 case glslang::EOpConstructUMat4x4:
2541 case glslang::EOpConstructBMat2x2:
2542 case glslang::EOpConstructBMat2x3:
2543 case glslang::EOpConstructBMat2x4:
2544 case glslang::EOpConstructBMat3x2:
2545 case glslang::EOpConstructBMat3x3:
2546 case glslang::EOpConstructBMat3x4:
2547 case glslang::EOpConstructBMat4x2:
2548 case glslang::EOpConstructBMat4x3:
2549 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002550 case glslang::EOpConstructF16Mat2x2:
2551 case glslang::EOpConstructF16Mat2x3:
2552 case glslang::EOpConstructF16Mat2x4:
2553 case glslang::EOpConstructF16Mat3x2:
2554 case glslang::EOpConstructF16Mat3x3:
2555 case glslang::EOpConstructF16Mat3x4:
2556 case glslang::EOpConstructF16Mat4x2:
2557 case glslang::EOpConstructF16Mat4x3:
2558 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002559 isMatrix = true;
2560 // fall through
2561 case glslang::EOpConstructFloat:
2562 case glslang::EOpConstructVec2:
2563 case glslang::EOpConstructVec3:
2564 case glslang::EOpConstructVec4:
2565 case glslang::EOpConstructDouble:
2566 case glslang::EOpConstructDVec2:
2567 case glslang::EOpConstructDVec3:
2568 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002569 case glslang::EOpConstructFloat16:
2570 case glslang::EOpConstructF16Vec2:
2571 case glslang::EOpConstructF16Vec3:
2572 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002573 case glslang::EOpConstructBool:
2574 case glslang::EOpConstructBVec2:
2575 case glslang::EOpConstructBVec3:
2576 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002577 case glslang::EOpConstructInt8:
2578 case glslang::EOpConstructI8Vec2:
2579 case glslang::EOpConstructI8Vec3:
2580 case glslang::EOpConstructI8Vec4:
2581 case glslang::EOpConstructUint8:
2582 case glslang::EOpConstructU8Vec2:
2583 case glslang::EOpConstructU8Vec3:
2584 case glslang::EOpConstructU8Vec4:
2585 case glslang::EOpConstructInt16:
2586 case glslang::EOpConstructI16Vec2:
2587 case glslang::EOpConstructI16Vec3:
2588 case glslang::EOpConstructI16Vec4:
2589 case glslang::EOpConstructUint16:
2590 case glslang::EOpConstructU16Vec2:
2591 case glslang::EOpConstructU16Vec3:
2592 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002593 case glslang::EOpConstructInt:
2594 case glslang::EOpConstructIVec2:
2595 case glslang::EOpConstructIVec3:
2596 case glslang::EOpConstructIVec4:
2597 case glslang::EOpConstructUint:
2598 case glslang::EOpConstructUVec2:
2599 case glslang::EOpConstructUVec3:
2600 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002601 case glslang::EOpConstructInt64:
2602 case glslang::EOpConstructI64Vec2:
2603 case glslang::EOpConstructI64Vec3:
2604 case glslang::EOpConstructI64Vec4:
2605 case glslang::EOpConstructUint64:
2606 case glslang::EOpConstructU64Vec2:
2607 case glslang::EOpConstructU64Vec3:
2608 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002609 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002610 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002611 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002612 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002613 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002614 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002615 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002616 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002617 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002618 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002619 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002620 else if (node->getOp() == glslang::EOpConstructStruct ||
2621 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2622 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002623 std::vector<spv::Id> constituents;
2624 for (int c = 0; c < (int)arguments.size(); ++c)
2625 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002626 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002627 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002628 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002629 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002630 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002631
Bas Nieuwenhuizenc9ffeec2020-09-03 03:09:39 +02002632 if (node->getType().getQualifier().isNonUniform()) {
2633 builder.addDecoration(constructed, spv::DecorationNonUniformEXT);
2634 }
2635
John Kessenich140f3df2015-06-26 16:58:36 -06002636 builder.clearAccessChain();
2637 builder.setAccessChainRValue(constructed);
2638
2639 return false;
2640 }
2641
2642 // These six are component-wise compares with component-wise results.
2643 // Forward on to createBinaryOperation(), requesting a vector result.
2644 case glslang::EOpLessThan:
2645 case glslang::EOpGreaterThan:
2646 case glslang::EOpLessThanEqual:
2647 case glslang::EOpGreaterThanEqual:
2648 case glslang::EOpVectorEqual:
2649 case glslang::EOpVectorNotEqual:
2650 {
2651 // Map the operation to a binary
2652 binOp = node->getOp();
2653 reduceComparison = false;
2654 switch (node->getOp()) {
2655 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2656 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2657 default: binOp = node->getOp(); break;
2658 }
2659
2660 break;
2661 }
2662 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002663 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002664 binOp = glslang::EOpMul;
2665 break;
2666 case glslang::EOpOuterProduct:
2667 // two vectors multiplied to make a matrix
2668 binOp = glslang::EOpOuterProduct;
2669 break;
2670 case glslang::EOpDot:
2671 {
qining25262b32016-05-06 17:25:16 -04002672 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002673 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002674 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002675 binOp = glslang::EOpMul;
2676 break;
2677 }
2678 case glslang::EOpMod:
2679 // when an aggregate, this is the floating-point mod built-in function,
2680 // which can be emitted by the one in createBinaryOperation()
2681 binOp = glslang::EOpMod;
2682 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002683
John Kessenich140f3df2015-06-26 16:58:36 -06002684 case glslang::EOpEmitVertex:
2685 case glslang::EOpEndPrimitive:
2686 case glslang::EOpBarrier:
2687 case glslang::EOpMemoryBarrier:
2688 case glslang::EOpMemoryBarrierAtomicCounter:
2689 case glslang::EOpMemoryBarrierBuffer:
2690 case glslang::EOpMemoryBarrierImage:
2691 case glslang::EOpMemoryBarrierShared:
2692 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002693 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002694 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002695 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002696 case glslang::EOpWorkgroupMemoryBarrier:
2697 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002698 case glslang::EOpSubgroupBarrier:
2699 case glslang::EOpSubgroupMemoryBarrier:
2700 case glslang::EOpSubgroupMemoryBarrierBuffer:
2701 case glslang::EOpSubgroupMemoryBarrierImage:
2702 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002703 noReturnValue = true;
2704 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2705 break;
2706
John Kessenich426394d2015-07-23 10:22:48 -06002707 case glslang::EOpAtomicAdd:
2708 case glslang::EOpAtomicMin:
2709 case glslang::EOpAtomicMax:
2710 case glslang::EOpAtomicAnd:
2711 case glslang::EOpAtomicOr:
2712 case glslang::EOpAtomicXor:
2713 case glslang::EOpAtomicExchange:
2714 case glslang::EOpAtomicCompSwap:
2715 atomic = true;
2716 break;
2717
John Kesseniche5eee8f2019-10-18 01:03:11 -06002718#ifndef GLSLANG_WEB
2719 case glslang::EOpAtomicStore:
2720 noReturnValue = true;
2721 // fallthrough
2722 case glslang::EOpAtomicLoad:
2723 atomic = true;
2724 break;
2725
John Kessenich0d0c6d32017-07-23 16:08:26 -06002726 case glslang::EOpAtomicCounterAdd:
2727 case glslang::EOpAtomicCounterSubtract:
2728 case glslang::EOpAtomicCounterMin:
2729 case glslang::EOpAtomicCounterMax:
2730 case glslang::EOpAtomicCounterAnd:
2731 case glslang::EOpAtomicCounterOr:
2732 case glslang::EOpAtomicCounterXor:
2733 case glslang::EOpAtomicCounterExchange:
2734 case glslang::EOpAtomicCounterCompSwap:
2735 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2736 builder.addCapability(spv::CapabilityAtomicStorageOps);
2737 atomic = true;
2738 break;
2739
Ian Romanickb3bd4022019-01-21 08:57:25 -08002740 case glslang::EOpAbsDifference:
2741 case glslang::EOpAddSaturate:
2742 case glslang::EOpSubSaturate:
2743 case glslang::EOpAverage:
2744 case glslang::EOpAverageRounded:
2745 case glslang::EOpMul32x16:
2746 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2747 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2748 binOp = node->getOp();
2749 break;
2750
Daniel Kochdb32b242020-03-17 20:42:47 -04002751 case glslang::EOpIgnoreIntersection:
2752 case glslang::EOpTerminateRay:
2753 case glslang::EOpTrace:
2754 case glslang::EOpExecuteCallable:
Chao Chen3c366992018-09-19 11:41:59 -07002755 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2756 noReturnValue = true;
2757 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04002758 case glslang::EOpRayQueryInitialize:
2759 case glslang::EOpRayQueryTerminate:
2760 case glslang::EOpRayQueryGenerateIntersection:
2761 case glslang::EOpRayQueryConfirmIntersection:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002762 builder.addExtension("SPV_KHR_ray_query");
2763 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
Torosdagli06c2eee2020-03-19 11:09:57 -04002764 noReturnValue = true;
2765 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002766 case glslang::EOpRayQueryProceed:
2767 case glslang::EOpRayQueryGetIntersectionType:
2768 case glslang::EOpRayQueryGetRayTMin:
2769 case glslang::EOpRayQueryGetRayFlags:
2770 case glslang::EOpRayQueryGetIntersectionT:
2771 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2772 case glslang::EOpRayQueryGetIntersectionInstanceId:
2773 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2774 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2775 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2776 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2777 case glslang::EOpRayQueryGetIntersectionFrontFace:
2778 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
2779 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2780 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2781 case glslang::EOpRayQueryGetWorldRayDirection:
2782 case glslang::EOpRayQueryGetWorldRayOrigin:
2783 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2784 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2785 builder.addExtension("SPV_KHR_ray_query");
2786 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
2787 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002788 case glslang::EOpCooperativeMatrixLoad:
2789 case glslang::EOpCooperativeMatrixStore:
2790 noReturnValue = true;
2791 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002792 case glslang::EOpBeginInvocationInterlock:
2793 case glslang::EOpEndInvocationInterlock:
2794 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2795 noReturnValue = true;
2796 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002797#endif
Chao Chen3c366992018-09-19 11:41:59 -07002798
Jeff Bolz04d73732019-05-31 13:06:01 -05002799 case glslang::EOpDebugPrintf:
2800 noReturnValue = true;
2801 break;
2802
John Kessenich140f3df2015-06-26 16:58:36 -06002803 default:
2804 break;
2805 }
2806
2807 //
2808 // See if it maps to a regular operation.
2809 //
John Kessenich140f3df2015-06-26 16:58:36 -06002810 if (binOp != glslang::EOpNull) {
2811 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2812 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2813 assert(left && right);
2814
2815 builder.clearAccessChain();
2816 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002817 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002818
2819 builder.clearAccessChain();
2820 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002821 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002822
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002823 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002824 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002825 TranslateNoContractionDecoration(node->getType().getQualifier()),
2826 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002827 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002828 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002829 left->getType().getBasicType(), reduceComparison);
2830
2831 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002832 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002833 builder.clearAccessChain();
2834 builder.setAccessChainRValue(result);
2835
2836 return false;
2837 }
2838
John Kessenich426394d2015-07-23 10:22:48 -06002839 //
2840 // Create the list of operands.
2841 //
John Kessenich140f3df2015-06-26 16:58:36 -06002842 glslang::TIntermSequence& glslangOperands = node->getSequence();
2843 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002844 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002845 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002846 // special case l-value operands; there are just a few
2847 bool lvalue = false;
2848 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002849 case glslang::EOpModf:
2850 if (arg == 1)
2851 lvalue = true;
2852 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002853
Torosdagli06c2eee2020-03-19 11:09:57 -04002854 case glslang::EOpRayQueryInitialize:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002855 case glslang::EOpRayQueryTerminate:
2856 case glslang::EOpRayQueryConfirmIntersection:
2857 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04002858 case glslang::EOpRayQueryGenerateIntersection:
2859 case glslang::EOpRayQueryGetIntersectionType:
2860 case glslang::EOpRayQueryGetIntersectionT:
2861 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2862 case glslang::EOpRayQueryGetIntersectionInstanceId:
2863 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2864 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2865 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2866 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2867 case glslang::EOpRayQueryGetIntersectionFrontFace:
2868 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2869 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2870 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2871 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2872 if (arg == 0)
2873 lvalue = true;
2874 break;
2875
John Kesseniche5eee8f2019-10-18 01:03:11 -06002876 case glslang::EOpAtomicAdd:
2877 case glslang::EOpAtomicMin:
2878 case glslang::EOpAtomicMax:
2879 case glslang::EOpAtomicAnd:
2880 case glslang::EOpAtomicOr:
2881 case glslang::EOpAtomicXor:
2882 case glslang::EOpAtomicExchange:
2883 case glslang::EOpAtomicCompSwap:
2884 if (arg == 0)
2885 lvalue = true;
2886 break;
2887
John Kessenicha28f7a72019-08-06 07:00:58 -06002888#ifndef GLSLANG_WEB
2889 case glslang::EOpFrexp:
2890 if (arg == 1)
2891 lvalue = true;
2892 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002893 case glslang::EOpInterpolateAtSample:
2894 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002895 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002896 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002897 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002898
2899 // Does it need a swizzle inversion? If so, evaluation is inverted;
2900 // operate first on the swizzle base, then apply the swizzle.
John Kessenichbbbd9a22020-03-03 07:21:37 -07002901 // That is, we transform
2902 //
2903 // interpolate(v.zy) -> interpolate(v).zy
2904 //
John Kessenichecba76f2017-01-06 00:34:48 -07002905 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002906 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
John Kessenich8985fc92020-03-03 10:25:07 -07002907 invertedType = convertGlslangToSpvType(
2908 glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
John Kessenich8c8505c2016-07-26 12:50:38 -06002909 }
Rex Xu7a26c172015-12-08 17:12:09 +08002910 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002911 case glslang::EOpAtomicLoad:
2912 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002913 case glslang::EOpAtomicCounterAdd:
2914 case glslang::EOpAtomicCounterSubtract:
2915 case glslang::EOpAtomicCounterMin:
2916 case glslang::EOpAtomicCounterMax:
2917 case glslang::EOpAtomicCounterAnd:
2918 case glslang::EOpAtomicCounterOr:
2919 case glslang::EOpAtomicCounterXor:
2920 case glslang::EOpAtomicCounterExchange:
2921 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002922 if (arg == 0)
2923 lvalue = true;
2924 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002925 case glslang::EOpAddCarry:
2926 case glslang::EOpSubBorrow:
2927 if (arg == 2)
2928 lvalue = true;
2929 break;
2930 case glslang::EOpUMulExtended:
2931 case glslang::EOpIMulExtended:
2932 if (arg >= 2)
2933 lvalue = true;
2934 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002935 case glslang::EOpCooperativeMatrixLoad:
2936 if (arg == 0 || arg == 1)
2937 lvalue = true;
2938 break;
2939 case glslang::EOpCooperativeMatrixStore:
2940 if (arg == 1)
2941 lvalue = true;
2942 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002943#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002944 default:
2945 break;
2946 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002947 builder.clearAccessChain();
2948 if (invertedType != spv::NoType && arg == 0)
2949 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2950 else
2951 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002952
John Kessenichb9197c82019-08-11 07:41:45 -06002953#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002954 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2955 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2956
2957 if (arg == 1) {
2958 // fold "element" parameter into the access chain
2959 spv::Builder::AccessChain save = builder.getAccessChain();
2960 builder.clearAccessChain();
2961 glslangOperands[2]->traverse(this);
2962
2963 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2964
2965 builder.setAccessChain(save);
2966
2967 // Point to the first element of the array.
John Kessenich8985fc92020-03-03 10:25:07 -07002968 builder.accessChainPush(elementId,
2969 TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
2970 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002971
2972 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2973 unsigned int alignment = builder.getAccessChain().alignment;
2974
2975 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2976 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2977 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2978 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2979 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
John Kessenich8985fc92020-03-03 10:25:07 -07002980 if (builder.getStorageClass(builder.getAccessChain().base) ==
2981 spv::StorageClassPhysicalStorageBufferEXT) {
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002982 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2983 }
2984
2985 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2986
2987 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2988 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2989 }
2990
John Kessenich8985fc92020-03-03 10:25:07 -07002991 if (memoryAccess &
2992 (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2993 memoryAccessOperands.push_back(spv::IdImmediate(true,
2994 builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002995 }
2996 } else if (arg == 2) {
2997 continue;
2998 }
2999 }
John Kessenichb9197c82019-08-11 07:41:45 -06003000#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003001
John Kessenichbbbd9a22020-03-03 07:21:37 -07003002 // for l-values, pass the address, for r-values, pass the value
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003003 if (lvalue) {
John Kessenichbbbd9a22020-03-03 07:21:37 -07003004 if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
3005 // SPIR-V cannot represent an l-value containing a swizzle that doesn't
3006 // reduce to a simple access chain. So, we need a temporary vector to
3007 // receive the result, and must later swizzle that into the original
3008 // l-value.
Cody Northrop4d2298b2020-04-13 21:59:49 -06003009 complexLvalues.push_back(builder.getAccessChain());
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02003010 complexLValueQualifiers.push_back(glslangOperands[arg]->getAsTyped()->getType().getQualifier());
John Kessenich435dd802020-06-30 01:27:08 -06003011 temporaryLvalues.push_back(builder.createVariable(
3012 spv::NoPrecision, spv::StorageClassFunction,
Cody Northrop4d2298b2020-04-13 21:59:49 -06003013 builder.accessChainGetInferredType(), "swizzleTemp"));
3014 operands.push_back(temporaryLvalues.back());
John Kessenichbbbd9a22020-03-03 07:21:37 -07003015 } else {
3016 operands.push_back(builder.accessChainGetLValue());
3017 }
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003018 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
3019 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
3020 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003021 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Torosdagli06c2eee2020-03-19 11:09:57 -04003022 glslang::TOperator glslangOp = node->getOp();
3023 if (arg == 1 &&
3024 (glslangOp == glslang::EOpRayQueryGetIntersectionType ||
3025 glslangOp == glslang::EOpRayQueryGetIntersectionT ||
3026 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceCustomIndex ||
3027 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceId ||
3028 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset ||
3029 glslangOp == glslang::EOpRayQueryGetIntersectionGeometryIndex ||
3030 glslangOp == glslang::EOpRayQueryGetIntersectionPrimitiveIndex ||
3031 glslangOp == glslang::EOpRayQueryGetIntersectionBarycentrics ||
3032 glslangOp == glslang::EOpRayQueryGetIntersectionFrontFace ||
3033 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayDirection ||
3034 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayOrigin ||
3035 glslangOp == glslang::EOpRayQueryGetIntersectionObjectToWorld ||
3036 glslangOp == glslang::EOpRayQueryGetIntersectionWorldToObject
3037 )) {
3038 bool cond = glslangOperands[arg]->getAsConstantUnion()->getConstArray()[0].getBConst();
3039 operands.push_back(builder.makeIntConstant(cond ? 1 : 0));
3040 }
3041 else {
3042 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
3043 }
3044
John Kesseniche485c7a2017-05-31 18:50:53 -06003045 }
John Kessenich140f3df2015-06-26 16:58:36 -06003046 }
John Kessenich426394d2015-07-23 10:22:48 -06003047
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003048 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06003049#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003050 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
3051 std::vector<spv::IdImmediate> idImmOps;
3052
3053 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3054 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3055 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3056 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3057 // get the pointee type
3058 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
3059 assert(builder.isCooperativeMatrixType(typeId));
3060 // do the op
3061 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
3062 // store the result to the pointer (out param 'm')
3063 builder.createStore(result, operands[0]);
3064 result = 0;
3065 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
3066 std::vector<spv::IdImmediate> idImmOps;
3067
3068 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3069 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
3070 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3071 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3072 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3073
3074 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
3075 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06003076 } else
3077#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06003078 if (atomic) {
3079 // Handle all atomics
John Kessenich8985fc92020-03-03 10:25:07 -07003080 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
3081 lvalueCoherentFlags);
Jeff Bolz04d73732019-05-31 13:06:01 -05003082 } else if (node->getOp() == glslang::EOpDebugPrintf) {
3083 if (!nonSemanticDebugPrintf) {
3084 nonSemanticDebugPrintf = builder.import("NonSemantic.DebugPrintf");
3085 }
3086 result = builder.createBuiltinCall(builder.makeVoidType(), nonSemanticDebugPrintf, spv::NonSemanticDebugPrintfDebugPrintf, operands);
3087 builder.addExtension(spv::E_SPV_KHR_non_semantic_info);
John Kesseniche5eee8f2019-10-18 01:03:11 -06003088 } else {
John Kessenich426394d2015-07-23 10:22:48 -06003089 // Pass through to generic operations.
3090 switch (glslangOperands.size()) {
3091 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06003092 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06003093 break;
3094 case 1:
John Kessenichead86222018-03-28 18:01:20 -06003095 {
3096 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06003097 TranslateNoContractionDecoration(node->getType().getQualifier()),
3098 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06003099 result = createUnaryOperation(
3100 node->getOp(), decorations,
3101 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003102 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06003103 }
John Kessenich426394d2015-07-23 10:22:48 -06003104 break;
3105 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06003106 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06003107 break;
3108 }
Cody Northrop4d2298b2020-04-13 21:59:49 -06003109
John Kessenichbbbd9a22020-03-03 07:21:37 -07003110 if (invertedType != spv::NoResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003111 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
Cody Northrop4d2298b2020-04-13 21:59:49 -06003112
3113 for (unsigned int i = 0; i < temporaryLvalues.size(); ++i) {
3114 builder.setAccessChain(complexLvalues[i]);
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02003115 builder.accessChainStore(builder.createLoad(temporaryLvalues[i], spv::NoPrecision), TranslateNonUniformDecoration(complexLValueQualifiers[i]));
John Kessenichbbbd9a22020-03-03 07:21:37 -07003116 }
John Kessenich140f3df2015-06-26 16:58:36 -06003117 }
3118
3119 if (noReturnValue)
3120 return false;
3121
3122 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04003123 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07003124 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06003125 } else {
3126 builder.clearAccessChain();
3127 builder.setAccessChainRValue(result);
3128 return false;
3129 }
3130}
3131
John Kessenich433e9ff2017-01-26 20:31:11 -07003132// This path handles both if-then-else and ?:
3133// The if-then-else has a node type of void, while
3134// ?: has either a void or a non-void node type
3135//
3136// Leaving the result, when not void:
3137// GLSL only has r-values as the result of a :?, but
3138// if we have an l-value, that can be more efficient if it will
3139// become the base of a complex r-value expression, because the
3140// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06003141bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
3142{
John Kessenich0c1e71a2019-01-10 18:23:06 +07003143 // see if OpSelect can handle it
3144 const auto isOpSelectable = [&]() {
3145 if (node->getBasicType() == glslang::EbtVoid)
3146 return false;
3147 // OpSelect can do all other types starting with SPV 1.4
3148 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
3149 // pre-1.4, only scalars and vectors can be handled
3150 if ((!node->getType().isScalar() && !node->getType().isVector()))
3151 return false;
3152 }
3153 return true;
3154 };
3155
John Kessenich4bee5312018-02-20 21:29:05 -07003156 // See if it simple and safe, or required, to execute both sides.
3157 // Crucially, side effects must be either semantically required or avoided,
3158 // and there are performance trade-offs.
3159 // Return true if required or a good idea (and safe) to execute both sides,
3160 // false otherwise.
3161 const auto bothSidesPolicy = [&]() -> bool {
3162 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07003163 if (node->getTrueBlock() == nullptr ||
3164 node->getFalseBlock() == nullptr)
3165 return false;
3166
John Kessenich4bee5312018-02-20 21:29:05 -07003167 // required? (unless we write additional code to look for side effects
3168 // and make performance trade-offs if none are present)
3169 if (!node->getShortCircuit())
3170 return true;
3171
3172 // if not required to execute both, decide based on performance/practicality...
3173
John Kessenich0c1e71a2019-01-10 18:23:06 +07003174 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07003175 return false;
3176
John Kessenich433e9ff2017-01-26 20:31:11 -07003177 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
3178 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
3179
3180 // return true if a single operand to ? : is okay for OpSelect
3181 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003182 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07003183 };
3184
3185 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
3186 operandOkay(node->getFalseBlock()->getAsTyped());
3187 };
3188
John Kessenich4bee5312018-02-20 21:29:05 -07003189 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
3190 // emit the condition before doing anything with selection
3191 node->getCondition()->traverse(this);
3192 spv::Id condition = accessChainLoad(node->getCondition()->getType());
3193
3194 // Find a way of executing both sides and selecting the right result.
3195 const auto executeBothSides = [&]() -> void {
3196 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07003197 node->getTrueBlock()->traverse(this);
3198 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3199 node->getFalseBlock()->traverse(this);
3200 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3201
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003202 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003203
John Kessenich4bee5312018-02-20 21:29:05 -07003204 // done if void
3205 if (node->getBasicType() == glslang::EbtVoid)
3206 return;
John Kesseniche434ad92017-03-30 10:09:28 -06003207
John Kessenich4bee5312018-02-20 21:29:05 -07003208 // emit code to select between trueValue and falseValue
3209
3210 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07003211 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07003212 // Emit OpSelect for this selection.
3213
3214 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07003215 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
3216 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07003217 condition = builder.smearScalar(spv::NoPrecision, condition,
3218 builder.makeVectorType(builder.makeBoolType(),
3219 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07003220 }
John Kessenich4bee5312018-02-20 21:29:05 -07003221
3222 // OpSelect
3223 result = builder.createTriOp(spv::OpSelect,
3224 convertGlslangToSpvType(node->getType()), condition,
3225 trueValue, falseValue);
3226
3227 builder.clearAccessChain();
3228 builder.setAccessChainRValue(result);
3229 } else {
3230 // We need control flow to select the result.
3231 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
John Kessenich435dd802020-06-30 01:27:08 -06003232 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()),
3233 spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich4bee5312018-02-20 21:29:05 -07003234
3235 // Selection control:
3236 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3237
3238 // make an "if" based on the value created by the condition
3239 spv::Builder::If ifBuilder(condition, control, builder);
3240
3241 // emit the "then" statement
3242 builder.createStore(trueValue, result);
3243 ifBuilder.makeBeginElse();
3244 // emit the "else" statement
3245 builder.createStore(falseValue, result);
3246
3247 // finish off the control flow
3248 ifBuilder.makeEndIf();
3249
3250 builder.clearAccessChain();
3251 builder.setAccessChainLValue(result);
3252 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003253 };
3254
John Kessenich4bee5312018-02-20 21:29:05 -07003255 // Execute the one side needed, as per the condition
3256 const auto executeOneSide = [&]() {
3257 // Always emit control flow.
John Kessenich435dd802020-06-30 01:27:08 -06003258 if (node->getBasicType() != glslang::EbtVoid) {
3259 result = builder.createVariable(TranslatePrecisionDecoration(node->getType()), spv::StorageClassFunction,
3260 convertGlslangToSpvType(node->getType()));
3261 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003262
John Kessenich4bee5312018-02-20 21:29:05 -07003263 // Selection control:
3264 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3265
3266 // make an "if" based on the value created by the condition
3267 spv::Builder::If ifBuilder(condition, control, builder);
3268
3269 // emit the "then" statement
3270 if (node->getTrueBlock() != nullptr) {
3271 node->getTrueBlock()->traverse(this);
3272 if (result != spv::NoResult)
3273 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3274 }
3275
3276 if (node->getFalseBlock() != nullptr) {
3277 ifBuilder.makeBeginElse();
3278 // emit the "else" statement
3279 node->getFalseBlock()->traverse(this);
3280 if (result != spv::NoResult)
3281 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3282 }
3283
3284 // finish off the control flow
3285 ifBuilder.makeEndIf();
3286
3287 if (result != spv::NoResult) {
3288 builder.clearAccessChain();
3289 builder.setAccessChainLValue(result);
3290 }
3291 };
3292
3293 // Try for OpSelect (or a requirement to execute both sides)
3294 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003295 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3296 if (node->getType().getQualifier().isSpecConstant())
3297 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003298 executeBothSides();
3299 } else
3300 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003301
3302 return false;
3303}
3304
3305bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3306{
3307 // emit and get the condition before doing anything with switch
3308 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003309 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003310
Rex Xu57e65922017-07-04 23:23:40 +08003311 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003312 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003313
John Kessenich140f3df2015-06-26 16:58:36 -06003314 // browse the children to sort out code segments
3315 int defaultSegment = -1;
3316 std::vector<TIntermNode*> codeSegments;
3317 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3318 std::vector<int> caseValues;
3319 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3320 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3321 TIntermNode* child = *c;
3322 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003323 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003324 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003325 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich8985fc92020-03-03 10:25:07 -07003326 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()
3327 ->getConstArray()[0].getIConst());
John Kessenich140f3df2015-06-26 16:58:36 -06003328 } else
3329 codeSegments.push_back(child);
3330 }
3331
qining25262b32016-05-06 17:25:16 -04003332 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003333 // statements between the last case and the end of the switch statement
3334 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3335 (int)codeSegments.size() == defaultSegment)
3336 codeSegments.push_back(nullptr);
3337
3338 // make the switch statement
3339 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
John Kessenich8985fc92020-03-03 10:25:07 -07003340 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment,
3341 segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003342
3343 // emit all the code in the segments
3344 breakForLoop.push(false);
3345 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3346 builder.nextSwitchSegment(segmentBlocks, s);
3347 if (codeSegments[s])
3348 codeSegments[s]->traverse(this);
3349 else
3350 builder.addSwitchBreak();
3351 }
3352 breakForLoop.pop();
3353
3354 builder.endSwitch(segmentBlocks);
3355
3356 return false;
3357}
3358
3359void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3360{
3361 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003362 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003363
3364 builder.clearAccessChain();
3365 builder.setAccessChainRValue(constant);
3366}
3367
3368bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3369{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003370 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003371 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003372
3373 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003374 std::vector<unsigned int> operands;
3375 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003376
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003377 // Spec requires back edges to target header blocks, and every header block
3378 // must dominate its merge block. Make a header block first to ensure these
3379 // conditions are met. By definition, it will contain OpLoopMerge, followed
3380 // by a block-ending branch. But we don't want to put any other body/test
3381 // instructions in it, since the body/test may have arbitrary instructions,
3382 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003383 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003384 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003385 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003386 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003387 spv::Block& test = builder.makeNewBlock();
3388 builder.createBranch(&test);
3389
3390 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003391 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003392 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003393 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3394
3395 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003396 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003397 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003398 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003399 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003400 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003401
3402 builder.setBuildPoint(&blocks.continue_target);
3403 if (node->getTerminal())
3404 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003405 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003406 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003407 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003408 builder.createBranch(&blocks.body);
3409
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003410 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003411 builder.setBuildPoint(&blocks.body);
3412 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003413 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003414 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003415 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003416
3417 builder.setBuildPoint(&blocks.continue_target);
3418 if (node->getTerminal())
3419 node->getTerminal()->traverse(this);
3420 if (node->getTest()) {
3421 node->getTest()->traverse(this);
3422 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003423 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003424 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003425 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003426 // TODO: unless there was a break/return/discard instruction
3427 // somewhere in the body, this is an infinite loop, so we should
3428 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003429 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003430 }
John Kessenich140f3df2015-06-26 16:58:36 -06003431 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003432 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003433 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003434 return false;
3435}
3436
3437bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3438{
3439 if (node->getExpression())
3440 node->getExpression()->traverse(this);
3441
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003442 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003443
John Kessenich140f3df2015-06-26 16:58:36 -06003444 switch (node->getFlowOp()) {
3445 case glslang::EOpKill:
3446 builder.makeDiscard();
3447 break;
3448 case glslang::EOpBreak:
3449 if (breakForLoop.top())
3450 builder.createLoopExit();
3451 else
3452 builder.addSwitchBreak();
3453 break;
3454 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003455 builder.createLoopContinue();
3456 break;
3457 case glslang::EOpReturn:
John Kessenich435dd802020-06-30 01:27:08 -06003458 if (node->getExpression() != nullptr) {
John Kesseniched33e052016-10-06 12:59:51 -06003459 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3460 spv::Id returnId = accessChainLoad(glslangReturnType);
John Kessenich435dd802020-06-30 01:27:08 -06003461 if (builder.getTypeId(returnId) != currentFunction->getReturnType() ||
3462 TranslatePrecisionDecoration(glslangReturnType) != currentFunction->getReturnPrecision()) {
John Kesseniched33e052016-10-06 12:59:51 -06003463 builder.clearAccessChain();
John Kessenich435dd802020-06-30 01:27:08 -06003464 spv::Id copyId = builder.createVariable(currentFunction->getReturnPrecision(),
3465 spv::StorageClassFunction, currentFunction->getReturnType());
John Kesseniched33e052016-10-06 12:59:51 -06003466 builder.setAccessChainLValue(copyId);
3467 multiTypeStore(glslangReturnType, returnId);
John Kessenich435dd802020-06-30 01:27:08 -06003468 returnId = builder.createLoad(copyId, currentFunction->getReturnPrecision());
John Kesseniched33e052016-10-06 12:59:51 -06003469 }
3470 builder.makeReturn(false, returnId);
3471 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003472 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003473
3474 builder.clearAccessChain();
3475 break;
3476
John Kessenichb9197c82019-08-11 07:41:45 -06003477#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003478 case glslang::EOpDemote:
3479 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3480 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3481 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3482 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003483#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003484
John Kessenich140f3df2015-06-26 16:58:36 -06003485 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003486 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003487 break;
3488 }
3489
3490 return false;
3491}
3492
John Kessenich9c14f772019-06-17 08:38:35 -06003493spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003494{
qining25262b32016-05-06 17:25:16 -04003495 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003496 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003497 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003498 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003499 spv::Id result = createSpvConstant(*node);
3500 if (result != spv::NoResult)
3501 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003502 }
3503
3504 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003505 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003506 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3507 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003508
John Kessenichb9197c82019-08-11 07:41:45 -06003509 const bool contains16BitType = node->getType().contains16BitFloat() ||
3510 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003511 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003512 switch (storageClass) {
3513 case spv::StorageClassInput:
3514 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003515 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003516 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003517 break;
John Kessenich18310872018-05-14 22:08:53 -06003518 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003519 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003520 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3521 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003522 else
3523 builder.addCapability(spv::CapabilityStorageUniform16);
3524 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003525#ifndef GLSLANG_WEB
3526 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003527 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003528 builder.addCapability(spv::CapabilityStoragePushConstant16);
3529 break;
John Kessenich18310872018-05-14 22:08:53 -06003530 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003531 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003532 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003533 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3534 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003535#endif
John Kessenich18310872018-05-14 22:08:53 -06003536 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003537 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003538 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003539 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003540 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003541 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003542 }
3543 }
Rex Xuf89ad982017-04-07 23:22:33 +08003544
John Kessenichb9197c82019-08-11 07:41:45 -06003545 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003546 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003547 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003548 builder.addCapability(spv::CapabilityStoragePushConstant8);
3549 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003550 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003551 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003552 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003553 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003554 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003555 } else {
3556 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003557 }
3558 }
3559
John Kessenich140f3df2015-06-26 16:58:36 -06003560 const char* name = node->getName().c_str();
3561 if (glslang::IsAnonymous(name))
3562 name = "";
3563
Alejandro Piñeiroff6dcca2020-06-04 09:39:31 +02003564 spv::Id initializer = spv::NoResult;
3565
3566 if (node->getType().getQualifier().storage == glslang::EvqUniform &&
3567 !node->getConstArray().empty()) {
3568 int nextConst = 0;
3569 initializer = createSpvConstantFromConstUnionArray(node->getType(),
3570 node->getConstArray(),
3571 nextConst,
3572 false /* specConst */);
3573 }
3574
John Kessenich435dd802020-06-30 01:27:08 -06003575 return builder.createVariable(spv::NoPrecision, storageClass, spvType, name, initializer);
John Kessenich140f3df2015-06-26 16:58:36 -06003576}
3577
3578// Return type Id of the sampled type.
3579spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3580{
3581 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003582 case glslang::EbtInt: return builder.makeIntType(32);
3583 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003584 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003585#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003586 case glslang::EbtFloat16:
3587 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3588 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3589 return builder.makeFloatType(16);
3590#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003591 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003592 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003593 return builder.makeFloatType(32);
3594 }
3595}
3596
John Kessenich8c8505c2016-07-26 12:50:38 -06003597// If node is a swizzle operation, return the type that should be used if
3598// the swizzle base is first consumed by another operation, before the swizzle
3599// is applied.
3600spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3601{
John Kessenichecba76f2017-01-06 00:34:48 -07003602 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003603 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3604 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3605 else
3606 return spv::NoType;
3607}
3608
3609// When inverting a swizzle with a parent op, this function
3610// will apply the swizzle operation to a completed parent operation.
John Kessenich8985fc92020-03-03 10:25:07 -07003611spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
3612 spv::Id parentResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003613{
3614 std::vector<unsigned> swizzle;
3615 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3616 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3617}
3618
John Kessenich8c8505c2016-07-26 12:50:38 -06003619// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3620void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3621{
3622 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3623 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3624 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3625}
3626
John Kessenich3ac051e2015-12-20 11:29:16 -07003627// Convert from a glslang type to an SPV type, by calling into a
3628// recursive version of this function. This establishes the inherited
3629// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003630spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003631{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003632 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003633}
3634
3635// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003636// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003637// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003638spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003639 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3640 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003641{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003642 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003643
3644 switch (type.getBasicType()) {
3645 case glslang::EbtVoid:
3646 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003647 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003648 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003649 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003650 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3651 // a 32-bit int where non-0 means true.
3652 if (explicitLayout != glslang::ElpNone)
3653 spvType = builder.makeUintType(32);
3654 else
3655 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003656 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003657 case glslang::EbtInt:
3658 spvType = builder.makeIntType(32);
3659 break;
3660 case glslang::EbtUint:
3661 spvType = builder.makeUintType(32);
3662 break;
3663 case glslang::EbtFloat:
3664 spvType = builder.makeFloatType(32);
3665 break;
3666#ifndef GLSLANG_WEB
3667 case glslang::EbtDouble:
3668 spvType = builder.makeFloatType(64);
3669 break;
3670 case glslang::EbtFloat16:
3671 spvType = builder.makeFloatType(16);
3672 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003673 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003674 spvType = builder.makeIntType(8);
3675 break;
3676 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003677 spvType = builder.makeUintType(8);
3678 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003679 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003680 spvType = builder.makeIntType(16);
3681 break;
3682 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003683 spvType = builder.makeUintType(16);
3684 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003685 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003686 spvType = builder.makeIntType(64);
3687 break;
3688 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003689 spvType = builder.makeUintType(64);
3690 break;
John Kessenich426394d2015-07-23 10:22:48 -06003691 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003692 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003693 spvType = builder.makeUintType(32);
3694 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04003695 case glslang::EbtAccStruct:
3696 spvType = builder.makeAccelerationStructureType();
Chao Chenb50c02e2018-09-19 11:42:24 -07003697 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04003698 case glslang::EbtRayQuery:
3699 spvType = builder.makeRayQueryType();
3700 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003701 case glslang::EbtReference:
3702 {
3703 // Make the forward pointer, then recurse to convert the structure type, then
3704 // patch up the forward pointer with a real pointer type.
3705 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3706 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3707 forwardPointers[type.getReferentType()] = forwardId;
3708 }
3709 spvType = forwardPointers[type.getReferentType()];
3710 if (!forwardReferenceOnly) {
3711 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3712 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3713 forwardPointers[type.getReferentType()],
3714 referentType);
3715 }
3716 }
3717 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003718#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003719 case glslang::EbtSampler:
3720 {
3721 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003722 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003723 spvType = builder.makeSamplerType();
3724 } else {
3725 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003726 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3727 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3728 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3729 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003730 // already has both image and sampler, make the combined type
3731 spvType = builder.makeSampledImageType(spvType);
3732 }
John Kessenich55e7d112015-11-15 21:33:39 -07003733 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003734 }
John Kessenich140f3df2015-06-26 16:58:36 -06003735 break;
3736 case glslang::EbtStruct:
3737 case glslang::EbtBlock:
3738 {
3739 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003740 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003741
3742 // Try to share structs for different layouts, but not yet for other
3743 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003744 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003745 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003746 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003747 break;
3748
3749 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003750 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003751 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003752 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003753 }
3754 break;
Jeff Bolz04d73732019-05-31 13:06:01 -05003755 case glslang::EbtString:
3756 // no type used for OpString
3757 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003758 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003759 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003760 break;
3761 }
3762
3763 if (type.isMatrix())
3764 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3765 else {
3766 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3767 if (type.getVectorSize() > 1)
3768 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3769 }
3770
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003771 if (type.isCoopMat()) {
3772 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3773 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3774 if (type.getBasicType() == glslang::EbtFloat16)
3775 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003776 if (type.getBasicType() == glslang::EbtUint8 ||
3777 type.getBasicType() == glslang::EbtInt8) {
3778 builder.addCapability(spv::CapabilityInt8);
3779 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003780
3781 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3782 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3783 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3784
3785 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3786 }
3787
John Kessenich140f3df2015-06-26 16:58:36 -06003788 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003789 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3790
John Kessenichc9a80832015-09-12 12:17:44 -06003791 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003792 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003793 // We need to decorate array strides for types needing explicit layout, except blocks.
3794 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003795 // Use a dummy glslang type for querying internal strides of
3796 // arrays of arrays, but using just a one-dimensional array.
3797 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003798 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3799 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003800
3801 // Will compute the higher-order strides here, rather than making a whole
3802 // pile of types and doing repetitive recursion on their contents.
3803 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3804 }
John Kessenichf8842e52016-01-04 19:22:56 -07003805
3806 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003807 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003808 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003809 if (stride > 0)
3810 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003811 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003812 }
3813 } else {
3814 // single-dimensional array, and don't yet have stride
3815
John Kessenichf8842e52016-01-04 19:22:56 -07003816 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003817 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3818 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003819 }
John Kessenich31ed4832015-09-09 17:51:38 -06003820
John Kessenichead86222018-03-28 18:01:20 -06003821 // Do the outer dimension, which might not be known for a runtime-sized array.
3822 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3823 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003824 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003825 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003826#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003827 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003828 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003829 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3830 }
John Kessenichb9197c82019-08-11 07:41:45 -06003831#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003832 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003833 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003834 if (stride > 0)
3835 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003836 }
3837
3838 return spvType;
3839}
3840
John Kessenich0e737842017-03-24 18:38:16 -06003841// TODO: this functionality should exist at a higher level, in creating the AST
3842//
3843// Identify interface members that don't have their required extension turned on.
3844//
3845bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3846{
John Kessenicha28f7a72019-08-06 07:00:58 -06003847#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003848 auto& extensions = glslangIntermediate->getRequestedExtensions();
3849
Rex Xubcf291a2017-03-29 23:01:36 +08003850 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3851 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3852 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003853 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3854 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3855 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003856
3857 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3858 if (member.getFieldName() == "gl_ViewportMask" &&
3859 extensions.find("GL_NV_viewport_array2") == extensions.end())
3860 return true;
3861 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3862 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3863 return true;
3864 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3865 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3866 return true;
3867 }
3868#endif
John Kessenich0e737842017-03-24 18:38:16 -06003869
3870 return false;
3871};
3872
John Kessenich6090df02016-06-30 21:18:02 -06003873// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3874// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3875// Mutually recursive with convertGlslangToSpvType().
3876spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3877 const glslang::TTypeList* glslangMembers,
3878 glslang::TLayoutPacking explicitLayout,
3879 const glslang::TQualifier& qualifier)
3880{
3881 // Create a vector of struct types for SPIR-V to consume
3882 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07003883 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
3884 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003885 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003886 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3887 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3888 if (glslangMember.hiddenMember()) {
3889 ++memberDelta;
3890 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003891 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06003892 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003893 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003894 if (filterMember(glslangMember)) {
3895 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08003896 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003897 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003898 }
Roy05a5b532020-01-03 16:21:34 +08003899 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003900 }
John Kessenich6090df02016-06-30 21:18:02 -06003901 // modify just this child's view of the qualifier
3902 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3903 InheritQualifiers(memberQualifier, qualifier);
3904
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003905 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003906 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003907 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003908
3909 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003910 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3911 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003912
3913 // Make forward pointers for any pointer members, and create a list of members to
3914 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003915 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003916 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3917 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3918 }
3919 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003920 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3921 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003922 } else {
3923 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003924 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3925 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003926 }
John Kessenich6090df02016-06-30 21:18:02 -06003927 }
3928 }
3929
3930 // Make the SPIR-V type
3931 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003932 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003933 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3934
3935 // Decorate it
3936 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3937
John Kessenichd72f4882019-01-16 14:55:37 +07003938 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003939 auto it = deferredForwardPointers[i];
3940 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3941 }
3942
John Kessenich6090df02016-06-30 21:18:02 -06003943 return spvType;
3944}
3945
3946void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3947 const glslang::TTypeList* glslangMembers,
3948 glslang::TLayoutPacking explicitLayout,
3949 const glslang::TQualifier& qualifier,
3950 spv::Id spvType)
3951{
3952 // Name and decorate the non-hidden members
3953 int offset = -1;
3954 int locationOffset = 0; // for use within the members of this struct
3955 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3956 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3957 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003958 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08003959 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06003960 if (filterMember(glslangMember))
3961 continue;
3962 }
John Kessenich6090df02016-06-30 21:18:02 -06003963
3964 // modify just this child's view of the qualifier
3965 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3966 InheritQualifiers(memberQualifier, qualifier);
3967
3968 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003969 if (member < 0)
3970 continue;
3971
3972 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3973 builder.addMemberDecoration(spvType, member,
3974 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3975 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3976 // Add interpolation and auxiliary storage decorations only to
3977 // top-level members of Input and Output storage classes
3978 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3979 type.getQualifier().storage == glslang::EvqVaryingOut) {
3980 if (type.getBasicType() == glslang::EbtBlock ||
3981 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3982 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3983 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003984#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003985 addMeshNVDecoration(spvType, member, memberQualifier);
3986#endif
John Kessenich6090df02016-06-30 21:18:02 -06003987 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003988 }
3989 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003990
John Kessenichb9197c82019-08-11 07:41:45 -06003991#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003992 if (type.getBasicType() == glslang::EbtBlock &&
3993 qualifier.storage == glslang::EvqBuffer) {
3994 // Add memory decorations only to top-level members of shader storage block
3995 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003996 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003997 for (unsigned int i = 0; i < memory.size(); ++i)
3998 builder.addMemberDecoration(spvType, member, memory[i]);
3999 }
John Kessenichf8d1d742019-10-21 06:55:11 -06004000
John Kessenichb9197c82019-08-11 07:41:45 -06004001#endif
John Kessenich6090df02016-06-30 21:18:02 -06004002
John Kessenich5d610ee2018-03-07 18:05:55 -07004003 // Location assignment was already completed correctly by the front end,
4004 // just track whether a member needs to be decorated.
4005 // Ignore member locations if the container is an array, as that's
4006 // ill-specified and decisions have been made to not allow this.
4007 if (! type.isArray() && memberQualifier.hasLocation())
4008 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06004009
John Kessenich5d610ee2018-03-07 18:05:55 -07004010 if (qualifier.hasLocation()) // track for upcoming inheritance
4011 locationOffset += glslangIntermediate->computeTypeLocationSize(
4012 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06004013
John Kessenich5d610ee2018-03-07 18:05:55 -07004014 // component, XFB, others
4015 if (glslangMember.getQualifier().hasComponent())
4016 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
4017 glslangMember.getQualifier().layoutComponent);
4018 if (glslangMember.getQualifier().hasXfbOffset())
4019 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
4020 glslangMember.getQualifier().layoutXfbOffset);
4021 else if (explicitLayout != glslang::ElpNone) {
4022 // figure out what to do with offset, which is accumulating
4023 int nextOffset;
4024 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
4025 if (offset >= 0)
4026 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
4027 offset = nextOffset;
4028 }
John Kessenich6090df02016-06-30 21:18:02 -06004029
John Kessenich5d610ee2018-03-07 18:05:55 -07004030 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
4031 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
4032 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06004033
John Kessenich5d610ee2018-03-07 18:05:55 -07004034 // built-in variable decorations
4035 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
4036 if (builtIn != spv::BuiltInMax)
4037 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08004038
John Kessenichb9197c82019-08-11 07:41:45 -06004039#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06004040 // nonuniform
4041 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
4042
John Kessenichead86222018-03-28 18:01:20 -06004043 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
4044 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
4045 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
4046 memberQualifier.semanticName);
4047 }
4048
John Kessenich5d610ee2018-03-07 18:05:55 -07004049 if (builtIn == spv::BuiltInLayer) {
4050 // SPV_NV_viewport_array2 extension
4051 if (glslangMember.getQualifier().layoutViewportRelative){
4052 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
4053 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4054 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08004055 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004056 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
4057 builder.addMemberDecoration(spvType, member,
4058 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
4059 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
4060 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4061 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08004062 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004063 }
4064 if (glslangMember.getQualifier().layoutPassthrough) {
4065 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
4066 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
4067 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4068 }
chaoc771d89f2017-01-13 01:10:53 -08004069#endif
John Kessenich6090df02016-06-30 21:18:02 -06004070 }
4071
4072 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07004073 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
4074 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06004075}
4076
John Kessenich6c292d32016-02-15 20:58:50 -07004077// Turn the expression forming the array size into an id.
4078// This is not quite trivial, because of specialization constants.
4079// Sometimes, a raw constant is turned into an Id, and sometimes
4080// a specialization constant expression is.
4081spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
4082{
4083 // First, see if this is sized with a node, meaning a specialization constant:
4084 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
4085 if (specNode != nullptr) {
4086 builder.clearAccessChain();
4087 specNode->traverse(this);
4088 return accessChainLoad(specNode->getAsTyped()->getType());
4089 }
qining25262b32016-05-06 17:25:16 -04004090
John Kessenich6c292d32016-02-15 20:58:50 -07004091 // Otherwise, need a compile-time (front end) size, get it:
4092 int size = arraySizes.getDimSize(dim);
4093 assert(size > 0);
4094 return builder.makeUintConstant(size);
4095}
4096
John Kessenich103bef92016-02-08 21:38:15 -07004097// Wrap the builder's accessChainLoad to:
4098// - localize handling of RelaxedPrecision
4099// - use the SPIR-V inferred type instead of another conversion of the glslang type
4100// (avoids unnecessary work and possible type punning for structures)
4101// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07004102spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
4103{
John Kessenich103bef92016-02-08 21:38:15 -07004104 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004105
4106 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4107 coherentFlags |= TranslateCoherent(type);
4108
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004109 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004110 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004111
John Kessenich5611c6d2018-04-05 11:25:02 -06004112 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
John Kessenich8985fc92020-03-03 10:25:07 -07004113 TranslateNonUniformDecoration(type.getQualifier()),
4114 nominalTypeId,
4115 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
4116 TranslateMemoryScope(coherentFlags),
4117 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07004118
4119 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08004120 if (type.getBasicType() == glslang::EbtBool) {
4121 if (builder.isScalarType(nominalTypeId)) {
4122 // Conversion for bool
4123 spv::Id boolType = builder.makeBoolType();
4124 if (nominalTypeId != boolType)
4125 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
4126 } else if (builder.isVectorType(nominalTypeId)) {
4127 // Conversion for bvec
4128 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4129 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
4130 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07004131 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
4132 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004133 }
4134 }
John Kessenich103bef92016-02-08 21:38:15 -07004135
4136 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07004137}
4138
Rex Xu27253232016-02-23 17:51:09 +08004139// Wrap the builder's accessChainStore to:
4140// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06004141//
4142// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08004143void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
4144{
4145 // Need to convert to abstract types when necessary
4146 if (type.getBasicType() == glslang::EbtBool) {
4147 spv::Id nominalTypeId = builder.accessChainGetInferredType();
4148
4149 if (builder.isScalarType(nominalTypeId)) {
4150 // Conversion for bool
4151 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06004152 if (nominalTypeId != boolType) {
4153 // keep these outside arguments, for determinant order-of-evaluation
4154 spv::Id one = builder.makeUintConstant(1);
4155 spv::Id zero = builder.makeUintConstant(0);
4156 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
4157 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06004158 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08004159 } else if (builder.isVectorType(nominalTypeId)) {
4160 // Conversion for bvec
4161 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4162 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06004163 if (nominalTypeId != bvecType) {
4164 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06004165 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
4166 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
4167 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06004168 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06004169 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
4170 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004171 }
4172 }
4173
Jeff Bolz36831c92018-09-05 10:11:41 -05004174 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4175 coherentFlags |= TranslateCoherent(type);
4176
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004177 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004178 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004179
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02004180 builder.accessChainStore(rvalue, TranslateNonUniformDecoration(type.getQualifier()),
John Kessenich8985fc92020-03-03 10:25:07 -07004181 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
4182 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004183 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08004184}
4185
John Kessenich4bf71552016-09-02 11:20:21 -06004186// For storing when types match at the glslang level, but not might match at the
4187// SPIR-V level.
4188//
4189// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004190// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004191// as in a member-decorated way.
4192//
4193// NOTE: This function can handle any store request; if it's not special it
4194// simplifies to a simple OpStore.
4195//
4196// Implicitly uses the existing builder.accessChain as the storage target.
4197void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4198{
John Kessenichb3e24e42016-09-11 12:33:43 -06004199 // we only do the complex path here if it's an aggregate
4200 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004201 accessChainStore(type, rValue);
4202 return;
4203 }
4204
John Kessenichb3e24e42016-09-11 12:33:43 -06004205 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004206 spv::Id rType = builder.getTypeId(rValue);
4207 spv::Id lValue = builder.accessChainGetLValue();
4208 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4209 if (lType == rType) {
4210 accessChainStore(type, rValue);
4211 return;
4212 }
4213
John Kessenichb3e24e42016-09-11 12:33:43 -06004214 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004215 // where the two types were the same type in GLSL. This requires member
4216 // by member copy, recursively.
4217
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004218 // SPIR-V 1.4 added an instruction to do help do this.
4219 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4220 // However, bool in uniform space is changed to int, so
4221 // OpCopyLogical does not work for that.
4222 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4223 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4224 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4225 if (lBool == rBool) {
4226 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4227 accessChainStore(type, logicalCopy);
4228 return;
4229 }
4230 }
4231
John Kessenichb3e24e42016-09-11 12:33:43 -06004232 // If an array, copy element by element.
4233 if (type.isArray()) {
4234 glslang::TType glslangElementType(type, 0);
4235 spv::Id elementRType = builder.getContainedTypeId(rType);
4236 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4237 // get the source member
4238 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004239
John Kessenichb3e24e42016-09-11 12:33:43 -06004240 // set up the target storage
4241 builder.clearAccessChain();
4242 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004243 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4244 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004245
John Kessenichb3e24e42016-09-11 12:33:43 -06004246 // store the member
4247 multiTypeStore(glslangElementType, elementRValue);
4248 }
4249 } else {
4250 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004251
John Kessenichb3e24e42016-09-11 12:33:43 -06004252 // loop over structure members
4253 const glslang::TTypeList& members = *type.getStruct();
4254 for (int m = 0; m < (int)members.size(); ++m) {
4255 const glslang::TType& glslangMemberType = *members[m].type;
4256
4257 // get the source member
4258 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4259 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4260
4261 // set up the target storage
4262 builder.clearAccessChain();
4263 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004264 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4265 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004266
4267 // store the member
4268 multiTypeStore(glslangMemberType, memberRValue);
4269 }
John Kessenich4bf71552016-09-02 11:20:21 -06004270 }
4271}
4272
John Kessenichf85e8062015-12-19 13:57:10 -07004273// Decide whether or not this type should be
4274// decorated with offsets and strides, and if so
4275// whether std140 or std430 rules should be applied.
4276glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004277{
John Kessenichf85e8062015-12-19 13:57:10 -07004278 // has to be a block
4279 if (type.getBasicType() != glslang::EbtBlock)
4280 return glslang::ElpNone;
4281
Chao Chen3c366992018-09-19 11:41:59 -07004282 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004283 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004284 type.getQualifier().storage != glslang::EvqBuffer &&
4285 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004286 return glslang::ElpNone;
4287
4288 // return the layout to use
4289 switch (type.getQualifier().layoutPacking) {
4290 case glslang::ElpStd140:
4291 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004292 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004293 return type.getQualifier().layoutPacking;
4294 default:
4295 return glslang::ElpNone;
4296 }
John Kessenich31ed4832015-09-09 17:51:38 -06004297}
4298
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004299// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004300int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4301 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004302{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004303 int size;
John Kessenich49987892015-12-29 17:11:44 -07004304 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004305 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4306 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004307
4308 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004309}
4310
John Kessenich49987892015-12-29 17:11:44 -07004311// 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 -07004312// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004313int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4314 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004315{
John Kessenich49987892015-12-29 17:11:44 -07004316 glslang::TType elementType;
4317 elementType.shallowCopy(matrixType);
4318 elementType.clearArraySizes();
4319
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004320 int size;
John Kessenich49987892015-12-29 17:11:44 -07004321 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004322 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4323 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004324
4325 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004326}
4327
John Kessenich5e4b1242015-08-06 22:53:06 -06004328// Given a member type of a struct, realign the current offset for it, and compute
4329// the next (not yet aligned) offset for the next member, which will get aligned
4330// on the next call.
4331// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4332// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4333// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004334void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4335 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004336{
4337 // this will get a positive value when deemed necessary
4338 nextOffset = -1;
4339
John Kessenich5e4b1242015-08-06 22:53:06 -06004340 // override anything in currentOffset with user-set offset
4341 if (memberType.getQualifier().hasOffset())
4342 currentOffset = memberType.getQualifier().layoutOffset;
4343
4344 // It could be that current linker usage in glslang updated all the layoutOffset,
4345 // in which case the following code does not matter. But, that's not quite right
4346 // once cross-compilation unit GLSL validation is done, as the original user
4347 // settings are needed in layoutOffset, and then the following will come into play.
4348
John Kessenichf85e8062015-12-19 13:57:10 -07004349 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004350 if (! memberType.getQualifier().hasOffset())
4351 currentOffset = -1;
4352
4353 return;
4354 }
4355
John Kessenichf85e8062015-12-19 13:57:10 -07004356 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004357 if (currentOffset < 0)
4358 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004359
John Kessenich5e4b1242015-08-06 22:53:06 -06004360 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4361 // but possibly not yet correctly aligned.
4362
4363 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004364 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004365 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4366 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004367
4368 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004369 // TODO: make this consistent in early phases of code:
4370 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4371 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4372 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004373 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004374 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004375 int dummySize;
4376 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4377 if (componentAlignment <= 4)
4378 memberAlignment = componentAlignment;
4379 }
4380
4381 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004382 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004383
4384 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004385 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4386 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004387 glslang::RoundToPow2(currentOffset, 16);
4388
John Kessenich5e4b1242015-08-06 22:53:06 -06004389 nextOffset = currentOffset + memberSize;
4390}
4391
David Netoa901ffe2016-06-08 14:11:40 +01004392void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004393{
David Netoa901ffe2016-06-08 14:11:40 +01004394 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4395 switch (glslangBuiltIn)
4396 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004397 case glslang::EbvPointSize:
4398#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004399 case glslang::EbvClipDistance:
4400 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004401 case glslang::EbvViewportMaskNV:
4402 case glslang::EbvSecondaryPositionNV:
4403 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004404 case glslang::EbvPositionPerViewNV:
4405 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004406 case glslang::EbvTaskCountNV:
4407 case glslang::EbvPrimitiveCountNV:
4408 case glslang::EbvPrimitiveIndicesNV:
4409 case glslang::EbvClipDistancePerViewNV:
4410 case glslang::EbvCullDistancePerViewNV:
4411 case glslang::EbvLayerPerViewNV:
4412 case glslang::EbvMeshViewCountNV:
4413 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004414#endif
David Netoa901ffe2016-06-08 14:11:40 +01004415 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4416 // Alternately, we could just call this for any glslang built-in, since the
4417 // capability already guards against duplicates.
4418 TranslateBuiltInDecoration(glslangBuiltIn, false);
4419 break;
4420 default:
4421 // Capabilities were already generated when the struct was declared.
4422 break;
4423 }
John Kessenichebb50532016-05-16 19:22:05 -06004424}
4425
John Kessenich6fccb3c2016-09-19 16:01:41 -06004426bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004427{
John Kessenicheee9d532016-09-19 18:09:30 -06004428 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004429}
4430
John Kessenichd41993d2017-09-10 15:21:05 -06004431// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004432// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4433// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004434bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004435{
John Kessenich6a14f782017-12-04 02:48:10 -07004436 assert(qualifier == glslang::EvqIn ||
4437 qualifier == glslang::EvqOut ||
4438 qualifier == glslang::EvqInOut ||
rdbd8edfd82020-06-02 08:30:07 +02004439 qualifier == glslang::EvqUniform ||
John Kessenich6a14f782017-12-04 02:48:10 -07004440 qualifier == glslang::EvqConstReadOnly);
rdbd8edfd82020-06-02 08:30:07 +02004441 return qualifier != glslang::EvqConstReadOnly &&
4442 qualifier != glslang::EvqUniform;
John Kessenichd41993d2017-09-10 15:21:05 -06004443}
4444
4445// Is parameter pass-by-original?
4446bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4447 bool implicitThisParam)
4448{
4449 if (implicitThisParam) // implicit this
4450 return true;
4451 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004452 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004453 return paramType.containsOpaque() || // sampler, etc.
4454 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4455}
4456
John Kessenich140f3df2015-06-26 16:58:36 -06004457// Make all the functions, skeletally, without actually visiting their bodies.
4458void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4459{
John Kessenich8985fc92020-03-03 10:25:07 -07004460 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4461 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004462 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4463 if (paramPrecision != spv::NoPrecision)
4464 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004465 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004466 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004467 // Original and non-writable params pass the pointer directly and
4468 // use restrict/aliased, others are stored to a pointer in Function
4469 // memory and use RestrictPointer/AliasedPointer.
4470 if (originalParam(type.getQualifier().storage, type, false) ||
4471 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004472 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4473 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004474 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004475 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4476 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004477 }
4478 }
John Kessenichfad62972017-07-18 02:35:46 -06004479 };
4480
John Kessenich140f3df2015-06-26 16:58:36 -06004481 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4482 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004483 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004484 continue;
4485
4486 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004487 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004488 //
qining25262b32016-05-06 17:25:16 -04004489 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004490 // function. What it is an address of varies:
4491 //
John Kessenich4bf71552016-09-02 11:20:21 -06004492 // - "in" parameters not marked as "const" can be written to without modifying the calling
4493 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004494 //
4495 // - "const in" parameters can just be the r-value, as no writes need occur.
4496 //
John Kessenich4bf71552016-09-02 11:20:21 -06004497 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4498 // 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 -06004499
4500 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004501 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004502 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4503
John Kessenich155d3512019-08-08 23:29:20 -06004504#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004505 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4506 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004507#else
4508 bool implicitThis = false;
4509#endif
John Kessenich37789792017-03-21 23:56:40 -06004510
John Kessenichfad62972017-07-18 02:35:46 -06004511 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004512 for (int p = 0; p < (int)parameters.size(); ++p) {
4513 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4514 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004515 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004516 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004517 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004518 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4519 else
John Kessenich4bf71552016-09-02 11:20:21 -06004520 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004521 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004522 paramTypes.push_back(typeId);
4523 }
4524
4525 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004526 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4527 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004528 glslFunction->getName().c_str(), paramTypes,
4529 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004530 if (implicitThis)
4531 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004532
4533 // Track function to emit/call later
4534 functionMap[glslFunction->getName().c_str()] = function;
4535
4536 // Set the parameter id's
4537 for (int p = 0; p < (int)parameters.size(); ++p) {
4538 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4539 // give a name too
4540 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004541
4542 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004543 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004544 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004545 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004546 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004547 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004548 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004549 }
4550 }
4551}
4552
4553// Process all the initializers, while skipping the functions and link objects
4554void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4555{
4556 builder.setBuildPoint(shaderEntry->getLastBlock());
4557 for (int i = 0; i < (int)initializers.size(); ++i) {
4558 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004559 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4560 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004561
4562 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004563 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004564 initializer->traverse(this);
4565 }
4566 }
4567}
4568
4569// Process all the functions, while skipping initializers.
4570void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4571{
4572 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4573 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004574 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004575 node->traverse(this);
4576 }
4577}
4578
4579void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4580{
qining25262b32016-05-06 17:25:16 -04004581 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004582 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004583 currentFunction = functionMap[node->getName().c_str()];
4584 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004585 builder.setBuildPoint(functionBlock);
4586}
4587
John Kessenich8985fc92020-03-03 10:25:07 -07004588void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4589 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004590{
Rex Xufc618912015-09-09 16:42:49 +08004591 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004592
4593 glslang::TSampler sampler = {};
4594 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004595#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004596 bool f16ShadowCompare = false;
4597#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004598 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004599 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4600 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004601#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004602 f16ShadowCompare = sampler.shadow &&
4603 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004604#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004605 }
4606
John Kessenich140f3df2015-06-26 16:58:36 -06004607 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4608 builder.clearAccessChain();
4609 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004610
John Kessenicha28f7a72019-08-06 07:00:58 -06004611#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004612 // Special case l-value operands
4613 bool lvalue = false;
4614 switch (node.getOp()) {
4615 case glslang::EOpImageAtomicAdd:
4616 case glslang::EOpImageAtomicMin:
4617 case glslang::EOpImageAtomicMax:
4618 case glslang::EOpImageAtomicAnd:
4619 case glslang::EOpImageAtomicOr:
4620 case glslang::EOpImageAtomicXor:
4621 case glslang::EOpImageAtomicExchange:
4622 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004623 case glslang::EOpImageAtomicLoad:
4624 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004625 if (i == 0)
4626 lvalue = true;
4627 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004628 case glslang::EOpSparseImageLoad:
4629 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4630 lvalue = true;
4631 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004632 case glslang::EOpSparseTexture:
4633 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4634 lvalue = true;
4635 break;
4636 case glslang::EOpSparseTextureClamp:
4637 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4638 lvalue = true;
4639 break;
4640 case glslang::EOpSparseTextureLod:
4641 case glslang::EOpSparseTextureOffset:
4642 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4643 lvalue = true;
4644 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004645 case glslang::EOpSparseTextureFetch:
4646 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4647 lvalue = true;
4648 break;
4649 case glslang::EOpSparseTextureFetchOffset:
4650 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4651 lvalue = true;
4652 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004653 case glslang::EOpSparseTextureLodOffset:
4654 case glslang::EOpSparseTextureGrad:
4655 case glslang::EOpSparseTextureOffsetClamp:
4656 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4657 lvalue = true;
4658 break;
4659 case glslang::EOpSparseTextureGradOffset:
4660 case glslang::EOpSparseTextureGradClamp:
4661 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4662 lvalue = true;
4663 break;
4664 case glslang::EOpSparseTextureGradOffsetClamp:
4665 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4666 lvalue = true;
4667 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004668 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004669 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4670 lvalue = true;
4671 break;
4672 case glslang::EOpSparseTextureGatherOffset:
4673 case glslang::EOpSparseTextureGatherOffsets:
4674 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4675 lvalue = true;
4676 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004677 case glslang::EOpSparseTextureGatherLod:
4678 if (i == 3)
4679 lvalue = true;
4680 break;
4681 case glslang::EOpSparseTextureGatherLodOffset:
4682 case glslang::EOpSparseTextureGatherLodOffsets:
4683 if (i == 4)
4684 lvalue = true;
4685 break;
Rex Xu129799a2017-07-05 17:23:28 +08004686 case glslang::EOpSparseImageLoadLod:
4687 if (i == 3)
4688 lvalue = true;
4689 break;
Chao Chen3a137962018-09-19 11:41:27 -07004690 case glslang::EOpImageSampleFootprintNV:
4691 if (i == 4)
4692 lvalue = true;
4693 break;
4694 case glslang::EOpImageSampleFootprintClampNV:
4695 case glslang::EOpImageSampleFootprintLodNV:
4696 if (i == 5)
4697 lvalue = true;
4698 break;
4699 case glslang::EOpImageSampleFootprintGradNV:
4700 if (i == 6)
4701 lvalue = true;
4702 break;
4703 case glslang::EOpImageSampleFootprintGradClampNV:
4704 if (i == 7)
4705 lvalue = true;
4706 break;
Rex Xufc618912015-09-09 16:42:49 +08004707 default:
4708 break;
4709 }
4710
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004711 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004712 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004713 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4714 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4715 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004716#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004717 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004718 }
4719}
4720
John Kessenichfc51d282015-08-19 13:34:18 -06004721void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004722{
John Kessenichfc51d282015-08-19 13:34:18 -06004723 builder.clearAccessChain();
4724 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004725 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004726}
John Kessenich140f3df2015-06-26 16:58:36 -06004727
John Kessenichfc51d282015-08-19 13:34:18 -06004728spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4729{
John Kesseniche485c7a2017-05-31 18:50:53 -06004730 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004731 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004732
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004733 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004734
John Kessenichfc51d282015-08-19 13:34:18 -06004735 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004736
John Kessenichf43c7392019-03-31 10:51:57 -06004737 const glslang::TType &imageType = node->getAsAggregate()
4738 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4739 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004740 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004741#ifdef GLSLANG_WEB
4742 const bool f16ShadowCompare = false;
4743#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004744 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004745 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4746 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004747#endif
4748
John Kessenichf43c7392019-03-31 10:51:57 -06004749 const auto signExtensionMask = [&]() {
4750 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4751 if (sampler.type == glslang::EbtUint)
4752 return spv::ImageOperandsZeroExtendMask;
4753 else if (sampler.type == glslang::EbtInt)
4754 return spv::ImageOperandsSignExtendMask;
4755 }
4756 return spv::ImageOperandsMaskNone;
4757 };
4758
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004759 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4760
John Kessenichfc51d282015-08-19 13:34:18 -06004761 std::vector<spv::Id> arguments;
4762 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004763 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004764 else
4765 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenich12c155f2020-06-30 07:52:05 -06004766 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
John Kessenichfc51d282015-08-19 13:34:18 -06004767
4768 spv::Builder::TextureParameters params = { };
4769 params.sampler = arguments[0];
4770
Rex Xu04db3f52015-09-16 11:44:02 +08004771 glslang::TCrackedTextureOp cracked;
4772 node->crackTexture(sampler, cracked);
4773
amhagan05506bb2017-06-13 16:53:02 -04004774 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004775
Bas Nieuwenhuizen58064312020-09-03 03:04:13 +02004776 if (builder.isSampledImage(params.sampler) &&
4777 ((cracked.query && node->getOp() != glslang::EOpTextureQueryLod) || cracked.fragMask || cracked.fetch)) {
4778 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4779 if (imageType.getQualifier().isNonUniform()) {
4780 builder.addDecoration(params.sampler, spv::DecorationNonUniformEXT);
4781 }
4782 }
John Kessenichfc51d282015-08-19 13:34:18 -06004783 // Check for queries
4784 if (cracked.query) {
4785 switch (node->getOp()) {
4786 case glslang::EOpImageQuerySize:
4787 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004788 if (arguments.size() > 1) {
4789 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004790 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004791 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004792 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004793#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004794 case glslang::EOpImageQuerySamples:
4795 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004796 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004797 case glslang::EOpTextureQueryLod:
4798 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004799 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004800 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004801 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004802 case glslang::EOpSparseTexelsResident:
4803 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004804#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004805 default:
4806 assert(0);
4807 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004808 }
John Kessenich140f3df2015-06-26 16:58:36 -06004809 }
4810
LoopDawg4425f242018-02-18 11:40:01 -07004811 int components = node->getType().getVectorSize();
4812
4813 if (node->getOp() == glslang::EOpTextureFetch) {
4814 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4815 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4816 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4817 // here around e.g. which ones return scalars or other types.
4818 components = 4;
4819 }
4820
4821 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4822
4823 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4824
Rex Xufc618912015-09-09 16:42:49 +08004825 // Check for image functions other than queries
4826 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004827 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004828 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004829 spv::IdImmediate image = { true, *(opIt++) };
4830 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004831
4832 // Handle subpass operations
4833 // TODO: GLSL should change to have the "MS" only on the type rather than the
4834 // built-in function.
4835 if (cracked.subpass) {
4836 // add on the (0,0) coordinate
4837 spv::Id zero = builder.makeIntConstant(0);
4838 std::vector<spv::Id> comps;
4839 comps.push_back(zero);
4840 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004841 spv::IdImmediate coord = { true,
4842 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4843 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004844 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4845 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004846 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004847 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4848 }
4849 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004850 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004851 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004852 spv::IdImmediate imageOperand = { true, *(opIt++) };
4853 operands.push_back(imageOperand);
4854 }
John Kessenich6c292d32016-02-15 20:58:50 -07004855 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004856 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4857 builder.setPrecision(result, precision);
4858 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004859 }
4860
John Kessenich149afc32018-08-14 13:31:43 -06004861 spv::IdImmediate coord = { true, *(opIt++) };
4862 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004863 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004864 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004865 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004866 mask = mask | spv::ImageOperandsSampleMask;
4867 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004868 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004869 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4870 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004871 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004872 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004873 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4874 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004875 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004876 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004877 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4878 operands.push_back(imageOperands);
4879 }
4880 if (mask & spv::ImageOperandsSampleMask) {
4881 spv::IdImmediate imageOperand = { true, *opIt++ };
4882 operands.push_back(imageOperand);
4883 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004884 if (mask & spv::ImageOperandsLodMask) {
4885 spv::IdImmediate imageOperand = { true, *opIt++ };
4886 operands.push_back(imageOperand);
4887 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004888 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004889 spv::IdImmediate imageOperand = { true,
4890 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004891 operands.push_back(imageOperand);
4892 }
4893
John Kessenich149afc32018-08-14 13:31:43 -06004894 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004895 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004896
John Kessenich149afc32018-08-14 13:31:43 -06004897 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004898 builder.setPrecision(result[0], precision);
4899
4900 // If needed, add a conversion constructor to the proper size.
4901 if (components != node->getType().getVectorSize())
4902 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4903
4904 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004905 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004906
Jeff Bolz36831c92018-09-05 10:11:41 -05004907 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004908 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004909 spv::IdImmediate texel = { true, *(opIt + 1) };
4910 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004911 } else {
4912 spv::IdImmediate texel = { true, *opIt };
4913 operands.push_back(texel);
4914 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004915
4916 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004917 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004918 mask = mask | spv::ImageOperandsSampleMask;
4919 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004920 if (cracked.lod) {
4921 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4922 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4923 mask = mask | spv::ImageOperandsLodMask;
4924 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004925 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4926 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004927 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004928 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004929 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4930 operands.push_back(imageOperands);
4931 }
4932 if (mask & spv::ImageOperandsSampleMask) {
4933 spv::IdImmediate imageOperand = { true, *opIt++ };
4934 operands.push_back(imageOperand);
4935 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004936 if (mask & spv::ImageOperandsLodMask) {
4937 spv::IdImmediate imageOperand = { true, *opIt++ };
4938 operands.push_back(imageOperand);
4939 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004940 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004941 spv::IdImmediate imageOperand = { true,
4942 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004943 operands.push_back(imageOperand);
4944 }
4945
John Kessenich56bab042015-09-16 10:54:31 -06004946 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004947 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004948 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004949 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004950 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4951 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004952 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004953 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004954 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4955
Jeff Bolz36831c92018-09-05 10:11:41 -05004956 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004957 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004958 mask = mask | spv::ImageOperandsSampleMask;
4959 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004960 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004961 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4962 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4963
Jeff Bolz36831c92018-09-05 10:11:41 -05004964 mask = mask | spv::ImageOperandsLodMask;
4965 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004966 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4967 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004968 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004969 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004970 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004971 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004972 }
4973 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004974 spv::IdImmediate imageOperand = { true, *opIt++ };
4975 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004976 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004977 if (mask & spv::ImageOperandsLodMask) {
4978 spv::IdImmediate imageOperand = { true, *opIt++ };
4979 operands.push_back(imageOperand);
4980 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004981 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07004982 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
4983 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004984 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004985 }
4986
4987 // Create the return type that was a special structure
4988 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004989 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004990 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4991 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4992
4993 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4994
4995 // Decode the return type
4996 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4997 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004998 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004999 // Process image atomic operations
5000
5001 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
5002 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06005003 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005004 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06005005 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06005006
Jeff Bolz36831c92018-09-05 10:11:41 -05005007 spv::Id resultTypeId;
5008 // imageAtomicStore has a void return type so base the pointer type on
5009 // the type of the value operand.
5010 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08005011 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05005012 } else {
5013 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
5014 }
John Kessenich56bab042015-09-16 10:54:31 -06005015 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Jeff Bolz39ffdaf2020-03-09 10:48:12 -05005016 if (imageType.getQualifier().nonUniform) {
5017 builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
5018 }
Rex Xufc618912015-09-09 16:42:49 +08005019
5020 std::vector<spv::Id> operands;
5021 operands.push_back(pointer);
5022 for (; opIt != arguments.end(); ++opIt)
5023 operands.push_back(*opIt);
5024
John Kessenich8985fc92020-03-03 10:25:07 -07005025 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
5026 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08005027 }
5028 }
5029
John Kessenicha28f7a72019-08-06 07:00:58 -06005030#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04005031 // Check for fragment mask functions other than queries
5032 if (cracked.fragMask) {
5033 assert(sampler.ms);
5034
5035 auto opIt = arguments.begin();
5036 std::vector<spv::Id> operands;
5037
amhagan05506bb2017-06-13 16:53:02 -04005038 operands.push_back(params.sampler);
5039 ++opIt;
5040
5041 if (sampler.isSubpass()) {
5042 // add on the (0,0) coordinate
5043 spv::Id zero = builder.makeIntConstant(0);
5044 std::vector<spv::Id> comps;
5045 comps.push_back(zero);
5046 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07005047 operands.push_back(builder.makeCompositeConstant(
5048 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04005049 }
5050
5051 for (; opIt != arguments.end(); ++opIt)
5052 operands.push_back(*opIt);
5053
5054 spv::Op fragMaskOp = spv::OpNop;
5055 if (node->getOp() == glslang::EOpFragmentMaskFetch)
5056 fragMaskOp = spv::OpFragmentMaskFetchAMD;
5057 else if (node->getOp() == glslang::EOpFragmentFetch)
5058 fragMaskOp = spv::OpFragmentFetchAMD;
5059
5060 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
5061 builder.addCapability(spv::CapabilityFragmentMaskAMD);
5062 return builder.createOp(fragMaskOp, resultType(), operands);
5063 }
5064#endif
5065
Rex Xufc618912015-09-09 16:42:49 +08005066 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08005067 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07005068 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005069 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08005070
John Kessenichfc51d282015-08-19 13:34:18 -06005071 // check for bias argument
5072 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08005073 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005074 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08005075 if (cracked.gather)
5076 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08005077
5078 if (f16ShadowCompare)
5079 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005080 if (cracked.offset)
5081 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08005082 else if (cracked.offsets)
5083 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005084 if (cracked.grad)
5085 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08005086 if (cracked.lodClamp)
5087 ++nonBiasArgCount;
5088 if (sparse)
5089 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07005090 if (imageFootprint)
5091 //Following three extra arguments
5092 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5093 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06005094 if ((int)arguments.size() > nonBiasArgCount)
5095 bias = true;
5096 }
5097
John Kessenicha28f7a72019-08-06 07:00:58 -06005098#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08005099 if (cracked.gather) {
5100 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
5101 if (bias || cracked.lod ||
5102 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
5103 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08005104 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08005105 }
5106 }
5107#endif
5108
John Kessenichfc51d282015-08-19 13:34:18 -06005109 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07005110
John Kessenichfc51d282015-08-19 13:34:18 -06005111 params.coords = arguments[1];
5112 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07005113 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07005114
5115 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08005116 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005117 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08005118 ++extraArgs;
5119 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07005120 params.Dref = arguments[2];
5121 ++extraArgs;
5122 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06005123 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06005124 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06005125 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06005126 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06005127 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005128 dRefComp = builder.getNumComponents(params.coords) - 1;
5129 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07005130 params.Dref = builder.createCompositeExtract(params.coords,
5131 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06005132 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005133
5134 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06005135 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005136 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06005137 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06005138 } else if (glslangIntermediate->getStage() != EShLangFragment &&
5139 !(glslangIntermediate->getStage() == EShLangCompute &&
5140 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07005141 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
5142 noImplicitLod = true;
5143 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005144
5145 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005146 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005147 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08005148 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005149 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005150
5151 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06005152 if (cracked.grad) {
5153 params.gradX = arguments[2 + extraArgs];
5154 params.gradY = arguments[3 + extraArgs];
5155 extraArgs += 2;
5156 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005157
5158 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07005159 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06005160 params.offset = arguments[2 + extraArgs];
5161 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005162 } else if (cracked.offsets) {
5163 params.offsets = arguments[2 + extraArgs];
5164 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005165 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005166
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005167#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005168 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005169 if (cracked.lodClamp) {
5170 params.lodClamp = arguments[2 + extraArgs];
5171 ++extraArgs;
5172 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005173 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005174 if (sparse) {
5175 params.texelOut = arguments[2 + extraArgs];
5176 ++extraArgs;
5177 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005178 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005179 if (cracked.gather && ! sampler.shadow) {
5180 // default component is 0, if missing, otherwise an argument
5181 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005182 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005183 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005184 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005185 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005186 }
Chao Chen3a137962018-09-19 11:41:27 -07005187 spv::Id resultStruct = spv::NoResult;
5188 if (imageFootprint) {
5189 //Following three extra arguments
5190 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5191 params.granularity = arguments[2 + extraArgs];
5192 params.coarse = arguments[3 + extraArgs];
5193 resultStruct = arguments[4 + extraArgs];
5194 extraArgs += 3;
5195 }
5196#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005197 // bias
5198 if (bias) {
5199 params.bias = arguments[2 + extraArgs];
5200 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005201 }
John Kessenichfc51d282015-08-19 13:34:18 -06005202
John Kessenicha28f7a72019-08-06 07:00:58 -06005203#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005204 if (imageFootprint) {
5205 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5206 builder.addCapability(spv::CapabilityImageFootprintNV);
5207
5208
5209 //resultStructType(OpenGL type) contains 5 elements:
5210 //struct gl_TextureFootprint2DNV {
5211 // uvec2 anchor;
5212 // uvec2 offset;
5213 // uvec2 mask;
5214 // uint lod;
5215 // uint granularity;
5216 //};
5217 //or
5218 //struct gl_TextureFootprint3DNV {
5219 // uvec3 anchor;
5220 // uvec3 offset;
5221 // uvec2 mask;
5222 // uint lod;
5223 // uint granularity;
5224 //};
5225 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5226 assert(builder.isStructType(resultStructType));
5227
5228 //resType (SPIR-V type) contains 6 elements:
5229 //Member 0 must be a Boolean type scalar(LOD),
5230 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5231 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5232 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5233 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5234 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5235 std::vector<spv::Id> members;
5236 members.push_back(resultType());
5237 for (int i = 0; i < 5; i++) {
5238 members.push_back(builder.getContainedTypeId(resultStructType, i));
5239 }
5240 spv::Id resType = builder.makeStructType(members, "ResType");
5241
5242 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005243 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5244 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005245
5246 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5247 for (int i = 0; i < 5; i++) {
5248 builder.clearAccessChain();
5249 builder.setAccessChainLValue(resultStruct);
5250
5251 //Accessing to a struct we created, no coherent flag is set
5252 spv::Builder::AccessChain::CoherentFlags flags;
5253 flags.clear();
5254
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005255 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005256 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
Bas Nieuwenhuizende949a22020-08-24 23:27:26 +02005257 i+1), TranslateNonUniformDecoration(imageType.getQualifier()));
Chao Chen3a137962018-09-19 11:41:27 -07005258 }
5259 return builder.createCompositeExtract(res, resultType(), 0);
5260 }
5261#endif
5262
John Kessenich65336482016-06-16 14:06:26 -06005263 // projective component (might not to move)
5264 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5265 // are divided by the last component of P."
5266 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5267 // unused components will appear after all used components."
5268 if (cracked.proj) {
5269 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5270 int projTargetComp;
5271 switch (sampler.dim) {
5272 case glslang::Esd1D: projTargetComp = 1; break;
5273 case glslang::Esd2D: projTargetComp = 2; break;
5274 case glslang::EsdRect: projTargetComp = 2; break;
5275 default: projTargetComp = projSourceComp; break;
5276 }
5277 // copy the projective coordinate if we have to
5278 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005279 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005280 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005281 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005282 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005283 }
5284 }
5285
John Kessenichf8d1d742019-10-21 06:55:11 -06005286#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005287 // nonprivate
5288 if (imageType.getQualifier().nonprivate) {
5289 params.nonprivate = true;
5290 }
5291
5292 // volatile
5293 if (imageType.getQualifier().volatil) {
5294 params.volatil = true;
5295 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005296#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005297
St0fFa1184dd2018-04-09 21:08:14 +02005298 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005299 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5300 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005301 );
LoopDawg4425f242018-02-18 11:40:01 -07005302
5303 if (components != node->getType().getVectorSize())
5304 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5305
5306 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005307}
5308
5309spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5310{
5311 // Grab the function's pointer from the previously created function
5312 spv::Function* function = functionMap[node->getName().c_str()];
5313 if (! function)
5314 return 0;
5315
5316 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5317 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5318
5319 // See comments in makeFunctions() for details about the semantics for parameter passing.
5320 //
5321 // These imply we need a four step process:
5322 // 1. Evaluate the arguments
5323 // 2. Allocate and make copies of in, out, and inout arguments
5324 // 3. Make the call
5325 // 4. Copy back the results
5326
John Kessenichd3ed90b2018-05-04 11:43:03 -06005327 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005328 std::vector<spv::Builder::AccessChain> lValues;
5329 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005330 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005331 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005332 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005333 // build l-value
5334 builder.clearAccessChain();
5335 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005336 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005337 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005338 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005339 // save l-value
5340 lValues.push_back(builder.getAccessChain());
5341 } else {
5342 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005343 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005344 }
5345 }
5346
5347 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5348 // copy the original into that space.
5349 //
5350 // Also, build up the list of actual arguments to pass in for the call
5351 int lValueCount = 0;
5352 int rValueCount = 0;
5353 std::vector<spv::Id> spvArgs;
5354 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5355 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005356 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005357 builder.setAccessChain(lValues[lValueCount]);
5358 arg = builder.accessChainGetLValue();
5359 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005360 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005361 // need space to hold the copy
John Kessenich435dd802020-06-30 01:27:08 -06005362 arg = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction,
John Kessenich8985fc92020-03-03 10:25:07 -07005363 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005364 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5365 // need to copy the input into output space
5366 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005367 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005368 builder.clearAccessChain();
5369 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005370 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005371 }
5372 ++lValueCount;
5373 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005374 // process r-value, which involves a copy for a type mismatch
John Kessenich4df10332020-06-26 08:37:06 -06005375 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a]) ||
John Kessenich435dd802020-06-30 01:27:08 -06005376 TranslatePrecisionDecoration(*argTypes[a]) != function->getParamPrecision(a))
John Kessenich4df10332020-06-26 08:37:06 -06005377 {
John Kessenich435dd802020-06-30 01:27:08 -06005378 spv::Id argCopy = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction, function->getParamType(a), "arg");
John Kessenichd3ed90b2018-05-04 11:43:03 -06005379 builder.clearAccessChain();
5380 builder.setAccessChainLValue(argCopy);
5381 multiTypeStore(*argTypes[a], rValues[rValueCount]);
John Kessenich435dd802020-06-30 01:27:08 -06005382 arg = builder.createLoad(argCopy, function->getParamPrecision(a));
John Kessenichd3ed90b2018-05-04 11:43:03 -06005383 } else
5384 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005385 ++rValueCount;
5386 }
5387 spvArgs.push_back(arg);
5388 }
5389
5390 // 3. Make the call.
5391 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005392 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005393
5394 // 4. Copy back out an "out" arguments.
5395 lValueCount = 0;
5396 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005397 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005398 ++lValueCount;
5399 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005400 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
John Kessenich435dd802020-06-30 01:27:08 -06005401 spv::Id copy = builder.createLoad(spvArgs[a], spv::NoPrecision);
John Kessenich140f3df2015-06-26 16:58:36 -06005402 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005403 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005404 }
5405 ++lValueCount;
5406 }
5407 }
5408
5409 return result;
5410}
5411
5412// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005413spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005414 spv::Id typeId, spv::Id left, spv::Id right,
5415 glslang::TBasicType typeProxy, bool reduceComparison)
5416{
John Kessenich66011cb2018-03-06 16:12:04 -07005417 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5418 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005419 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005420
5421 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005422 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005423 bool comparison = false;
5424
5425 switch (op) {
5426 case glslang::EOpAdd:
5427 case glslang::EOpAddAssign:
5428 if (isFloat)
5429 binOp = spv::OpFAdd;
5430 else
5431 binOp = spv::OpIAdd;
5432 break;
5433 case glslang::EOpSub:
5434 case glslang::EOpSubAssign:
5435 if (isFloat)
5436 binOp = spv::OpFSub;
5437 else
5438 binOp = spv::OpISub;
5439 break;
5440 case glslang::EOpMul:
5441 case glslang::EOpMulAssign:
5442 if (isFloat)
5443 binOp = spv::OpFMul;
5444 else
5445 binOp = spv::OpIMul;
5446 break;
5447 case glslang::EOpVectorTimesScalar:
5448 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005449 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005450 if (builder.isVector(right))
5451 std::swap(left, right);
5452 assert(builder.isScalar(right));
5453 needMatchingVectors = false;
5454 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005455 } else if (isFloat)
5456 binOp = spv::OpFMul;
5457 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005458 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005459 break;
5460 case glslang::EOpVectorTimesMatrix:
5461 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005462 binOp = spv::OpVectorTimesMatrix;
5463 break;
5464 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005465 binOp = spv::OpMatrixTimesVector;
5466 break;
5467 case glslang::EOpMatrixTimesScalar:
5468 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005469 binOp = spv::OpMatrixTimesScalar;
5470 break;
5471 case glslang::EOpMatrixTimesMatrix:
5472 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005473 binOp = spv::OpMatrixTimesMatrix;
5474 break;
5475 case glslang::EOpOuterProduct:
5476 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005477 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005478 break;
5479
5480 case glslang::EOpDiv:
5481 case glslang::EOpDivAssign:
5482 if (isFloat)
5483 binOp = spv::OpFDiv;
5484 else if (isUnsigned)
5485 binOp = spv::OpUDiv;
5486 else
5487 binOp = spv::OpSDiv;
5488 break;
5489 case glslang::EOpMod:
5490 case glslang::EOpModAssign:
5491 if (isFloat)
5492 binOp = spv::OpFMod;
5493 else if (isUnsigned)
5494 binOp = spv::OpUMod;
5495 else
5496 binOp = spv::OpSMod;
5497 break;
5498 case glslang::EOpRightShift:
5499 case glslang::EOpRightShiftAssign:
5500 if (isUnsigned)
5501 binOp = spv::OpShiftRightLogical;
5502 else
5503 binOp = spv::OpShiftRightArithmetic;
5504 break;
5505 case glslang::EOpLeftShift:
5506 case glslang::EOpLeftShiftAssign:
5507 binOp = spv::OpShiftLeftLogical;
5508 break;
5509 case glslang::EOpAnd:
5510 case glslang::EOpAndAssign:
5511 binOp = spv::OpBitwiseAnd;
5512 break;
5513 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005514 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005515 binOp = spv::OpLogicalAnd;
5516 break;
5517 case glslang::EOpInclusiveOr:
5518 case glslang::EOpInclusiveOrAssign:
5519 binOp = spv::OpBitwiseOr;
5520 break;
5521 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005522 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005523 binOp = spv::OpLogicalOr;
5524 break;
5525 case glslang::EOpExclusiveOr:
5526 case glslang::EOpExclusiveOrAssign:
5527 binOp = spv::OpBitwiseXor;
5528 break;
5529 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005530 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005531 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005532 break;
5533
Ian Romanickb3bd4022019-01-21 08:57:25 -08005534 case glslang::EOpAbsDifference:
5535 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5536 break;
5537
5538 case glslang::EOpAddSaturate:
5539 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5540 break;
5541
5542 case glslang::EOpSubSaturate:
5543 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5544 break;
5545
5546 case glslang::EOpAverage:
5547 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5548 break;
5549
5550 case glslang::EOpAverageRounded:
5551 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5552 break;
5553
5554 case glslang::EOpMul32x16:
5555 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5556 break;
5557
John Kessenich140f3df2015-06-26 16:58:36 -06005558 case glslang::EOpLessThan:
5559 case glslang::EOpGreaterThan:
5560 case glslang::EOpLessThanEqual:
5561 case glslang::EOpGreaterThanEqual:
5562 case glslang::EOpEqual:
5563 case glslang::EOpNotEqual:
5564 case glslang::EOpVectorEqual:
5565 case glslang::EOpVectorNotEqual:
5566 comparison = true;
5567 break;
5568 default:
5569 break;
5570 }
5571
John Kessenich7c1aa102015-10-15 13:29:11 -06005572 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005573 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005574 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005575 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5576 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005577 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005578
5579 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005580 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005581 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005582
qining25262b32016-05-06 17:25:16 -04005583 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005584 decorations.addNoContraction(builder, result);
5585 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005586 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005587 }
5588
5589 if (! comparison)
5590 return 0;
5591
John Kessenich7c1aa102015-10-15 13:29:11 -06005592 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005593
John Kessenich4583b612016-08-07 19:14:22 -06005594 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005595 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5596 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005597 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005598 return result;
5599 }
John Kessenich140f3df2015-06-26 16:58:36 -06005600
5601 switch (op) {
5602 case glslang::EOpLessThan:
5603 if (isFloat)
5604 binOp = spv::OpFOrdLessThan;
5605 else if (isUnsigned)
5606 binOp = spv::OpULessThan;
5607 else
5608 binOp = spv::OpSLessThan;
5609 break;
5610 case glslang::EOpGreaterThan:
5611 if (isFloat)
5612 binOp = spv::OpFOrdGreaterThan;
5613 else if (isUnsigned)
5614 binOp = spv::OpUGreaterThan;
5615 else
5616 binOp = spv::OpSGreaterThan;
5617 break;
5618 case glslang::EOpLessThanEqual:
5619 if (isFloat)
5620 binOp = spv::OpFOrdLessThanEqual;
5621 else if (isUnsigned)
5622 binOp = spv::OpULessThanEqual;
5623 else
5624 binOp = spv::OpSLessThanEqual;
5625 break;
5626 case glslang::EOpGreaterThanEqual:
5627 if (isFloat)
5628 binOp = spv::OpFOrdGreaterThanEqual;
5629 else if (isUnsigned)
5630 binOp = spv::OpUGreaterThanEqual;
5631 else
5632 binOp = spv::OpSGreaterThanEqual;
5633 break;
5634 case glslang::EOpEqual:
5635 case glslang::EOpVectorEqual:
5636 if (isFloat)
5637 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005638 else if (isBool)
5639 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005640 else
5641 binOp = spv::OpIEqual;
5642 break;
5643 case glslang::EOpNotEqual:
5644 case glslang::EOpVectorNotEqual:
5645 if (isFloat)
Graeme Leese65ce5662020-06-05 13:32:51 +01005646 binOp = spv::OpFUnordNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005647 else if (isBool)
5648 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005649 else
5650 binOp = spv::OpINotEqual;
5651 break;
5652 default:
5653 break;
5654 }
5655
qining25262b32016-05-06 17:25:16 -04005656 if (binOp != spv::OpNop) {
5657 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005658 decorations.addNoContraction(builder, result);
5659 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005660 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005661 }
John Kessenich140f3df2015-06-26 16:58:36 -06005662
5663 return 0;
5664}
5665
John Kessenich04bb8a02015-12-12 12:28:14 -07005666//
5667// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5668// These can be any of:
5669//
5670// matrix * scalar
5671// scalar * matrix
5672// matrix * matrix linear algebraic
5673// matrix * vector
5674// vector * matrix
5675// matrix * matrix componentwise
5676// matrix op matrix op in {+, -, /}
5677// matrix op scalar op in {+, -, /}
5678// scalar op matrix op in {+, -, /}
5679//
John Kessenichead86222018-03-28 18:01:20 -06005680spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5681 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005682{
5683 bool firstClass = true;
5684
5685 // First, handle first-class matrix operations (* and matrix/scalar)
5686 switch (op) {
5687 case spv::OpFDiv:
5688 if (builder.isMatrix(left) && builder.isScalar(right)) {
5689 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005690 spv::Id resultType = builder.getTypeId(right);
5691 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005692 op = spv::OpMatrixTimesScalar;
5693 } else
5694 firstClass = false;
5695 break;
5696 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005697 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005698 std::swap(left, right);
5699 assert(builder.isScalar(right));
5700 break;
5701 case spv::OpVectorTimesMatrix:
5702 assert(builder.isVector(left));
5703 assert(builder.isMatrix(right));
5704 break;
5705 case spv::OpMatrixTimesVector:
5706 assert(builder.isMatrix(left));
5707 assert(builder.isVector(right));
5708 break;
5709 case spv::OpMatrixTimesMatrix:
5710 assert(builder.isMatrix(left));
5711 assert(builder.isMatrix(right));
5712 break;
5713 default:
5714 firstClass = false;
5715 break;
5716 }
5717
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005718 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5719 firstClass = true;
5720
qining25262b32016-05-06 17:25:16 -04005721 if (firstClass) {
5722 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005723 decorations.addNoContraction(builder, result);
5724 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005725 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005726 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005727
LoopDawg592860c2016-06-09 08:57:35 -06005728 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005729 // The result type of all of them is the same type as the (a) matrix operand.
5730 // The algorithm is to:
5731 // - break the matrix(es) into vectors
5732 // - smear any scalar to a vector
5733 // - do vector operations
5734 // - make a matrix out the vector results
5735 switch (op) {
5736 case spv::OpFAdd:
5737 case spv::OpFSub:
5738 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005739 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005740 case spv::OpFMul:
5741 {
5742 // one time set up...
5743 bool leftMat = builder.isMatrix(left);
5744 bool rightMat = builder.isMatrix(right);
5745 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5746 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5747 spv::Id scalarType = builder.getScalarTypeId(typeId);
5748 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5749 std::vector<spv::Id> results;
5750 spv::Id smearVec = spv::NoResult;
5751 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005752 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005753 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005754 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005755
5756 // do each vector op
5757 for (unsigned int c = 0; c < numCols; ++c) {
5758 std::vector<unsigned int> indexes;
5759 indexes.push_back(c);
5760 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5761 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005762 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005763 decorations.addNoContraction(builder, result);
5764 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005765 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005766 }
5767
5768 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005769 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005770 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005771 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005772 }
5773 default:
5774 assert(0);
5775 return spv::NoResult;
5776 }
5777}
5778
John Kessenichead86222018-03-28 18:01:20 -06005779spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005780 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005781{
5782 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005783 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005784 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005785 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5786 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005787
5788 switch (op) {
5789 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005790 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005791 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005792 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005793 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005794 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005795 unaryOp = spv::OpSNegate;
5796 break;
5797
5798 case glslang::EOpLogicalNot:
5799 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005800 unaryOp = spv::OpLogicalNot;
5801 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005802 case glslang::EOpBitwiseNot:
5803 unaryOp = spv::OpNot;
5804 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005805
John Kessenich140f3df2015-06-26 16:58:36 -06005806 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005807 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005808 break;
5809 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005810 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005811 break;
5812 case glslang::EOpTranspose:
5813 unaryOp = spv::OpTranspose;
5814 break;
5815
5816 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005817 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005818 break;
5819 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005820 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005821 break;
5822 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005823 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005824 break;
5825 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005826 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005827 break;
5828 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005829 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005830 break;
5831 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005832 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005833 break;
5834 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005835 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005836 break;
5837 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005838 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005839 break;
5840
5841 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005842 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005843 break;
5844 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005845 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005846 break;
5847 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005848 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005849 break;
5850 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005851 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005852 break;
5853 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005854 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005855 break;
5856 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005857 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005858 break;
5859
5860 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005861 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005862 break;
5863 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005864 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005865 break;
5866
5867 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005868 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005869 break;
5870 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005871 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005872 break;
5873 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005874 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005875 break;
5876 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005877 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005878 break;
5879 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005880 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005881 break;
5882 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005883 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005884 break;
5885
5886 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005887 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005888 break;
5889 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005890 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005891 break;
5892 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005893 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005894 break;
5895 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005896 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005897 break;
5898 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005899 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005900 break;
5901 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005902 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005903 break;
5904
5905 case glslang::EOpIsNan:
5906 unaryOp = spv::OpIsNan;
5907 break;
5908 case glslang::EOpIsInf:
5909 unaryOp = spv::OpIsInf;
5910 break;
LoopDawg592860c2016-06-09 08:57:35 -06005911 case glslang::EOpIsFinite:
5912 unaryOp = spv::OpIsFinite;
5913 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005914
Rex Xucbc426e2015-12-15 16:03:10 +08005915 case glslang::EOpFloatBitsToInt:
5916 case glslang::EOpFloatBitsToUint:
5917 case glslang::EOpIntBitsToFloat:
5918 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005919 case glslang::EOpDoubleBitsToInt64:
5920 case glslang::EOpDoubleBitsToUint64:
5921 case glslang::EOpInt64BitsToDouble:
5922 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005923 case glslang::EOpFloat16BitsToInt16:
5924 case glslang::EOpFloat16BitsToUint16:
5925 case glslang::EOpInt16BitsToFloat16:
5926 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005927 unaryOp = spv::OpBitcast;
5928 break;
5929
John Kessenich140f3df2015-06-26 16:58:36 -06005930 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005931 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005932 break;
5933 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005934 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005935 break;
5936 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005937 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005938 break;
5939 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005940 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005941 break;
5942 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005943 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005944 break;
5945 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005946 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005947 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005948#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005949 case glslang::EOpPackSnorm4x8:
5950 libCall = spv::GLSLstd450PackSnorm4x8;
5951 break;
5952 case glslang::EOpUnpackSnorm4x8:
5953 libCall = spv::GLSLstd450UnpackSnorm4x8;
5954 break;
5955 case glslang::EOpPackUnorm4x8:
5956 libCall = spv::GLSLstd450PackUnorm4x8;
5957 break;
5958 case glslang::EOpUnpackUnorm4x8:
5959 libCall = spv::GLSLstd450UnpackUnorm4x8;
5960 break;
5961 case glslang::EOpPackDouble2x32:
5962 libCall = spv::GLSLstd450PackDouble2x32;
5963 break;
5964 case glslang::EOpUnpackDouble2x32:
5965 libCall = spv::GLSLstd450UnpackDouble2x32;
5966 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005967#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005968
Rex Xu8ff43de2016-04-22 16:51:45 +08005969 case glslang::EOpPackInt2x32:
5970 case glslang::EOpUnpackInt2x32:
5971 case glslang::EOpPackUint2x32:
5972 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005973 case glslang::EOpPack16:
5974 case glslang::EOpPack32:
5975 case glslang::EOpPack64:
5976 case glslang::EOpUnpack32:
5977 case glslang::EOpUnpack16:
5978 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005979 case glslang::EOpPackInt2x16:
5980 case glslang::EOpUnpackInt2x16:
5981 case glslang::EOpPackUint2x16:
5982 case glslang::EOpUnpackUint2x16:
5983 case glslang::EOpPackInt4x16:
5984 case glslang::EOpUnpackInt4x16:
5985 case glslang::EOpPackUint4x16:
5986 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005987 case glslang::EOpPackFloat2x16:
5988 case glslang::EOpUnpackFloat2x16:
5989 unaryOp = spv::OpBitcast;
5990 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005991
John Kessenich140f3df2015-06-26 16:58:36 -06005992 case glslang::EOpDPdx:
5993 unaryOp = spv::OpDPdx;
5994 break;
5995 case glslang::EOpDPdy:
5996 unaryOp = spv::OpDPdy;
5997 break;
5998 case glslang::EOpFwidth:
5999 unaryOp = spv::OpFwidth;
6000 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006001
John Kessenich140f3df2015-06-26 16:58:36 -06006002 case glslang::EOpAny:
6003 unaryOp = spv::OpAny;
6004 break;
6005 case glslang::EOpAll:
6006 unaryOp = spv::OpAll;
6007 break;
6008
6009 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06006010 if (isFloat)
6011 libCall = spv::GLSLstd450FAbs;
6012 else
6013 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06006014 break;
6015 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06006016 if (isFloat)
6017 libCall = spv::GLSLstd450FSign;
6018 else
6019 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06006020 break;
6021
John Kessenicha28f7a72019-08-06 07:00:58 -06006022#ifndef GLSLANG_WEB
6023 case glslang::EOpDPdxFine:
6024 unaryOp = spv::OpDPdxFine;
6025 break;
6026 case glslang::EOpDPdyFine:
6027 unaryOp = spv::OpDPdyFine;
6028 break;
6029 case glslang::EOpFwidthFine:
6030 unaryOp = spv::OpFwidthFine;
6031 break;
6032 case glslang::EOpDPdxCoarse:
6033 unaryOp = spv::OpDPdxCoarse;
6034 break;
6035 case glslang::EOpDPdyCoarse:
6036 unaryOp = spv::OpDPdyCoarse;
6037 break;
6038 case glslang::EOpFwidthCoarse:
6039 unaryOp = spv::OpFwidthCoarse;
6040 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04006041 case glslang::EOpRayQueryProceed:
6042 unaryOp = spv::OpRayQueryProceedKHR;
6043 break;
6044 case glslang::EOpRayQueryGetRayTMin:
6045 unaryOp = spv::OpRayQueryGetRayTMinKHR;
6046 break;
6047 case glslang::EOpRayQueryGetRayFlags:
6048 unaryOp = spv::OpRayQueryGetRayFlagsKHR;
6049 break;
6050 case glslang::EOpRayQueryGetWorldRayOrigin:
6051 unaryOp = spv::OpRayQueryGetWorldRayOriginKHR;
6052 break;
6053 case glslang::EOpRayQueryGetWorldRayDirection:
6054 unaryOp = spv::OpRayQueryGetWorldRayDirectionKHR;
6055 break;
6056 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
6057 unaryOp = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
6058 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006059 case glslang::EOpInterpolateAtCentroid:
6060 if (typeProxy == glslang::EbtFloat16)
6061 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6062 libCall = spv::GLSLstd450InterpolateAtCentroid;
6063 break;
John Kessenichfc51d282015-08-19 13:34:18 -06006064 case glslang::EOpAtomicCounterIncrement:
6065 case glslang::EOpAtomicCounterDecrement:
6066 case glslang::EOpAtomicCounter:
6067 {
6068 // Handle all of the atomics in one place, in createAtomicOperation()
6069 std::vector<spv::Id> operands;
6070 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006071 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06006072 }
6073
John Kessenichfc51d282015-08-19 13:34:18 -06006074 case glslang::EOpBitFieldReverse:
6075 unaryOp = spv::OpBitReverse;
6076 break;
6077 case glslang::EOpBitCount:
6078 unaryOp = spv::OpBitCount;
6079 break;
6080 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006081 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006082 break;
6083 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006084 if (isUnsigned)
6085 libCall = spv::GLSLstd450FindUMsb;
6086 else
6087 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006088 break;
6089
Ian Romanickb3bd4022019-01-21 08:57:25 -08006090 case glslang::EOpCountLeadingZeros:
6091 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6092 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6093 unaryOp = spv::OpUCountLeadingZerosINTEL;
6094 break;
6095
6096 case glslang::EOpCountTrailingZeros:
6097 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6098 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6099 unaryOp = spv::OpUCountTrailingZerosINTEL;
6100 break;
6101
Rex Xu574ab042016-04-14 16:53:07 +08006102 case glslang::EOpBallot:
6103 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006104 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006105 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08006106 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08006107 case glslang::EOpMinInvocations:
6108 case glslang::EOpMaxInvocations:
6109 case glslang::EOpAddInvocations:
6110 case glslang::EOpMinInvocationsNonUniform:
6111 case glslang::EOpMaxInvocationsNonUniform:
6112 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006113 case glslang::EOpMinInvocationsInclusiveScan:
6114 case glslang::EOpMaxInvocationsInclusiveScan:
6115 case glslang::EOpAddInvocationsInclusiveScan:
6116 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6117 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6118 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6119 case glslang::EOpMinInvocationsExclusiveScan:
6120 case glslang::EOpMaxInvocationsExclusiveScan:
6121 case glslang::EOpAddInvocationsExclusiveScan:
6122 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6123 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6124 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08006125 {
6126 std::vector<spv::Id> operands;
6127 operands.push_back(operand);
6128 return createInvocationsOperation(op, typeId, operands, typeProxy);
6129 }
John Kessenich66011cb2018-03-06 16:12:04 -07006130 case glslang::EOpSubgroupAll:
6131 case glslang::EOpSubgroupAny:
6132 case glslang::EOpSubgroupAllEqual:
6133 case glslang::EOpSubgroupBroadcastFirst:
6134 case glslang::EOpSubgroupBallot:
6135 case glslang::EOpSubgroupInverseBallot:
6136 case glslang::EOpSubgroupBallotBitCount:
6137 case glslang::EOpSubgroupBallotInclusiveBitCount:
6138 case glslang::EOpSubgroupBallotExclusiveBitCount:
6139 case glslang::EOpSubgroupBallotFindLSB:
6140 case glslang::EOpSubgroupBallotFindMSB:
6141 case glslang::EOpSubgroupAdd:
6142 case glslang::EOpSubgroupMul:
6143 case glslang::EOpSubgroupMin:
6144 case glslang::EOpSubgroupMax:
6145 case glslang::EOpSubgroupAnd:
6146 case glslang::EOpSubgroupOr:
6147 case glslang::EOpSubgroupXor:
6148 case glslang::EOpSubgroupInclusiveAdd:
6149 case glslang::EOpSubgroupInclusiveMul:
6150 case glslang::EOpSubgroupInclusiveMin:
6151 case glslang::EOpSubgroupInclusiveMax:
6152 case glslang::EOpSubgroupInclusiveAnd:
6153 case glslang::EOpSubgroupInclusiveOr:
6154 case glslang::EOpSubgroupInclusiveXor:
6155 case glslang::EOpSubgroupExclusiveAdd:
6156 case glslang::EOpSubgroupExclusiveMul:
6157 case glslang::EOpSubgroupExclusiveMin:
6158 case glslang::EOpSubgroupExclusiveMax:
6159 case glslang::EOpSubgroupExclusiveAnd:
6160 case glslang::EOpSubgroupExclusiveOr:
6161 case glslang::EOpSubgroupExclusiveXor:
6162 case glslang::EOpSubgroupQuadSwapHorizontal:
6163 case glslang::EOpSubgroupQuadSwapVertical:
6164 case glslang::EOpSubgroupQuadSwapDiagonal: {
6165 std::vector<spv::Id> operands;
6166 operands.push_back(operand);
6167 return createSubgroupOperation(op, typeId, operands, typeProxy);
6168 }
Rex Xu9d93a232016-05-05 12:30:44 +08006169 case glslang::EOpMbcnt:
6170 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6171 libCall = spv::MbcntAMD;
6172 break;
6173
6174 case glslang::EOpCubeFaceIndex:
6175 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6176 libCall = spv::CubeFaceIndexAMD;
6177 break;
6178
6179 case glslang::EOpCubeFaceCoord:
6180 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6181 libCall = spv::CubeFaceCoordAMD;
6182 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006183 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006184 unaryOp = spv::OpGroupNonUniformPartitionNV;
6185 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006186 case glslang::EOpConstructReference:
6187 unaryOp = spv::OpBitcast;
6188 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006189#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006190
6191 case glslang::EOpCopyObject:
6192 unaryOp = spv::OpCopyObject;
6193 break;
6194
John Kessenich140f3df2015-06-26 16:58:36 -06006195 default:
6196 return 0;
6197 }
6198
6199 spv::Id id;
6200 if (libCall >= 0) {
6201 std::vector<spv::Id> args;
6202 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006203 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006204 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006205 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006206 }
John Kessenich140f3df2015-06-26 16:58:36 -06006207
John Kessenichb9197c82019-08-11 07:41:45 -06006208 decorations.addNoContraction(builder, id);
6209 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006210 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006211}
6212
John Kessenich7a53f762016-01-20 11:19:27 -07006213// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006214spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6215 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006216{
6217 // Handle unary operations vector by vector.
6218 // The result type is the same type as the original type.
6219 // The algorithm is to:
6220 // - break the matrix into vectors
6221 // - apply the operation to each vector
6222 // - make a matrix out the vector results
6223
6224 // get the types sorted out
6225 int numCols = builder.getNumColumns(operand);
6226 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006227 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6228 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006229 std::vector<spv::Id> results;
6230
6231 // do each vector op
6232 for (int c = 0; c < numCols; ++c) {
6233 std::vector<unsigned int> indexes;
6234 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006235 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6236 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006237 decorations.addNoContraction(builder, destVec);
6238 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006239 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006240 }
6241
6242 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006243 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006244 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006245 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006246}
6247
John Kessenichad7645f2018-06-04 19:11:25 -06006248// For converting integers where both the bitwidth and the signedness could
6249// change, but only do the width change here. The caller is still responsible
6250// for the signedness conversion.
6251spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006252{
John Kessenichad7645f2018-06-04 19:11:25 -06006253 // Get the result type width, based on the type to convert to.
6254 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006255 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006256 case glslang::EOpConvInt16ToUint8:
6257 case glslang::EOpConvIntToUint8:
6258 case glslang::EOpConvInt64ToUint8:
6259 case glslang::EOpConvUint16ToInt8:
6260 case glslang::EOpConvUintToInt8:
6261 case glslang::EOpConvUint64ToInt8:
6262 width = 8;
6263 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006264 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006265 case glslang::EOpConvIntToUint16:
6266 case glslang::EOpConvInt64ToUint16:
6267 case glslang::EOpConvUint8ToInt16:
6268 case glslang::EOpConvUintToInt16:
6269 case glslang::EOpConvUint64ToInt16:
6270 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006271 break;
6272 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006273 case glslang::EOpConvInt16ToUint:
6274 case glslang::EOpConvInt64ToUint:
6275 case glslang::EOpConvUint8ToInt:
6276 case glslang::EOpConvUint16ToInt:
6277 case glslang::EOpConvUint64ToInt:
6278 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006279 break;
6280 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006281 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006282 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006283 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006284 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006285 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006286 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006287 break;
6288
6289 default:
6290 assert(false && "Default missing");
6291 break;
6292 }
6293
John Kessenichad7645f2018-06-04 19:11:25 -06006294 // Get the conversion operation and result type,
6295 // based on the target width, but the source type.
6296 spv::Id type = spv::NoType;
6297 spv::Op convOp = spv::OpNop;
6298 switch(op) {
6299 case glslang::EOpConvInt8ToUint16:
6300 case glslang::EOpConvInt8ToUint:
6301 case glslang::EOpConvInt8ToUint64:
6302 case glslang::EOpConvInt16ToUint8:
6303 case glslang::EOpConvInt16ToUint:
6304 case glslang::EOpConvInt16ToUint64:
6305 case glslang::EOpConvIntToUint8:
6306 case glslang::EOpConvIntToUint16:
6307 case glslang::EOpConvIntToUint64:
6308 case glslang::EOpConvInt64ToUint8:
6309 case glslang::EOpConvInt64ToUint16:
6310 case glslang::EOpConvInt64ToUint:
6311 convOp = spv::OpSConvert;
6312 type = builder.makeIntType(width);
6313 break;
6314 default:
6315 convOp = spv::OpUConvert;
6316 type = builder.makeUintType(width);
6317 break;
6318 }
6319
John Kessenich66011cb2018-03-06 16:12:04 -07006320 if (vectorSize > 0)
6321 type = builder.makeVectorType(type, vectorSize);
6322
John Kessenichad7645f2018-06-04 19:11:25 -06006323 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006324}
6325
John Kessenichead86222018-03-28 18:01:20 -06006326spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6327 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006328{
6329 spv::Op convOp = spv::OpNop;
6330 spv::Id zero = 0;
6331 spv::Id one = 0;
6332
6333 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6334
6335 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006336 case glslang::EOpConvIntToBool:
6337 case glslang::EOpConvUintToBool:
6338 zero = builder.makeUintConstant(0);
6339 zero = makeSmearedConstant(zero, vectorSize);
6340 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006341 case glslang::EOpConvFloatToBool:
6342 zero = builder.makeFloatConstant(0.0F);
6343 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006344 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006345 case glslang::EOpConvBoolToFloat:
6346 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006347 zero = builder.makeFloatConstant(0.0F);
6348 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006349 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006350
John Kessenich140f3df2015-06-26 16:58:36 -06006351 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006352 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006353#ifndef GLSLANG_WEB
6354 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006355 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006356 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006357 } else
6358#endif
6359 {
6360 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006361 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006362 }
Rex Xucabbb782017-03-24 13:41:14 +08006363
John Kessenich140f3df2015-06-26 16:58:36 -06006364 convOp = spv::OpSelect;
6365 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006366
John Kessenich140f3df2015-06-26 16:58:36 -06006367 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006368 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006369#ifndef GLSLANG_WEB
6370 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006371 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006372 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006373 } else
6374#endif
6375 {
6376 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006377 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006378 }
Rex Xucabbb782017-03-24 13:41:14 +08006379
John Kessenich140f3df2015-06-26 16:58:36 -06006380 convOp = spv::OpSelect;
6381 break;
6382
John Kessenich66011cb2018-03-06 16:12:04 -07006383 case glslang::EOpConvInt8ToFloat16:
6384 case glslang::EOpConvInt8ToFloat:
6385 case glslang::EOpConvInt8ToDouble:
6386 case glslang::EOpConvInt16ToFloat16:
6387 case glslang::EOpConvInt16ToFloat:
6388 case glslang::EOpConvInt16ToDouble:
6389 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006390 case glslang::EOpConvIntToFloat:
6391 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006392 case glslang::EOpConvInt64ToFloat:
6393 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006394 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006395 convOp = spv::OpConvertSToF;
6396 break;
6397
John Kessenich66011cb2018-03-06 16:12:04 -07006398 case glslang::EOpConvUint8ToFloat16:
6399 case glslang::EOpConvUint8ToFloat:
6400 case glslang::EOpConvUint8ToDouble:
6401 case glslang::EOpConvUint16ToFloat16:
6402 case glslang::EOpConvUint16ToFloat:
6403 case glslang::EOpConvUint16ToDouble:
6404 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006405 case glslang::EOpConvUintToFloat:
6406 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006407 case glslang::EOpConvUint64ToFloat:
6408 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006409 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006410 convOp = spv::OpConvertUToF;
6411 break;
6412
John Kessenich66011cb2018-03-06 16:12:04 -07006413 case glslang::EOpConvFloat16ToInt8:
6414 case glslang::EOpConvFloatToInt8:
6415 case glslang::EOpConvDoubleToInt8:
6416 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006417 case glslang::EOpConvFloatToInt16:
6418 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006419 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006420 case glslang::EOpConvFloatToInt:
6421 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006422 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006423 case glslang::EOpConvFloatToInt64:
6424 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006425 convOp = spv::OpConvertFToS;
6426 break;
6427
John Kessenich66011cb2018-03-06 16:12:04 -07006428 case glslang::EOpConvUint8ToInt8:
6429 case glslang::EOpConvInt8ToUint8:
6430 case glslang::EOpConvUint16ToInt16:
6431 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006432 case glslang::EOpConvUintToInt:
6433 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006434 case glslang::EOpConvUint64ToInt64:
6435 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006436 if (builder.isInSpecConstCodeGenMode()) {
6437 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006438#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006439 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6440 zero = builder.makeUint8Constant(0);
6441 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006442 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006443 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6444 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006445 } else
6446#endif
6447 {
Rex Xucabbb782017-03-24 13:41:14 +08006448 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006449 }
qining189b2032016-04-12 23:16:20 -04006450 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006451 // Use OpIAdd, instead of OpBitcast to do the conversion when
6452 // generating for OpSpecConstantOp instruction.
6453 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6454 }
6455 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006456 convOp = spv::OpBitcast;
6457 break;
6458
John Kessenich66011cb2018-03-06 16:12:04 -07006459 case glslang::EOpConvFloat16ToUint8:
6460 case glslang::EOpConvFloatToUint8:
6461 case glslang::EOpConvDoubleToUint8:
6462 case glslang::EOpConvFloat16ToUint16:
6463 case glslang::EOpConvFloatToUint16:
6464 case glslang::EOpConvDoubleToUint16:
6465 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006466 case glslang::EOpConvFloatToUint:
6467 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006468 case glslang::EOpConvFloatToUint64:
6469 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006470 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006471 convOp = spv::OpConvertFToU;
6472 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006473
John Kessenich39697cd2019-08-08 10:35:51 -06006474#ifndef GLSLANG_WEB
6475 case glslang::EOpConvInt8ToBool:
6476 case glslang::EOpConvUint8ToBool:
6477 zero = builder.makeUint8Constant(0);
6478 zero = makeSmearedConstant(zero, vectorSize);
6479 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6480 case glslang::EOpConvInt16ToBool:
6481 case glslang::EOpConvUint16ToBool:
6482 zero = builder.makeUint16Constant(0);
6483 zero = makeSmearedConstant(zero, vectorSize);
6484 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6485 case glslang::EOpConvInt64ToBool:
6486 case glslang::EOpConvUint64ToBool:
6487 zero = builder.makeUint64Constant(0);
6488 zero = makeSmearedConstant(zero, vectorSize);
6489 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6490 case glslang::EOpConvDoubleToBool:
6491 zero = builder.makeDoubleConstant(0.0);
6492 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006493 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006494 case glslang::EOpConvFloat16ToBool:
6495 zero = builder.makeFloat16Constant(0.0F);
6496 zero = makeSmearedConstant(zero, vectorSize);
Graeme Leese65ce5662020-06-05 13:32:51 +01006497 return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
John Kessenich39697cd2019-08-08 10:35:51 -06006498 case glslang::EOpConvBoolToDouble:
6499 convOp = spv::OpSelect;
6500 zero = builder.makeDoubleConstant(0.0);
6501 one = builder.makeDoubleConstant(1.0);
6502 break;
6503 case glslang::EOpConvBoolToFloat16:
6504 convOp = spv::OpSelect;
6505 zero = builder.makeFloat16Constant(0.0F);
6506 one = builder.makeFloat16Constant(1.0F);
6507 break;
6508 case glslang::EOpConvBoolToInt8:
6509 zero = builder.makeInt8Constant(0);
6510 one = builder.makeInt8Constant(1);
6511 convOp = spv::OpSelect;
6512 break;
6513 case glslang::EOpConvBoolToUint8:
6514 zero = builder.makeUint8Constant(0);
6515 one = builder.makeUint8Constant(1);
6516 convOp = spv::OpSelect;
6517 break;
6518 case glslang::EOpConvBoolToInt16:
6519 zero = builder.makeInt16Constant(0);
6520 one = builder.makeInt16Constant(1);
6521 convOp = spv::OpSelect;
6522 break;
6523 case glslang::EOpConvBoolToUint16:
6524 zero = builder.makeUint16Constant(0);
6525 one = builder.makeUint16Constant(1);
6526 convOp = spv::OpSelect;
6527 break;
6528 case glslang::EOpConvDoubleToFloat:
6529 case glslang::EOpConvFloatToDouble:
6530 case glslang::EOpConvDoubleToFloat16:
6531 case glslang::EOpConvFloat16ToDouble:
6532 case glslang::EOpConvFloatToFloat16:
6533 case glslang::EOpConvFloat16ToFloat:
6534 convOp = spv::OpFConvert;
6535 if (builder.isMatrixType(destType))
6536 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6537 break;
6538
John Kessenich66011cb2018-03-06 16:12:04 -07006539 case glslang::EOpConvInt8ToInt16:
6540 case glslang::EOpConvInt8ToInt:
6541 case glslang::EOpConvInt8ToInt64:
6542 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006543 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006544 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006545 case glslang::EOpConvIntToInt8:
6546 case glslang::EOpConvIntToInt16:
6547 case glslang::EOpConvIntToInt64:
6548 case glslang::EOpConvInt64ToInt8:
6549 case glslang::EOpConvInt64ToInt16:
6550 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006551 convOp = spv::OpSConvert;
6552 break;
6553
John Kessenich66011cb2018-03-06 16:12:04 -07006554 case glslang::EOpConvUint8ToUint16:
6555 case glslang::EOpConvUint8ToUint:
6556 case glslang::EOpConvUint8ToUint64:
6557 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006558 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006559 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006560 case glslang::EOpConvUintToUint8:
6561 case glslang::EOpConvUintToUint16:
6562 case glslang::EOpConvUintToUint64:
6563 case glslang::EOpConvUint64ToUint8:
6564 case glslang::EOpConvUint64ToUint16:
6565 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006566 convOp = spv::OpUConvert;
6567 break;
6568
John Kessenich66011cb2018-03-06 16:12:04 -07006569 case glslang::EOpConvInt8ToUint16:
6570 case glslang::EOpConvInt8ToUint:
6571 case glslang::EOpConvInt8ToUint64:
6572 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006573 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006574 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006575 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006576 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006577 case glslang::EOpConvIntToUint64:
6578 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006579 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006580 case glslang::EOpConvInt64ToUint:
6581 case glslang::EOpConvUint8ToInt16:
6582 case glslang::EOpConvUint8ToInt:
6583 case glslang::EOpConvUint8ToInt64:
6584 case glslang::EOpConvUint16ToInt8:
6585 case glslang::EOpConvUint16ToInt:
6586 case glslang::EOpConvUint16ToInt64:
6587 case glslang::EOpConvUintToInt8:
6588 case glslang::EOpConvUintToInt16:
6589 case glslang::EOpConvUintToInt64:
6590 case glslang::EOpConvUint64ToInt8:
6591 case glslang::EOpConvUint64ToInt16:
6592 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006593 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006594 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006595
6596 if (builder.isInSpecConstCodeGenMode()) {
6597 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006598 switch(op) {
6599 case glslang::EOpConvInt16ToUint8:
6600 case glslang::EOpConvIntToUint8:
6601 case glslang::EOpConvInt64ToUint8:
6602 case glslang::EOpConvUint16ToInt8:
6603 case glslang::EOpConvUintToInt8:
6604 case glslang::EOpConvUint64ToInt8:
6605 zero = builder.makeUint8Constant(0);
6606 break;
6607 case glslang::EOpConvInt8ToUint16:
6608 case glslang::EOpConvIntToUint16:
6609 case glslang::EOpConvInt64ToUint16:
6610 case glslang::EOpConvUint8ToInt16:
6611 case glslang::EOpConvUintToInt16:
6612 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006613 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006614 break;
6615 case glslang::EOpConvInt8ToUint:
6616 case glslang::EOpConvInt16ToUint:
6617 case glslang::EOpConvInt64ToUint:
6618 case glslang::EOpConvUint8ToInt:
6619 case glslang::EOpConvUint16ToInt:
6620 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006621 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006622 break;
6623 case glslang::EOpConvInt8ToUint64:
6624 case glslang::EOpConvInt16ToUint64:
6625 case glslang::EOpConvIntToUint64:
6626 case glslang::EOpConvUint8ToInt64:
6627 case glslang::EOpConvUint16ToInt64:
6628 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006629 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006630 break;
6631 default:
6632 assert(false && "Default missing");
6633 break;
6634 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006635 zero = makeSmearedConstant(zero, vectorSize);
6636 // Use OpIAdd, instead of OpBitcast to do the conversion when
6637 // generating for OpSpecConstantOp instruction.
6638 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6639 }
6640 // For normal run-time conversion instruction, use OpBitcast.
6641 convOp = spv::OpBitcast;
6642 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006643 case glslang::EOpConvUint64ToPtr:
6644 convOp = spv::OpConvertUToPtr;
6645 break;
6646 case glslang::EOpConvPtrToUint64:
6647 convOp = spv::OpConvertPtrToU;
6648 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006649 case glslang::EOpConvPtrToUvec2:
6650 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006651 if (builder.isVector(operand))
6652 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6653 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006654 convOp = spv::OpBitcast;
6655 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006656#endif
6657
John Kessenich140f3df2015-06-26 16:58:36 -06006658 default:
6659 break;
6660 }
6661
6662 spv::Id result = 0;
6663 if (convOp == spv::OpNop)
6664 return result;
6665
6666 if (convOp == spv::OpSelect) {
6667 zero = makeSmearedConstant(zero, vectorSize);
6668 one = makeSmearedConstant(one, vectorSize);
6669 result = builder.createTriOp(convOp, destType, operand, one, zero);
6670 } else
6671 result = builder.createUnaryOp(convOp, destType, operand);
6672
John Kessenichead86222018-03-28 18:01:20 -06006673 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006674 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006675 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006676}
6677
6678spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6679{
6680 if (vectorSize == 0)
6681 return constant;
6682
6683 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6684 std::vector<spv::Id> components;
6685 for (int c = 0; c < vectorSize; ++c)
6686 components.push_back(constant);
6687 return builder.makeCompositeConstant(vectorTypeId, components);
6688}
6689
John Kessenich426394d2015-07-23 10:22:48 -06006690// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006691spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6692 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6693 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006694{
6695 spv::Op opCode = spv::OpNop;
6696
6697 switch (op) {
6698 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006699 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006700 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006701 opCode = spv::OpAtomicIAdd;
Vikram Kushwaha79b93922020-07-19 15:45:01 -07006702 if (typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble) {
6703 opCode = spv::OpAtomicFAddEXT;
6704 builder.addExtension(spv::E_SPV_EXT_shader_atomic_float_add);
6705 if (typeProxy == glslang::EbtFloat)
6706 builder.addCapability(spv::CapabilityAtomicFloat32AddEXT);
6707 else
6708 builder.addCapability(spv::CapabilityAtomicFloat64AddEXT);
6709 }
John Kessenich426394d2015-07-23 10:22:48 -06006710 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006711 case glslang::EOpAtomicCounterSubtract:
6712 opCode = spv::OpAtomicISub;
6713 break;
John Kessenich426394d2015-07-23 10:22:48 -06006714 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006715 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006716 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006717 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6718 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006719 break;
6720 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006721 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006722 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006723 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6724 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006725 break;
6726 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006727 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006728 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006729 opCode = spv::OpAtomicAnd;
6730 break;
6731 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006732 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006733 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006734 opCode = spv::OpAtomicOr;
6735 break;
6736 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006737 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006738 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006739 opCode = spv::OpAtomicXor;
6740 break;
6741 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006742 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006743 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006744 opCode = spv::OpAtomicExchange;
6745 break;
6746 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006747 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006748 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006749 opCode = spv::OpAtomicCompareExchange;
6750 break;
6751 case glslang::EOpAtomicCounterIncrement:
6752 opCode = spv::OpAtomicIIncrement;
6753 break;
6754 case glslang::EOpAtomicCounterDecrement:
6755 opCode = spv::OpAtomicIDecrement;
6756 break;
6757 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006758 case glslang::EOpImageAtomicLoad:
6759 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006760 opCode = spv::OpAtomicLoad;
6761 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006762 case glslang::EOpAtomicStore:
6763 case glslang::EOpImageAtomicStore:
6764 opCode = spv::OpAtomicStore;
6765 break;
John Kessenich426394d2015-07-23 10:22:48 -06006766 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006767 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006768 break;
6769 }
6770
Rex Xue8fe8b02017-09-26 15:42:56 +08006771 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6772 builder.addCapability(spv::CapabilityInt64Atomics);
6773
John Kessenich426394d2015-07-23 10:22:48 -06006774 // Sort out the operands
6775 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006776 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006777 // - compare-exchange swaps the value and comparator
6778 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006779 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006780 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6781 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6782 spv::Id scopeId;
6783 if (glslangIntermediate->usingVulkanMemoryModel()) {
6784 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6785 } else {
6786 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6787 }
6788 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006789 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6790 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006791 spv::MemorySemanticsVolatileMask :
6792 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006793 spv::Id semanticsId2 = semanticsId;
6794
6795 pointerId = operands[0];
6796 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6797 // no additional operands
6798 } else if (opCode == spv::OpAtomicCompareExchange) {
6799 compareId = operands[1];
6800 valueId = operands[2];
6801 if (operands.size() > 3) {
6802 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006803 semanticsId = builder.makeUintConstant(
6804 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6805 semanticsId2 = builder.makeUintConstant(
6806 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006807 }
6808 } else if (opCode == spv::OpAtomicLoad) {
6809 if (operands.size() > 1) {
6810 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006811 semanticsId = builder.makeUintConstant(
6812 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006813 }
6814 } else {
6815 // atomic store or RMW
6816 valueId = operands[1];
6817 if (operands.size() > 2) {
6818 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006819 semanticsId = builder.makeUintConstant
6820 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006821 }
Rex Xu04db3f52015-09-16 11:44:02 +08006822 }
John Kessenich426394d2015-07-23 10:22:48 -06006823
Jeff Bolz36831c92018-09-05 10:11:41 -05006824 // Check for capabilities
6825 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006826 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6827 spv::MemorySemanticsMakeVisibleKHRMask |
6828 spv::MemorySemanticsOutputMemoryKHRMask |
6829 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006830 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6831 }
John Kessenich426394d2015-07-23 10:22:48 -06006832
Jeff Bolz36831c92018-09-05 10:11:41 -05006833 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6834 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6835 }
John Kessenich48d6e792017-10-06 21:21:48 -06006836
Jeff Bolz36831c92018-09-05 10:11:41 -05006837 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6838 spvAtomicOperands.push_back(pointerId);
6839 spvAtomicOperands.push_back(scopeId);
6840 spvAtomicOperands.push_back(semanticsId);
6841 if (opCode == spv::OpAtomicCompareExchange) {
6842 spvAtomicOperands.push_back(semanticsId2);
6843 spvAtomicOperands.push_back(valueId);
6844 spvAtomicOperands.push_back(compareId);
6845 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6846 spvAtomicOperands.push_back(valueId);
6847 }
John Kessenich48d6e792017-10-06 21:21:48 -06006848
Jeff Bolz36831c92018-09-05 10:11:41 -05006849 if (opCode == spv::OpAtomicStore) {
6850 builder.createNoResultOp(opCode, spvAtomicOperands);
6851 return 0;
6852 } else {
6853 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6854
6855 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6856 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6857 if (op == glslang::EOpAtomicCounterDecrement)
6858 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6859
6860 return resultId;
6861 }
John Kessenich426394d2015-07-23 10:22:48 -06006862}
6863
John Kessenich91cef522016-05-05 16:45:40 -06006864// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07006865spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
6866 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006867{
John Kessenich66011cb2018-03-06 16:12:04 -07006868 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6869 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006870
Rex Xu51596642016-09-21 18:56:12 +08006871 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006872 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006873 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6874
chaocf200da82016-12-20 12:44:35 -08006875 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6876 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006877 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6878 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006879 } else if (op == glslang::EOpAnyInvocation ||
6880 op == glslang::EOpAllInvocations ||
6881 op == glslang::EOpAllInvocationsEqual) {
6882 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6883 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006884 } else {
6885 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006886 if (op == glslang::EOpMinInvocationsNonUniform ||
6887 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006888 op == glslang::EOpAddInvocationsNonUniform ||
6889 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6890 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6891 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6892 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6893 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6894 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006895 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006896
Rex Xu430ef402016-10-14 17:22:23 +08006897 switch (op) {
6898 case glslang::EOpMinInvocations:
6899 case glslang::EOpMaxInvocations:
6900 case glslang::EOpAddInvocations:
6901 case glslang::EOpMinInvocationsNonUniform:
6902 case glslang::EOpMaxInvocationsNonUniform:
6903 case glslang::EOpAddInvocationsNonUniform:
6904 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006905 break;
6906 case glslang::EOpMinInvocationsInclusiveScan:
6907 case glslang::EOpMaxInvocationsInclusiveScan:
6908 case glslang::EOpAddInvocationsInclusiveScan:
6909 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6910 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6911 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6912 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006913 break;
6914 case glslang::EOpMinInvocationsExclusiveScan:
6915 case glslang::EOpMaxInvocationsExclusiveScan:
6916 case glslang::EOpAddInvocationsExclusiveScan:
6917 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6918 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6919 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6920 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006921 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006922 default:
6923 break;
Rex Xu430ef402016-10-14 17:22:23 +08006924 }
John Kessenich149afc32018-08-14 13:31:43 -06006925 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6926 spvGroupOperands.push_back(scope);
6927 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006928 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006929 spvGroupOperands.push_back(groupOp);
6930 }
Rex Xu51596642016-09-21 18:56:12 +08006931 }
6932
John Kessenich149afc32018-08-14 13:31:43 -06006933 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6934 spv::IdImmediate op = { true, *opIt };
6935 spvGroupOperands.push_back(op);
6936 }
John Kessenich91cef522016-05-05 16:45:40 -06006937
6938 switch (op) {
6939 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006940 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006941 break;
John Kessenich91cef522016-05-05 16:45:40 -06006942 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006943 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006944 break;
John Kessenich91cef522016-05-05 16:45:40 -06006945 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006946 opCode = spv::OpSubgroupAllEqualKHR;
6947 break;
Rex Xu51596642016-09-21 18:56:12 +08006948 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006949 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006950 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006951 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006952 break;
6953 case glslang::EOpReadFirstInvocation:
6954 opCode = spv::OpSubgroupFirstInvocationKHR;
6955 break;
6956 case glslang::EOpBallot:
6957 {
6958 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6959 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6960 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6961 //
6962 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6963 //
6964 spv::Id uintType = builder.makeUintType(32);
6965 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6966 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6967
6968 std::vector<spv::Id> components;
6969 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6970 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6971
6972 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6973 return builder.createUnaryOp(spv::OpBitcast, typeId,
6974 builder.createCompositeConstruct(uvec2Type, components));
6975 }
6976
Rex Xu9d93a232016-05-05 12:30:44 +08006977 case glslang::EOpMinInvocations:
6978 case glslang::EOpMaxInvocations:
6979 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006980 case glslang::EOpMinInvocationsInclusiveScan:
6981 case glslang::EOpMaxInvocationsInclusiveScan:
6982 case glslang::EOpAddInvocationsInclusiveScan:
6983 case glslang::EOpMinInvocationsExclusiveScan:
6984 case glslang::EOpMaxInvocationsExclusiveScan:
6985 case glslang::EOpAddInvocationsExclusiveScan:
6986 if (op == glslang::EOpMinInvocations ||
6987 op == glslang::EOpMinInvocationsInclusiveScan ||
6988 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006989 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006990 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006991 else {
6992 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006993 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006994 else
Rex Xu51596642016-09-21 18:56:12 +08006995 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006996 }
Rex Xu430ef402016-10-14 17:22:23 +08006997 } else if (op == glslang::EOpMaxInvocations ||
6998 op == glslang::EOpMaxInvocationsInclusiveScan ||
6999 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08007000 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007001 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007002 else {
7003 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007004 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007005 else
Rex Xu51596642016-09-21 18:56:12 +08007006 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08007007 }
7008 } else {
7009 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007010 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08007011 else
Rex Xu51596642016-09-21 18:56:12 +08007012 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08007013 }
7014
Rex Xu2bbbe062016-08-23 15:41:05 +08007015 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007016 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007017
7018 break;
Rex Xu9d93a232016-05-05 12:30:44 +08007019 case glslang::EOpMinInvocationsNonUniform:
7020 case glslang::EOpMaxInvocationsNonUniform:
7021 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08007022 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
7023 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
7024 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
7025 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
7026 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
7027 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
7028 if (op == glslang::EOpMinInvocationsNonUniform ||
7029 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
7030 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007031 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007032 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007033 else {
7034 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007035 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007036 else
Rex Xu51596642016-09-21 18:56:12 +08007037 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007038 }
7039 }
Rex Xu430ef402016-10-14 17:22:23 +08007040 else if (op == glslang::EOpMaxInvocationsNonUniform ||
7041 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
7042 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007043 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007044 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007045 else {
7046 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007047 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007048 else
Rex Xu51596642016-09-21 18:56:12 +08007049 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007050 }
7051 }
7052 else {
7053 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007054 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007055 else
Rex Xu51596642016-09-21 18:56:12 +08007056 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007057 }
7058
Rex Xu2bbbe062016-08-23 15:41:05 +08007059 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007060 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007061
7062 break;
John Kessenich91cef522016-05-05 16:45:40 -06007063 default:
7064 logger->missingFunctionality("invocation operation");
7065 return spv::NoResult;
7066 }
Rex Xu51596642016-09-21 18:56:12 +08007067
7068 assert(opCode != spv::OpNop);
7069 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06007070}
7071
Rex Xu2bbbe062016-08-23 15:41:05 +08007072// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06007073spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
7074 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08007075{
7076 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
7077 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08007078 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08007079 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07007080 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
7081 op == spv::OpGroupSMinNonUniformAMD ||
7082 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
7083 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08007084 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
7085
7086 // Handle group invocation operations scalar by scalar.
7087 // The result type is the same type as the original type.
7088 // The algorithm is to:
7089 // - break the vector into scalars
7090 // - apply the operation to each scalar
7091 // - make a vector out the scalar results
7092
7093 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08007094 int numComponents = builder.getNumComponents(operands[0]);
7095 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08007096 std::vector<spv::Id> results;
7097
7098 // do each scalar op
7099 for (int comp = 0; comp < numComponents; ++comp) {
7100 std::vector<unsigned int> indexes;
7101 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06007102 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
7103 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08007104 if (op == spv::OpSubgroupReadInvocationKHR) {
7105 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007106 spv::IdImmediate operand = { true, operands[1] };
7107 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08007108 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06007109 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7110 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08007111 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007112 spv::IdImmediate operand = { true, operands[1] };
7113 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08007114 } else {
John Kessenich149afc32018-08-14 13:31:43 -06007115 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7116 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06007117 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007118 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08007119 spvGroupOperands.push_back(scalar);
7120 }
Rex Xu2bbbe062016-08-23 15:41:05 +08007121
Rex Xub7072052016-09-26 15:53:40 +08007122 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08007123 }
7124
7125 // put the pieces together
7126 return builder.createCompositeConstruct(typeId, results);
7127}
Rex Xu2bbbe062016-08-23 15:41:05 +08007128
John Kessenich66011cb2018-03-06 16:12:04 -07007129// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06007130spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
7131 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07007132{
7133 // Add the required capabilities.
7134 switch (op) {
7135 case glslang::EOpSubgroupElect:
7136 builder.addCapability(spv::CapabilityGroupNonUniform);
7137 break;
7138 case glslang::EOpSubgroupAll:
7139 case glslang::EOpSubgroupAny:
7140 case glslang::EOpSubgroupAllEqual:
7141 builder.addCapability(spv::CapabilityGroupNonUniform);
7142 builder.addCapability(spv::CapabilityGroupNonUniformVote);
7143 break;
7144 case glslang::EOpSubgroupBroadcast:
7145 case glslang::EOpSubgroupBroadcastFirst:
7146 case glslang::EOpSubgroupBallot:
7147 case glslang::EOpSubgroupInverseBallot:
7148 case glslang::EOpSubgroupBallotBitExtract:
7149 case glslang::EOpSubgroupBallotBitCount:
7150 case glslang::EOpSubgroupBallotInclusiveBitCount:
7151 case glslang::EOpSubgroupBallotExclusiveBitCount:
7152 case glslang::EOpSubgroupBallotFindLSB:
7153 case glslang::EOpSubgroupBallotFindMSB:
7154 builder.addCapability(spv::CapabilityGroupNonUniform);
7155 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
7156 break;
7157 case glslang::EOpSubgroupShuffle:
7158 case glslang::EOpSubgroupShuffleXor:
7159 builder.addCapability(spv::CapabilityGroupNonUniform);
7160 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
7161 break;
7162 case glslang::EOpSubgroupShuffleUp:
7163 case glslang::EOpSubgroupShuffleDown:
7164 builder.addCapability(spv::CapabilityGroupNonUniform);
7165 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
7166 break;
7167 case glslang::EOpSubgroupAdd:
7168 case glslang::EOpSubgroupMul:
7169 case glslang::EOpSubgroupMin:
7170 case glslang::EOpSubgroupMax:
7171 case glslang::EOpSubgroupAnd:
7172 case glslang::EOpSubgroupOr:
7173 case glslang::EOpSubgroupXor:
7174 case glslang::EOpSubgroupInclusiveAdd:
7175 case glslang::EOpSubgroupInclusiveMul:
7176 case glslang::EOpSubgroupInclusiveMin:
7177 case glslang::EOpSubgroupInclusiveMax:
7178 case glslang::EOpSubgroupInclusiveAnd:
7179 case glslang::EOpSubgroupInclusiveOr:
7180 case glslang::EOpSubgroupInclusiveXor:
7181 case glslang::EOpSubgroupExclusiveAdd:
7182 case glslang::EOpSubgroupExclusiveMul:
7183 case glslang::EOpSubgroupExclusiveMin:
7184 case glslang::EOpSubgroupExclusiveMax:
7185 case glslang::EOpSubgroupExclusiveAnd:
7186 case glslang::EOpSubgroupExclusiveOr:
7187 case glslang::EOpSubgroupExclusiveXor:
7188 builder.addCapability(spv::CapabilityGroupNonUniform);
7189 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
7190 break;
7191 case glslang::EOpSubgroupClusteredAdd:
7192 case glslang::EOpSubgroupClusteredMul:
7193 case glslang::EOpSubgroupClusteredMin:
7194 case glslang::EOpSubgroupClusteredMax:
7195 case glslang::EOpSubgroupClusteredAnd:
7196 case glslang::EOpSubgroupClusteredOr:
7197 case glslang::EOpSubgroupClusteredXor:
7198 builder.addCapability(spv::CapabilityGroupNonUniform);
7199 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7200 break;
7201 case glslang::EOpSubgroupQuadBroadcast:
7202 case glslang::EOpSubgroupQuadSwapHorizontal:
7203 case glslang::EOpSubgroupQuadSwapVertical:
7204 case glslang::EOpSubgroupQuadSwapDiagonal:
7205 builder.addCapability(spv::CapabilityGroupNonUniform);
7206 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7207 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007208 case glslang::EOpSubgroupPartitionedAdd:
7209 case glslang::EOpSubgroupPartitionedMul:
7210 case glslang::EOpSubgroupPartitionedMin:
7211 case glslang::EOpSubgroupPartitionedMax:
7212 case glslang::EOpSubgroupPartitionedAnd:
7213 case glslang::EOpSubgroupPartitionedOr:
7214 case glslang::EOpSubgroupPartitionedXor:
7215 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7216 case glslang::EOpSubgroupPartitionedInclusiveMul:
7217 case glslang::EOpSubgroupPartitionedInclusiveMin:
7218 case glslang::EOpSubgroupPartitionedInclusiveMax:
7219 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7220 case glslang::EOpSubgroupPartitionedInclusiveOr:
7221 case glslang::EOpSubgroupPartitionedInclusiveXor:
7222 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7223 case glslang::EOpSubgroupPartitionedExclusiveMul:
7224 case glslang::EOpSubgroupPartitionedExclusiveMin:
7225 case glslang::EOpSubgroupPartitionedExclusiveMax:
7226 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7227 case glslang::EOpSubgroupPartitionedExclusiveOr:
7228 case glslang::EOpSubgroupPartitionedExclusiveXor:
7229 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7230 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7231 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007232 default: assert(0 && "Unhandled subgroup operation!");
7233 }
7234
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007235
7236 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7237 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007238 const bool isBool = typeProxy == glslang::EbtBool;
7239
7240 spv::Op opCode = spv::OpNop;
7241
7242 // Figure out which opcode to use.
7243 switch (op) {
7244 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7245 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7246 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7247 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7248 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7249 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7250 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7251 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7252 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7253 case glslang::EOpSubgroupBallotBitCount:
7254 case glslang::EOpSubgroupBallotInclusiveBitCount:
7255 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7256 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7257 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7258 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7259 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7260 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7261 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7262 case glslang::EOpSubgroupAdd:
7263 case glslang::EOpSubgroupInclusiveAdd:
7264 case glslang::EOpSubgroupExclusiveAdd:
7265 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007266 case glslang::EOpSubgroupPartitionedAdd:
7267 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7268 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007269 if (isFloat) {
7270 opCode = spv::OpGroupNonUniformFAdd;
7271 } else {
7272 opCode = spv::OpGroupNonUniformIAdd;
7273 }
7274 break;
7275 case glslang::EOpSubgroupMul:
7276 case glslang::EOpSubgroupInclusiveMul:
7277 case glslang::EOpSubgroupExclusiveMul:
7278 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007279 case glslang::EOpSubgroupPartitionedMul:
7280 case glslang::EOpSubgroupPartitionedInclusiveMul:
7281 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007282 if (isFloat) {
7283 opCode = spv::OpGroupNonUniformFMul;
7284 } else {
7285 opCode = spv::OpGroupNonUniformIMul;
7286 }
7287 break;
7288 case glslang::EOpSubgroupMin:
7289 case glslang::EOpSubgroupInclusiveMin:
7290 case glslang::EOpSubgroupExclusiveMin:
7291 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007292 case glslang::EOpSubgroupPartitionedMin:
7293 case glslang::EOpSubgroupPartitionedInclusiveMin:
7294 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007295 if (isFloat) {
7296 opCode = spv::OpGroupNonUniformFMin;
7297 } else if (isUnsigned) {
7298 opCode = spv::OpGroupNonUniformUMin;
7299 } else {
7300 opCode = spv::OpGroupNonUniformSMin;
7301 }
7302 break;
7303 case glslang::EOpSubgroupMax:
7304 case glslang::EOpSubgroupInclusiveMax:
7305 case glslang::EOpSubgroupExclusiveMax:
7306 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007307 case glslang::EOpSubgroupPartitionedMax:
7308 case glslang::EOpSubgroupPartitionedInclusiveMax:
7309 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007310 if (isFloat) {
7311 opCode = spv::OpGroupNonUniformFMax;
7312 } else if (isUnsigned) {
7313 opCode = spv::OpGroupNonUniformUMax;
7314 } else {
7315 opCode = spv::OpGroupNonUniformSMax;
7316 }
7317 break;
7318 case glslang::EOpSubgroupAnd:
7319 case glslang::EOpSubgroupInclusiveAnd:
7320 case glslang::EOpSubgroupExclusiveAnd:
7321 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007322 case glslang::EOpSubgroupPartitionedAnd:
7323 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7324 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007325 if (isBool) {
7326 opCode = spv::OpGroupNonUniformLogicalAnd;
7327 } else {
7328 opCode = spv::OpGroupNonUniformBitwiseAnd;
7329 }
7330 break;
7331 case glslang::EOpSubgroupOr:
7332 case glslang::EOpSubgroupInclusiveOr:
7333 case glslang::EOpSubgroupExclusiveOr:
7334 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007335 case glslang::EOpSubgroupPartitionedOr:
7336 case glslang::EOpSubgroupPartitionedInclusiveOr:
7337 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007338 if (isBool) {
7339 opCode = spv::OpGroupNonUniformLogicalOr;
7340 } else {
7341 opCode = spv::OpGroupNonUniformBitwiseOr;
7342 }
7343 break;
7344 case glslang::EOpSubgroupXor:
7345 case glslang::EOpSubgroupInclusiveXor:
7346 case glslang::EOpSubgroupExclusiveXor:
7347 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007348 case glslang::EOpSubgroupPartitionedXor:
7349 case glslang::EOpSubgroupPartitionedInclusiveXor:
7350 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007351 if (isBool) {
7352 opCode = spv::OpGroupNonUniformLogicalXor;
7353 } else {
7354 opCode = spv::OpGroupNonUniformBitwiseXor;
7355 }
7356 break;
7357 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7358 case glslang::EOpSubgroupQuadSwapHorizontal:
7359 case glslang::EOpSubgroupQuadSwapVertical:
7360 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7361 default: assert(0 && "Unhandled subgroup operation!");
7362 }
7363
John Kessenich149afc32018-08-14 13:31:43 -06007364 // get the right Group Operation
7365 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007366 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007367 default:
7368 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007369 case glslang::EOpSubgroupBallotBitCount:
7370 case glslang::EOpSubgroupAdd:
7371 case glslang::EOpSubgroupMul:
7372 case glslang::EOpSubgroupMin:
7373 case glslang::EOpSubgroupMax:
7374 case glslang::EOpSubgroupAnd:
7375 case glslang::EOpSubgroupOr:
7376 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007377 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007378 break;
7379 case glslang::EOpSubgroupBallotInclusiveBitCount:
7380 case glslang::EOpSubgroupInclusiveAdd:
7381 case glslang::EOpSubgroupInclusiveMul:
7382 case glslang::EOpSubgroupInclusiveMin:
7383 case glslang::EOpSubgroupInclusiveMax:
7384 case glslang::EOpSubgroupInclusiveAnd:
7385 case glslang::EOpSubgroupInclusiveOr:
7386 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007387 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007388 break;
7389 case glslang::EOpSubgroupBallotExclusiveBitCount:
7390 case glslang::EOpSubgroupExclusiveAdd:
7391 case glslang::EOpSubgroupExclusiveMul:
7392 case glslang::EOpSubgroupExclusiveMin:
7393 case glslang::EOpSubgroupExclusiveMax:
7394 case glslang::EOpSubgroupExclusiveAnd:
7395 case glslang::EOpSubgroupExclusiveOr:
7396 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007397 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007398 break;
7399 case glslang::EOpSubgroupClusteredAdd:
7400 case glslang::EOpSubgroupClusteredMul:
7401 case glslang::EOpSubgroupClusteredMin:
7402 case glslang::EOpSubgroupClusteredMax:
7403 case glslang::EOpSubgroupClusteredAnd:
7404 case glslang::EOpSubgroupClusteredOr:
7405 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007406 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007407 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007408 case glslang::EOpSubgroupPartitionedAdd:
7409 case glslang::EOpSubgroupPartitionedMul:
7410 case glslang::EOpSubgroupPartitionedMin:
7411 case glslang::EOpSubgroupPartitionedMax:
7412 case glslang::EOpSubgroupPartitionedAnd:
7413 case glslang::EOpSubgroupPartitionedOr:
7414 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007415 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007416 break;
7417 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7418 case glslang::EOpSubgroupPartitionedInclusiveMul:
7419 case glslang::EOpSubgroupPartitionedInclusiveMin:
7420 case glslang::EOpSubgroupPartitionedInclusiveMax:
7421 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7422 case glslang::EOpSubgroupPartitionedInclusiveOr:
7423 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007424 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007425 break;
7426 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7427 case glslang::EOpSubgroupPartitionedExclusiveMul:
7428 case glslang::EOpSubgroupPartitionedExclusiveMin:
7429 case glslang::EOpSubgroupPartitionedExclusiveMax:
7430 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7431 case glslang::EOpSubgroupPartitionedExclusiveOr:
7432 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007433 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007434 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007435 }
7436
John Kessenich149afc32018-08-14 13:31:43 -06007437 // build the instruction
7438 std::vector<spv::IdImmediate> spvGroupOperands;
7439
7440 // Every operation begins with the Execution Scope operand.
7441 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7442 spvGroupOperands.push_back(executionScope);
7443
7444 // Next, for all operations that use a Group Operation, push that as an operand.
7445 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007446 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007447 spvGroupOperands.push_back(groupOperand);
7448 }
7449
John Kessenich66011cb2018-03-06 16:12:04 -07007450 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007451 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7452 spv::IdImmediate operand = { true, *opIt };
7453 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007454 }
7455
7456 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007457 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007458 switch (op) {
7459 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007460 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7461 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7462 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7463 }
7464 if (directionId != spv::NoResult) {
7465 spv::IdImmediate direction = { true, directionId };
7466 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007467 }
7468
7469 return builder.createOp(opCode, typeId, spvGroupOperands);
7470}
7471
John Kessenich8985fc92020-03-03 10:25:07 -07007472spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7473 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007474{
John Kessenich66011cb2018-03-06 16:12:04 -07007475 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7476 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007477
John Kessenich140f3df2015-06-26 16:58:36 -06007478 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007479 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007480 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007481 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007482 spv::Id typeId0 = 0;
7483 if (consumedOperands > 0)
7484 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007485 spv::Id typeId1 = 0;
7486 if (consumedOperands > 1)
7487 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007488 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007489
7490 switch (op) {
7491 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007492 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007493 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007494 else if (isUnsigned)
7495 libCall = spv::GLSLstd450UMin;
7496 else
7497 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007498 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007499 break;
7500 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007501 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007502 break;
7503 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007504 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007505 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007506 else if (isUnsigned)
7507 libCall = spv::GLSLstd450UMax;
7508 else
7509 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007510 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007511 break;
7512 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007513 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007514 break;
7515 case glslang::EOpDot:
7516 opCode = spv::OpDot;
7517 break;
7518 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007519 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007520 break;
7521
7522 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007523 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007524 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007525 else if (isUnsigned)
7526 libCall = spv::GLSLstd450UClamp;
7527 else
7528 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007529 builder.promoteScalar(precision, operands.front(), operands[1]);
7530 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007531 break;
7532 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007533 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7534 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007535 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007536 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007537 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007538 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007539 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007540 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007541 break;
7542 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007543 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007544 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007545 break;
7546 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007547 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007548 builder.promoteScalar(precision, operands[0], operands[2]);
7549 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007550 break;
7551
7552 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007553 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007554 break;
7555 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007556 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007557 break;
7558 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007559 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007560 break;
7561 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007562 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007563 break;
7564 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007565 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007566 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007567 case glslang::EOpBarrier:
7568 {
7569 // This is for the extended controlBarrier function, with four operands.
7570 // The unextended barrier() goes through createNoArgOperation.
7571 assert(operands.size() == 4);
7572 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7573 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7574 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007575 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7576 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007577 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7578 spv::MemorySemanticsMakeVisibleKHRMask |
7579 spv::MemorySemanticsOutputMemoryKHRMask |
7580 spv::MemorySemanticsVolatileMask)) {
7581 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7582 }
John Kessenich8985fc92020-03-03 10:25:07 -07007583 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7584 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007585 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7586 }
7587 return 0;
7588 }
7589 break;
7590 case glslang::EOpMemoryBarrier:
7591 {
7592 // This is for the extended memoryBarrier function, with three operands.
7593 // The unextended memoryBarrier() goes through createNoArgOperation.
7594 assert(operands.size() == 3);
7595 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7596 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7597 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7598 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7599 spv::MemorySemanticsMakeVisibleKHRMask |
7600 spv::MemorySemanticsOutputMemoryKHRMask |
7601 spv::MemorySemanticsVolatileMask)) {
7602 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7603 }
7604 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7605 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7606 }
7607 return 0;
7608 }
7609 break;
7610
John Kessenicha28f7a72019-08-06 07:00:58 -06007611#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007612 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007613 if (typeProxy == glslang::EbtFloat16)
7614 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007615 libCall = spv::GLSLstd450InterpolateAtSample;
7616 break;
7617 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007618 if (typeProxy == glslang::EbtFloat16)
7619 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007620 libCall = spv::GLSLstd450InterpolateAtOffset;
7621 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007622 case glslang::EOpAddCarry:
7623 opCode = spv::OpIAddCarry;
7624 typeId = builder.makeStructResultType(typeId0, typeId0);
7625 consumedOperands = 2;
7626 break;
7627 case glslang::EOpSubBorrow:
7628 opCode = spv::OpISubBorrow;
7629 typeId = builder.makeStructResultType(typeId0, typeId0);
7630 consumedOperands = 2;
7631 break;
7632 case glslang::EOpUMulExtended:
7633 opCode = spv::OpUMulExtended;
7634 typeId = builder.makeStructResultType(typeId0, typeId0);
7635 consumedOperands = 2;
7636 break;
7637 case glslang::EOpIMulExtended:
7638 opCode = spv::OpSMulExtended;
7639 typeId = builder.makeStructResultType(typeId0, typeId0);
7640 consumedOperands = 2;
7641 break;
7642 case glslang::EOpBitfieldExtract:
7643 if (isUnsigned)
7644 opCode = spv::OpBitFieldUExtract;
7645 else
7646 opCode = spv::OpBitFieldSExtract;
7647 break;
7648 case glslang::EOpBitfieldInsert:
7649 opCode = spv::OpBitFieldInsert;
7650 break;
7651
7652 case glslang::EOpFma:
7653 libCall = spv::GLSLstd450Fma;
7654 break;
7655 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007656 {
7657 libCall = spv::GLSLstd450FrexpStruct;
7658 assert(builder.isPointerType(typeId1));
7659 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007660 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007661 if (width == 16)
7662 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7663 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007664 if (builder.getNumComponents(operands[0]) == 1)
7665 frexpIntType = builder.makeIntegerType(width, true);
7666 else
John Kessenich8985fc92020-03-03 10:25:07 -07007667 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7668 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007669 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7670 consumedOperands = 1;
7671 }
John Kessenich55e7d112015-11-15 21:33:39 -07007672 break;
7673 case glslang::EOpLdexp:
7674 libCall = spv::GLSLstd450Ldexp;
7675 break;
7676
Rex Xu574ab042016-04-14 16:53:07 +08007677 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007678 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007679
John Kessenich66011cb2018-03-06 16:12:04 -07007680 case glslang::EOpSubgroupBroadcast:
7681 case glslang::EOpSubgroupBallotBitExtract:
7682 case glslang::EOpSubgroupShuffle:
7683 case glslang::EOpSubgroupShuffleXor:
7684 case glslang::EOpSubgroupShuffleUp:
7685 case glslang::EOpSubgroupShuffleDown:
7686 case glslang::EOpSubgroupClusteredAdd:
7687 case glslang::EOpSubgroupClusteredMul:
7688 case glslang::EOpSubgroupClusteredMin:
7689 case glslang::EOpSubgroupClusteredMax:
7690 case glslang::EOpSubgroupClusteredAnd:
7691 case glslang::EOpSubgroupClusteredOr:
7692 case glslang::EOpSubgroupClusteredXor:
7693 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007694 case glslang::EOpSubgroupPartitionedAdd:
7695 case glslang::EOpSubgroupPartitionedMul:
7696 case glslang::EOpSubgroupPartitionedMin:
7697 case glslang::EOpSubgroupPartitionedMax:
7698 case glslang::EOpSubgroupPartitionedAnd:
7699 case glslang::EOpSubgroupPartitionedOr:
7700 case glslang::EOpSubgroupPartitionedXor:
7701 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7702 case glslang::EOpSubgroupPartitionedInclusiveMul:
7703 case glslang::EOpSubgroupPartitionedInclusiveMin:
7704 case glslang::EOpSubgroupPartitionedInclusiveMax:
7705 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7706 case glslang::EOpSubgroupPartitionedInclusiveOr:
7707 case glslang::EOpSubgroupPartitionedInclusiveXor:
7708 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7709 case glslang::EOpSubgroupPartitionedExclusiveMul:
7710 case glslang::EOpSubgroupPartitionedExclusiveMin:
7711 case glslang::EOpSubgroupPartitionedExclusiveMax:
7712 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7713 case glslang::EOpSubgroupPartitionedExclusiveOr:
7714 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007715 return createSubgroupOperation(op, typeId, operands, typeProxy);
7716
Rex Xu9d93a232016-05-05 12:30:44 +08007717 case glslang::EOpSwizzleInvocations:
7718 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7719 libCall = spv::SwizzleInvocationsAMD;
7720 break;
7721 case glslang::EOpSwizzleInvocationsMasked:
7722 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7723 libCall = spv::SwizzleInvocationsMaskedAMD;
7724 break;
7725 case glslang::EOpWriteInvocation:
7726 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7727 libCall = spv::WriteInvocationAMD;
7728 break;
7729
7730 case glslang::EOpMin3:
7731 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7732 if (isFloat)
7733 libCall = spv::FMin3AMD;
7734 else {
7735 if (isUnsigned)
7736 libCall = spv::UMin3AMD;
7737 else
7738 libCall = spv::SMin3AMD;
7739 }
7740 break;
7741 case glslang::EOpMax3:
7742 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7743 if (isFloat)
7744 libCall = spv::FMax3AMD;
7745 else {
7746 if (isUnsigned)
7747 libCall = spv::UMax3AMD;
7748 else
7749 libCall = spv::SMax3AMD;
7750 }
7751 break;
7752 case glslang::EOpMid3:
7753 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7754 if (isFloat)
7755 libCall = spv::FMid3AMD;
7756 else {
7757 if (isUnsigned)
7758 libCall = spv::UMid3AMD;
7759 else
7760 libCall = spv::SMid3AMD;
7761 }
7762 break;
7763
7764 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007765 if (typeProxy == glslang::EbtFloat16)
7766 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007767 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7768 libCall = spv::InterpolateAtVertexAMD;
7769 break;
Chao Chen3c366992018-09-19 11:41:59 -07007770
Daniel Kochdb32b242020-03-17 20:42:47 -04007771 case glslang::EOpReportIntersection:
Chao Chenb50c02e2018-09-19 11:42:24 -07007772 typeId = builder.makeBoolType();
Daniel Kochdb32b242020-03-17 20:42:47 -04007773 opCode = spv::OpReportIntersectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007774 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04007775 case glslang::EOpTrace:
Daniel Kochdb32b242020-03-17 20:42:47 -04007776 builder.createNoResultOp(spv::OpTraceRayKHR, operands);
Ashwin Leleff1783d2018-10-22 16:41:44 -07007777 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04007778 case glslang::EOpExecuteCallable:
Daniel Kochdb32b242020-03-17 20:42:47 -04007779 builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007780 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007781
7782 case glslang::EOpRayQueryInitialize:
Torosdagli06c2eee2020-03-19 11:09:57 -04007783 builder.createNoResultOp(spv::OpRayQueryInitializeKHR, operands);
7784 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007785 case glslang::EOpRayQueryTerminate:
Torosdagli06c2eee2020-03-19 11:09:57 -04007786 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operands);
7787 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007788 case glslang::EOpRayQueryGenerateIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007789 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR, operands);
7790 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007791 case glslang::EOpRayQueryConfirmIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007792 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operands);
7793 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007794 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04007795 typeId = builder.makeBoolType();
7796 opCode = spv::OpRayQueryProceedKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007797 break;
7798 case glslang::EOpRayQueryGetIntersectionType:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007799 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007800 opCode = spv::OpRayQueryGetIntersectionTypeKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007801 break;
7802 case glslang::EOpRayQueryGetRayTMin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007803 typeId = builder.makeFloatType(32);
7804 opCode = spv::OpRayQueryGetRayTMinKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007805 break;
7806 case glslang::EOpRayQueryGetRayFlags:
Torosdagli06c2eee2020-03-19 11:09:57 -04007807 typeId = builder.makeIntType(32);
7808 opCode = spv::OpRayQueryGetRayFlagsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007809 break;
7810 case glslang::EOpRayQueryGetIntersectionT:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007811 typeId = builder.makeFloatType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007812 opCode = spv::OpRayQueryGetIntersectionTKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007813 break;
7814 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007815 typeId = builder.makeIntType(32);
7816 opCode = spv::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007817 break;
7818 case glslang::EOpRayQueryGetIntersectionInstanceId:
Torosdagli06c2eee2020-03-19 11:09:57 -04007819 typeId = builder.makeIntType(32);
7820 opCode = spv::OpRayQueryGetIntersectionInstanceIdKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007821 break;
7822 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
Torosdagli06c2eee2020-03-19 11:09:57 -04007823 typeId = builder.makeIntType(32);
7824 opCode = spv::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007825 break;
7826 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007827 typeId = builder.makeIntType(32);
7828 opCode = spv::OpRayQueryGetIntersectionGeometryIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007829 break;
7830 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007831 typeId = builder.makeIntType(32);
7832 opCode = spv::OpRayQueryGetIntersectionPrimitiveIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007833 break;
7834 case glslang::EOpRayQueryGetIntersectionBarycentrics:
Torosdagli06c2eee2020-03-19 11:09:57 -04007835 typeId = builder.makeVectorType(builder.makeFloatType(32), 2);
7836 opCode = spv::OpRayQueryGetIntersectionBarycentricsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007837 break;
7838 case glslang::EOpRayQueryGetIntersectionFrontFace:
Torosdagli06c2eee2020-03-19 11:09:57 -04007839 typeId = builder.makeBoolType();
7840 opCode = spv::OpRayQueryGetIntersectionFrontFaceKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007841 break;
7842 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
Torosdagli06c2eee2020-03-19 11:09:57 -04007843 typeId = builder.makeBoolType();
7844 opCode = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007845 break;
7846 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007847 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7848 opCode = spv::OpRayQueryGetIntersectionObjectRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007849 break;
7850 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007851 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7852 opCode = spv::OpRayQueryGetIntersectionObjectRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007853 break;
7854 case glslang::EOpRayQueryGetWorldRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007855 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7856 opCode = spv::OpRayQueryGetWorldRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007857 break;
7858 case glslang::EOpRayQueryGetWorldRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007859 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7860 opCode = spv::OpRayQueryGetWorldRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007861 break;
7862 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
Torosdagli06c2eee2020-03-19 11:09:57 -04007863 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007864 opCode = spv::OpRayQueryGetIntersectionObjectToWorldKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007865 break;
7866 case glslang::EOpRayQueryGetIntersectionWorldToObject:
Torosdagli06c2eee2020-03-19 11:09:57 -04007867 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007868 opCode = spv::OpRayQueryGetIntersectionWorldToObjectKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007869 break;
Chao Chen3c366992018-09-19 11:41:59 -07007870 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7871 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7872 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007873 case glslang::EOpCooperativeMatrixMulAdd:
7874 opCode = spv::OpCooperativeMatrixMulAddNV;
7875 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007876#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007877 default:
7878 return 0;
7879 }
7880
7881 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007882 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007883 // Use an extended instruction from the standard library.
7884 // Construct the call arguments, without modifying the original operands vector.
7885 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7886 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007887 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007888 } else if (opCode == spv::OpDot && !isFloat) {
7889 // int dot(int, int)
7890 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7891 const int componentCount = builder.getNumComponents(operands[0]);
7892 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7893 builder.setPrecision(mulOp, precision);
7894 id = builder.createCompositeExtract(mulOp, typeId, 0);
7895 for (int i = 1; i < componentCount; ++i) {
7896 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07007897 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01007898 }
John Kessenich2359bd02015-12-06 19:29:11 -07007899 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007900 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007901 case 0:
7902 // should all be handled by visitAggregate and createNoArgOperation
7903 assert(0);
7904 return 0;
7905 case 1:
7906 // should all be handled by createUnaryOperation
7907 assert(0);
7908 return 0;
7909 case 2:
7910 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7911 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007912 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007913 // anything 3 or over doesn't have l-value operands, so all should be consumed
7914 assert(consumedOperands == operands.size());
7915 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007916 break;
7917 }
7918 }
7919
John Kessenichb9197c82019-08-11 07:41:45 -06007920#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007921 // Decode the return types that were structures
7922 switch (op) {
7923 case glslang::EOpAddCarry:
7924 case glslang::EOpSubBorrow:
7925 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7926 id = builder.createCompositeExtract(id, typeId0, 0);
7927 break;
7928 case glslang::EOpUMulExtended:
7929 case glslang::EOpIMulExtended:
7930 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7931 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7932 break;
7933 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007934 {
7935 assert(operands.size() == 2);
7936 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7937 // "exp" is floating-point type (from HLSL intrinsic)
7938 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7939 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7940 builder.createStore(member1, operands[1]);
7941 } else
7942 // "exp" is integer type (from GLSL built-in function)
7943 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7944 id = builder.createCompositeExtract(id, typeId0, 0);
7945 }
John Kessenich55e7d112015-11-15 21:33:39 -07007946 break;
7947 default:
7948 break;
7949 }
John Kessenichb9197c82019-08-11 07:41:45 -06007950#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007951
John Kessenich32cfd492016-02-02 12:37:46 -07007952 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007953}
7954
Rex Xu9d93a232016-05-05 12:30:44 +08007955// Intrinsics with no arguments (or no return value, and no precision).
7956spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007957{
Jeff Bolz36831c92018-09-05 10:11:41 -05007958 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07007959 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
7960 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007961
7962 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007963 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007964 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007965 if (glslangIntermediate->usingVulkanMemoryModel()) {
7966 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7967 spv::MemorySemanticsOutputMemoryKHRMask |
7968 spv::MemorySemanticsAcquireReleaseMask);
7969 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7970 } else {
7971 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7972 }
John Kessenich82979362017-12-11 04:02:24 -07007973 } else {
7974 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7975 spv::MemorySemanticsWorkgroupMemoryMask |
7976 spv::MemorySemanticsAcquireReleaseMask);
7977 }
John Kessenich140f3df2015-06-26 16:58:36 -06007978 return 0;
7979 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007980 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7981 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007982 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007983 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007984 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7985 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007986 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007987 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007988 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7989 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007990 return 0;
7991 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007992 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7993 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007994 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007995#ifndef GLSLANG_WEB
7996 case glslang::EOpMemoryBarrierAtomicCounter:
7997 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7998 spv::MemorySemanticsAcquireReleaseMask);
7999 return 0;
8000 case glslang::EOpMemoryBarrierImage:
8001 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
8002 spv::MemorySemanticsAcquireReleaseMask);
8003 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06008004 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07008005 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07008006 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07008007 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008008 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07008009 case glslang::EOpDeviceMemoryBarrier:
8010 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
8011 spv::MemorySemanticsImageMemoryMask |
8012 spv::MemorySemanticsAcquireReleaseMask);
8013 return 0;
8014 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
8015 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
8016 spv::MemorySemanticsImageMemoryMask |
8017 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008018 return 0;
8019 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07008020 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8021 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008022 return 0;
8023 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07008024 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
8025 spv::MemorySemanticsWorkgroupMemoryMask |
8026 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06008027 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07008028 case glslang::EOpSubgroupBarrier:
8029 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8030 spv::MemorySemanticsAcquireReleaseMask);
8031 return spv::NoResult;
8032 case glslang::EOpSubgroupMemoryBarrier:
8033 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
8034 spv::MemorySemanticsAcquireReleaseMask);
8035 return spv::NoResult;
8036 case glslang::EOpSubgroupMemoryBarrierBuffer:
8037 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
8038 spv::MemorySemanticsAcquireReleaseMask);
8039 return spv::NoResult;
8040 case glslang::EOpSubgroupMemoryBarrierImage:
8041 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
8042 spv::MemorySemanticsAcquireReleaseMask);
8043 return spv::NoResult;
8044 case glslang::EOpSubgroupMemoryBarrierShared:
8045 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8046 spv::MemorySemanticsAcquireReleaseMask);
8047 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06008048
8049 case glslang::EOpEmitVertex:
8050 builder.createNoResultOp(spv::OpEmitVertex);
8051 return 0;
8052 case glslang::EOpEndPrimitive:
8053 builder.createNoResultOp(spv::OpEndPrimitive);
8054 return 0;
8055
John Kessenich66011cb2018-03-06 16:12:04 -07008056 case glslang::EOpSubgroupElect: {
8057 std::vector<spv::Id> operands;
8058 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
8059 }
Rex Xu9d93a232016-05-05 12:30:44 +08008060 case glslang::EOpTime:
8061 {
8062 std::vector<spv::Id> args; // Dummy arguments
8063 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
8064 return builder.setPrecision(id, precision);
8065 }
Daniel Kochdb32b242020-03-17 20:42:47 -04008066 case glslang::EOpIgnoreIntersection:
8067 builder.createNoResultOp(spv::OpIgnoreIntersectionKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008068 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04008069 case glslang::EOpTerminateRay:
8070 builder.createNoResultOp(spv::OpTerminateRayKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008071 return 0;
Torosdagli06c2eee2020-03-19 11:09:57 -04008072 case glslang::EOpRayQueryInitialize:
8073 builder.createNoResultOp(spv::OpRayQueryInitializeKHR);
8074 return 0;
8075 case glslang::EOpRayQueryTerminate:
8076 builder.createNoResultOp(spv::OpRayQueryTerminateKHR);
8077 return 0;
8078 case glslang::EOpRayQueryGenerateIntersection:
8079 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR);
8080 return 0;
8081 case glslang::EOpRayQueryConfirmIntersection:
8082 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR);
8083 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05008084 case glslang::EOpBeginInvocationInterlock:
8085 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
8086 return 0;
8087 case glslang::EOpEndInvocationInterlock:
8088 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
8089 return 0;
8090
Jeff Bolzba6170b2019-07-01 09:23:23 -05008091 case glslang::EOpIsHelperInvocation:
8092 {
8093 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08008094 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
8095 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
8096 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05008097 }
8098
amhagan91fb0092019-07-10 21:14:38 -04008099 case glslang::EOpReadClockSubgroupKHR: {
8100 std::vector<spv::Id> args;
8101 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
8102 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8103 builder.addCapability(spv::CapabilityShaderClockKHR);
8104 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8105 }
8106
8107 case glslang::EOpReadClockDeviceKHR: {
8108 std::vector<spv::Id> args;
8109 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
8110 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8111 builder.addCapability(spv::CapabilityShaderClockKHR);
8112 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8113 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06008114#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008115 default:
John Kessenich155d3512019-08-08 23:29:20 -06008116 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008117 }
John Kessenich155d3512019-08-08 23:29:20 -06008118
8119 logger->missingFunctionality("unknown operation with no arguments");
8120
8121 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008122}
8123
8124spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
8125{
John Kessenich2f273362015-07-18 22:34:27 -06008126 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06008127 spv::Id id;
8128 if (symbolValues.end() != iter) {
8129 id = iter->second;
8130 return id;
8131 }
8132
8133 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06008134 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
Daniel Kochdb32b242020-03-17 20:42:47 -04008135 auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06008136 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06008137 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06008138 if (forcedType.second != spv::NoType)
8139 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06008140
Rex Xuc884b4a2016-06-29 15:03:44 +08008141 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008142 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
8143 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
8144 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06008145#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008146 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06008147 if (symbol->getQualifier().hasComponent())
8148 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
8149 if (symbol->getQualifier().hasIndex())
8150 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07008151#endif
John Kessenich6c292d32016-02-15 20:58:50 -07008152 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07008153 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06008154 // atomic counters use this:
8155 if (symbol->getQualifier().hasOffset())
8156 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008157 }
8158
scygan2c864272016-05-18 18:09:17 +02008159 if (symbol->getQualifier().hasLocation())
8160 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07008161 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07008162 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07008163 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06008164 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07008165 }
John Kessenich140f3df2015-06-26 16:58:36 -06008166 if (symbol->getQualifier().hasSet())
8167 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07008168 else if (IsDescriptorResource(symbol->getType())) {
8169 // default to 0
8170 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
8171 }
John Kessenich140f3df2015-06-26 16:58:36 -06008172 if (symbol->getQualifier().hasBinding())
8173 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06008174 else if (IsDescriptorResource(symbol->getType())) {
8175 // default to 0
8176 builder.addDecoration(id, spv::DecorationBinding, 0);
8177 }
John Kessenich6c292d32016-02-15 20:58:50 -07008178 if (symbol->getQualifier().hasAttachment())
8179 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06008180 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07008181 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07008182 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008183 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07008184 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
8185 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
8186 builder.addDecoration(id, spv::DecorationXfbStride, stride);
8187 }
8188 if (symbol->getQualifier().hasXfbOffset())
8189 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008190 }
8191
John Kessenichb9197c82019-08-11 07:41:45 -06008192 // add built-in variable decoration
8193 if (builtIn != spv::BuiltInMax) {
8194 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
8195 }
8196
8197#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08008198 if (symbol->getType().isImage()) {
8199 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07008200 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
8201 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08008202 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07008203 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08008204 }
8205
John Kessenich5611c6d2018-04-05 11:25:02 -06008206 // nonuniform
8207 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
8208
chaoc0ad6a4e2016-12-19 16:29:34 -08008209 if (builtIn == spv::BuiltInSampleMask) {
8210 spv::Decoration decoration;
8211 // GL_NV_sample_mask_override_coverage extension
8212 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08008213 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08008214 else
8215 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07008216 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08008217 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07008218 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08008219 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
8220 }
8221 }
chaoc771d89f2017-01-13 01:10:53 -08008222 else if (builtIn == spv::BuiltInLayer) {
8223 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06008224 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008225 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08008226 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
8227 builder.addExtension(spv::E_SPV_NV_viewport_array2);
8228 }
John Kessenichb41bff62017-08-11 13:07:17 -06008229 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008230 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
8231 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08008232 builder.addCapability(spv::CapabilityShaderStereoViewNV);
8233 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
8234 }
8235 }
8236
chaoc6e5acae2016-12-20 13:28:52 -08008237 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008238 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08008239 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08008240 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
8241 }
Chao Chen9eada4b2018-09-19 11:39:56 -07008242 if (symbol->getQualifier().pervertexNV) {
8243 builder.addDecoration(id, spv::DecorationPerVertexNV);
8244 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
8245 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
8246 }
chaoc0ad6a4e2016-12-19 16:29:34 -08008247
John Kessenich5d610ee2018-03-07 18:05:55 -07008248 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
8249 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
8250 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
8251 symbol->getType().getQualifier().semanticName);
8252 }
8253
John Kessenich7015bd62019-08-01 03:28:08 -06008254 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07008255 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
8256 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008257 }
John Kessenichb9197c82019-08-11 07:41:45 -06008258#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008259
John Kessenich140f3df2015-06-26 16:58:36 -06008260 return id;
8261}
8262
John Kessenicha28f7a72019-08-06 07:00:58 -06008263#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008264// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
8265void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
8266{
8267 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07008268 if (qualifier.perPrimitiveNV) {
8269 // Need to add capability/extension for fragment shader.
8270 // Mesh shader already adds this by default.
8271 if (glslangIntermediate->getStage() == EShLangFragment) {
8272 builder.addCapability(spv::CapabilityMeshShadingNV);
8273 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8274 }
Chao Chen3c366992018-09-19 11:41:59 -07008275 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008276 }
Chao Chen3c366992018-09-19 11:41:59 -07008277 if (qualifier.perViewNV)
8278 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
8279 if (qualifier.perTaskNV)
8280 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
8281 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07008282 if (qualifier.perPrimitiveNV) {
8283 // Need to add capability/extension for fragment shader.
8284 // Mesh shader already adds this by default.
8285 if (glslangIntermediate->getStage() == EShLangFragment) {
8286 builder.addCapability(spv::CapabilityMeshShadingNV);
8287 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8288 }
Chao Chen3c366992018-09-19 11:41:59 -07008289 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008290 }
Chao Chen3c366992018-09-19 11:41:59 -07008291 if (qualifier.perViewNV)
8292 builder.addDecoration(id, spv::DecorationPerViewNV);
8293 if (qualifier.perTaskNV)
8294 builder.addDecoration(id, spv::DecorationPerTaskNV);
8295 }
8296}
8297#endif
8298
John Kessenich55e7d112015-11-15 21:33:39 -07008299// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008300// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008301//
8302// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8303//
8304// Recursively walk the nodes. The nodes form a tree whose leaves are
8305// regular constants, which themselves are trees that createSpvConstant()
8306// recursively walks. So, this function walks the "top" of the tree:
8307// - emit specialization constant-building instructions for specConstant
8308// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008309spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008310{
John Kessenich7cc0e282016-03-20 00:46:02 -06008311 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008312
qining4f4bb812016-04-03 23:55:17 -04008313 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008314 if (! node.getQualifier().specConstant) {
8315 // hand off to the non-spec-constant path
8316 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8317 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008318 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8319 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8320 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008321 }
8322
8323 // We now know we have a specialization constant to build
8324
Ricardo Garcia232ba0d2020-06-03 15:52:55 +02008325 // Extra capabilities may be needed.
8326 if (node.getType().contains8BitInt())
8327 builder.addCapability(spv::CapabilityInt8);
8328 if (node.getType().contains16BitFloat())
8329 builder.addCapability(spv::CapabilityFloat16);
8330 if (node.getType().contains16BitInt())
8331 builder.addCapability(spv::CapabilityInt16);
8332 if (node.getType().contains64BitInt())
8333 builder.addCapability(spv::CapabilityInt64);
8334 if (node.getType().containsDouble())
8335 builder.addCapability(spv::CapabilityFloat64);
8336
John Kessenichd94c0032016-05-30 19:29:40 -06008337 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008338 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8339 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8340 std::vector<spv::Id> dimConstId;
8341 for (int dim = 0; dim < 3; ++dim) {
8342 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8343 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008344 if (specConst) {
8345 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8346 glslangIntermediate->getLocalSizeSpecId(dim));
8347 }
qining4f4bb812016-04-03 23:55:17 -04008348 }
8349 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8350 }
8351
8352 // An AST node labelled as specialization constant should be a symbol node.
8353 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8354 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008355 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008356 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008357 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8358 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8359 // will set the builder into spec constant op instruction generating mode.
8360 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008361 result = accessChainLoad(sub_tree->getType());
8362 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008363 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008364 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008365 } else {
8366 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008367 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008368 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008369 builder.addName(result, sn->getName().c_str());
8370 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008371 }
qining4f4bb812016-04-03 23:55:17 -04008372
8373 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8374 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008375 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008376 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008377}
8378
John Kessenich140f3df2015-06-26 16:58:36 -06008379// Use 'consts' as the flattened glslang source of scalar constants to recursively
8380// build the aggregate SPIR-V constant.
8381//
8382// If there are not enough elements present in 'consts', 0 will be substituted;
8383// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8384//
John Kessenich8985fc92020-03-03 10:25:07 -07008385spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8386 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008387{
8388 // vector of constants for SPIR-V
8389 std::vector<spv::Id> spvConsts;
8390
8391 // Type is used for struct and array constants
8392 spv::Id typeId = convertGlslangToSpvType(glslangType);
8393
8394 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008395 glslang::TType elementType(glslangType, 0);
8396 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008397 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008398 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008399 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008400 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008401 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008402 } else if (glslangType.isCoopMat()) {
8403 glslang::TType componentType(glslangType.getBasicType());
8404 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008405 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008406 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8407 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008408 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008409 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008410 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8411 bool zero = nextConst >= consts.size();
8412 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008413 case glslang::EbtInt:
8414 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8415 break;
8416 case glslang::EbtUint:
8417 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8418 break;
8419 case glslang::EbtFloat:
8420 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8421 break;
8422 case glslang::EbtBool:
8423 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8424 break;
8425#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008426 case glslang::EbtInt8:
8427 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8428 break;
8429 case glslang::EbtUint8:
8430 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8431 break;
8432 case glslang::EbtInt16:
8433 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8434 break;
8435 case glslang::EbtUint16:
8436 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8437 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008438 case glslang::EbtInt64:
8439 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8440 break;
8441 case glslang::EbtUint64:
8442 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8443 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008444 case glslang::EbtDouble:
8445 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8446 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008447 case glslang::EbtFloat16:
8448 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8449 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008450#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008451 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008452 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008453 break;
8454 }
8455 ++nextConst;
8456 }
8457 } else {
8458 // we have a non-aggregate (scalar) constant
8459 bool zero = nextConst >= consts.size();
8460 spv::Id scalar = 0;
8461 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008462 case glslang::EbtInt:
8463 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8464 break;
8465 case glslang::EbtUint:
8466 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8467 break;
8468 case glslang::EbtFloat:
8469 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8470 break;
8471 case glslang::EbtBool:
8472 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8473 break;
8474#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008475 case glslang::EbtInt8:
8476 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8477 break;
8478 case glslang::EbtUint8:
8479 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8480 break;
8481 case glslang::EbtInt16:
8482 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8483 break;
8484 case glslang::EbtUint16:
8485 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8486 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008487 case glslang::EbtInt64:
8488 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8489 break;
8490 case glslang::EbtUint64:
8491 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8492 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008493 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008494 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008495 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008496 case glslang::EbtFloat16:
8497 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8498 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008499 case glslang::EbtReference:
8500 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8501 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8502 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008503#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008504 case glslang::EbtString:
8505 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8506 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008507 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008508 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008509 break;
8510 }
8511 ++nextConst;
8512 return scalar;
8513 }
8514
8515 return builder.makeCompositeConstant(typeId, spvConsts);
8516}
8517
John Kessenich7c1aa102015-10-15 13:29:11 -06008518// Return true if the node is a constant or symbol whose reading has no
8519// non-trivial observable cost or effect.
8520bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8521{
8522 // don't know what this is
8523 if (node == nullptr)
8524 return false;
8525
8526 // a constant is safe
8527 if (node->getAsConstantUnion() != nullptr)
8528 return true;
8529
8530 // not a symbol means non-trivial
8531 if (node->getAsSymbolNode() == nullptr)
8532 return false;
8533
8534 // a symbol, depends on what's being read
8535 switch (node->getType().getQualifier().storage) {
8536 case glslang::EvqTemporary:
8537 case glslang::EvqGlobal:
8538 case glslang::EvqIn:
8539 case glslang::EvqInOut:
8540 case glslang::EvqConst:
8541 case glslang::EvqConstReadOnly:
8542 case glslang::EvqUniform:
8543 return true;
8544 default:
8545 return false;
8546 }
qining25262b32016-05-06 17:25:16 -04008547}
John Kessenich7c1aa102015-10-15 13:29:11 -06008548
8549// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008550// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008551// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008552// Return true if trivial.
8553bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8554{
8555 if (node == nullptr)
8556 return false;
8557
John Kessenich84cc15f2017-05-24 16:44:47 -06008558 // count non scalars as trivial, as well as anything coming from HLSL
8559 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008560 return true;
8561
John Kessenich7c1aa102015-10-15 13:29:11 -06008562 // symbols and constants are trivial
8563 if (isTrivialLeaf(node))
8564 return true;
8565
8566 // otherwise, it needs to be a simple operation or one or two leaf nodes
8567
8568 // not a simple operation
8569 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8570 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8571 if (binaryNode == nullptr && unaryNode == nullptr)
8572 return false;
8573
8574 // not on leaf nodes
8575 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8576 return false;
8577
8578 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8579 return false;
8580 }
8581
8582 switch (node->getAsOperator()->getOp()) {
8583 case glslang::EOpLogicalNot:
8584 case glslang::EOpConvIntToBool:
8585 case glslang::EOpConvUintToBool:
8586 case glslang::EOpConvFloatToBool:
8587 case glslang::EOpConvDoubleToBool:
8588 case glslang::EOpEqual:
8589 case glslang::EOpNotEqual:
8590 case glslang::EOpLessThan:
8591 case glslang::EOpGreaterThan:
8592 case glslang::EOpLessThanEqual:
8593 case glslang::EOpGreaterThanEqual:
8594 case glslang::EOpIndexDirect:
8595 case glslang::EOpIndexDirectStruct:
8596 case glslang::EOpLogicalXor:
8597 case glslang::EOpAny:
8598 case glslang::EOpAll:
8599 return true;
8600 default:
8601 return false;
8602 }
8603}
8604
8605// Emit short-circuiting code, where 'right' is never evaluated unless
8606// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008607spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8608 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008609{
8610 spv::Id boolTypeId = builder.makeBoolType();
8611
8612 // emit left operand
8613 builder.clearAccessChain();
8614 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008615 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008616
8617 // Operands to accumulate OpPhi operands
8618 std::vector<spv::Id> phiOperands;
8619 // accumulate left operand's phi information
8620 phiOperands.push_back(leftId);
8621 phiOperands.push_back(builder.getBuildPoint()->getId());
8622
8623 // Make the two kinds of operation symmetric with a "!"
8624 // || => emit "if (! left) result = right"
8625 // && => emit "if ( left) result = right"
8626 //
8627 // TODO: this runtime "not" for || could be avoided by adding functionality
8628 // to 'builder' to have an "else" without an "then"
8629 if (op == glslang::EOpLogicalOr)
8630 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8631
8632 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008633 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008634
8635 // emit right operand as the "then" part of the "if"
8636 builder.clearAccessChain();
8637 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008638 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008639
8640 // accumulate left operand's phi information
8641 phiOperands.push_back(rightId);
8642 phiOperands.push_back(builder.getBuildPoint()->getId());
8643
8644 // finish the "if"
8645 ifBuilder.makeEndIf();
8646
8647 // phi together the two results
8648 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8649}
8650
John Kessenicha28f7a72019-08-06 07:00:58 -06008651#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008652// Return type Id of the imported set of extended instructions corresponds to the name.
8653// Import this set if it has not been imported yet.
8654spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8655{
8656 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8657 return extBuiltinMap[name];
8658 else {
Rex Xu51596642016-09-21 18:56:12 +08008659 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008660 spv::Id extBuiltins = builder.import(name);
8661 extBuiltinMap[name] = extBuiltins;
8662 return extBuiltins;
8663 }
8664}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008665#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008666
John Kessenich140f3df2015-06-26 16:58:36 -06008667}; // end anonymous namespace
8668
8669namespace glslang {
8670
John Kessenich68d78fd2015-07-12 19:28:10 -06008671void GetSpirvVersion(std::string& version)
8672{
John Kessenich9e55f632015-07-15 10:03:39 -06008673 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008674 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008675 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008676 version = buf;
8677}
8678
John Kessenicha372a3e2017-11-02 22:32:14 -06008679// For low-order part of the generator's magic number. Bump up
8680// when there is a change in the style (e.g., if SSA form changes,
8681// or a different instruction sequence to do something gets used).
8682int GetSpirvGeneratorVersion()
8683{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008684 // return 1; // start
8685 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008686 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008687 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008688 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008689 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8690 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008691 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenich3641ff72020-06-10 07:38:31 -06008692 // return 8; // switch to new dead block eliminator; use OpUnreachable
Graeme Leese060882f2020-06-22 11:03:46 +01008693 // return 9; // don't include opaque function parameters in OpEntryPoint global's operand list
8694 return 10; // Generate OpFUnordNotEqual for != comparisons
John Kessenicha372a3e2017-11-02 22:32:14 -06008695}
8696
John Kessenich140f3df2015-06-26 16:58:36 -06008697// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008698void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008699{
8700 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008701 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008702 if (out.fail())
8703 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008704 for (int i = 0; i < (int)spirv.size(); ++i) {
8705 unsigned int word = spirv[i];
8706 out.write((const char*)&word, 4);
8707 }
8708 out.close();
8709}
8710
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008711// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008712void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008713{
Shahbaz Youssefi1ef2e252020-07-03 15:42:53 -04008714#if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008715 std::ofstream out;
8716 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008717 if (out.fail())
8718 printf("ERROR: Failed to open file: %s\n", baseName);
Ben Claytonfbe9a232020-06-17 11:17:19 +01008719 out << "\t// " <<
8720 GetSpirvGeneratorVersion() <<
8721 GLSLANG_VERSION_MAJOR << "." << GLSLANG_VERSION_MINOR << "." << GLSLANG_VERSION_PATCH <<
8722 GLSLANG_VERSION_FLAVOR << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008723 if (varName != nullptr) {
8724 out << "\t #pragma once" << std::endl;
8725 out << "const uint32_t " << varName << "[] = {" << std::endl;
8726 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008727 const int WORDS_PER_LINE = 8;
8728 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8729 out << "\t";
8730 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8731 const unsigned int word = spirv[i + j];
8732 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8733 if (i + j + 1 < (int)spirv.size()) {
8734 out << ",";
8735 }
8736 }
8737 out << std::endl;
8738 }
Flavio15017db2017-02-15 14:29:33 -08008739 if (varName != nullptr) {
8740 out << "};";
johnkslangf881f082020-08-04 02:13:50 -06008741 out << std::endl;
Flavio15017db2017-02-15 14:29:33 -08008742 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008743 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008744#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008745}
8746
John Kessenich140f3df2015-06-26 16:58:36 -06008747//
8748// Set up the glslang traversal
8749//
John Kessenich4e11b612018-08-30 16:56:59 -06008750void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008751{
Lei Zhang17535f72016-05-04 15:55:59 -04008752 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008753 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008754}
8755
John Kessenich4e11b612018-08-30 16:56:59 -06008756void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008757 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008758{
John Kessenich140f3df2015-06-26 16:58:36 -06008759 TIntermNode* root = intermediate.getTreeRoot();
8760
8761 if (root == 0)
8762 return;
8763
John Kessenich4e11b612018-08-30 16:56:59 -06008764 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008765 if (options == nullptr)
8766 options = &defaultOptions;
8767
John Kessenich4e11b612018-08-30 16:56:59 -06008768 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008769
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008770 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008771 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008772 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008773 it.dumpSpv(spirv);
8774
GregFfb03a552018-03-29 11:49:14 -06008775#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008776 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8777 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008778 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008779 if ((prelegalization || options->optimizeSize) && !options->disableOptimizer) {
8780 SpirvToolsTransform(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008781 prelegalization = false;
8782 }
Shahbaz Youssefid52dce52020-06-17 12:47:44 -04008783 else if (options->stripDebugInfo) {
8784 // Strip debug info even if optimization is disabled.
8785 SpirvToolsStripDebugInfo(intermediate, spirv, logger);
8786 }
John Kessenich717c80a2018-08-23 15:17:10 -06008787
John Kessenich4e11b612018-08-30 16:56:59 -06008788 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008789 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008790
John Kessenich717c80a2018-08-23 15:17:10 -06008791 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008792 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008793
GregFcd1f1692017-09-21 18:40:22 -06008794#endif
8795
John Kessenich4e11b612018-08-30 16:56:59 -06008796 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008797}
8798
8799}; // end namespace glslang