blob: 565f60d5e9761ce3ed32913fe531748130431d81 [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.
John Kessenich140f3df2015-06-26 16:58:36 -06005//
John Kessenich927608b2017-01-06 12:34:14 -07006// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06007//
John Kessenich927608b2017-01-06 12:34:14 -07008// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions
10// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060011//
12// Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//
15// Redistributions in binary form must reproduce the above
16// copyright notice, this list of conditions and the following
17// disclaimer in the documentation and/or other materials provided
18// with the distribution.
19//
20// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21// contributors may be used to endorse or promote products derived
22// from this software without specific prior written permission.
23//
John Kessenich927608b2017-01-06 12:34:14 -070024// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060036
37//
John Kessenich140f3df2015-06-26 16:58:36 -060038// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080046 #include "GLSL.std.450.h"
47 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070048 #include "GLSL.ext.EXT.h"
Rex Xu51596642016-09-21 18:56:12 +080049 #include "GLSL.ext.AMD.h"
chaoc0ad6a4e2016-12-19 16:29:34 -080050 #include "GLSL.ext.NV.h"
Jeff Bolz04d73732019-05-31 13:06:01 -050051 #include "NonSemanticDebugPrintf.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060052}
John Kessenich140f3df2015-06-26 16:58:36 -060053
54// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020055#include "../glslang/MachineIndependent/localintermediate.h"
56#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060057#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050058#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060059
John Kessenich140f3df2015-06-26 16:58:36 -060060#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050061#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040062#include <list>
63#include <map>
64#include <stack>
65#include <string>
66#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060067
68namespace {
69
qining4c912612016-04-01 10:35:16 -040070namespace {
71class SpecConstantOpModeGuard {
72public:
73 SpecConstantOpModeGuard(spv::Builder* builder)
74 : builder_(builder) {
75 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040076 }
77 ~SpecConstantOpModeGuard() {
78 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
79 : builder_->setToNormalCodeGenMode();
80 }
qining40887662016-04-03 22:20:42 -040081 void turnOnSpecConstantOpMode() {
82 builder_->setToSpecConstCodeGenMode();
83 }
qining4c912612016-04-01 10:35:16 -040084
85private:
86 spv::Builder* builder_;
87 bool previous_flag_;
88};
John Kessenichead86222018-03-28 18:01:20 -060089
90struct OpDecorations {
John Kessenichb9197c82019-08-11 07:41:45 -060091 public:
92 OpDecorations(spv::Decoration precision, spv::Decoration noContraction, spv::Decoration nonUniform) :
93 precision(precision)
94#ifndef GLSLANG_WEB
95 ,
96 noContraction(noContraction),
97 nonUniform(nonUniform)
98#endif
99 { }
100
John Kessenichead86222018-03-28 18:01:20 -0600101 spv::Decoration precision;
John Kessenichb9197c82019-08-11 07:41:45 -0600102
103#ifdef GLSLANG_WEB
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400104 void addNoContraction(spv::Builder&, spv::Id) const { }
105 void addNonUniform(spv::Builder&, spv::Id) const { }
John Kessenichb9197c82019-08-11 07:41:45 -0600106#else
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400107 void addNoContraction(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, noContraction); }
108 void addNonUniform(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, nonUniform); }
John Kessenichb9197c82019-08-11 07:41:45 -0600109 protected:
110 spv::Decoration noContraction;
111 spv::Decoration nonUniform;
112#endif
113
John Kessenichead86222018-03-28 18:01:20 -0600114};
115
116} // namespace
qining4c912612016-04-01 10:35:16 -0400117
John Kessenich140f3df2015-06-26 16:58:36 -0600118//
119// The main holder of information for translating glslang to SPIR-V.
120//
121// Derives from the AST walking base class.
122//
123class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
124public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700125 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
126 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700127 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600128
129 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
130 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
131 void visitConstantUnion(glslang::TIntermConstantUnion*);
132 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
133 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
134 void visitSymbol(glslang::TIntermSymbol* symbol);
135 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
136 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
137 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
138
John Kessenichfca82622016-11-26 13:23:20 -0700139 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700140 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600141
142protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700143 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
144 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
145
Rex Xu17ff3432016-10-14 17:41:45 +0800146 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800147 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600148 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500149 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
150 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
151 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
152 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100153 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700154 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700155 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
156 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700157 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600158 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600159 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich9c14f772019-06-17 08:38:35 -0600160 spv::Id createSpvVariable(const glslang::TIntermSymbol*, spv::Id forcedType);
John Kessenich140f3df2015-06-26 16:58:36 -0600161 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600162 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
163 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
164 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600165 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600166 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600167 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600168 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600169 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
170 glslang::TLayoutPacking, const glslang::TQualifier&);
171 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
172 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700173 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700174 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800175 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600176 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700177 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700178 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
179 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700180 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
181 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100182 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600183
John Kessenich6fccb3c2016-09-19 16:01:41 -0600184 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600185 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600186 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600187 void makeFunctions(const glslang::TIntermSequence&);
188 void makeGlobalInitializers(const glslang::TIntermSequence&);
189 void visitFunctions(const glslang::TIntermSequence&);
190 void handleFunctionEntry(const glslang::TIntermAggregate* node);
John Kessenich8985fc92020-03-03 10:25:07 -0700191 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
192 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -0600193 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
194 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600195 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
196
John Kessenichead86222018-03-28 18:01:20 -0600197 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
198 glslang::TBasicType typeProxy, bool reduceComparison = true);
199 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
200 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
John Kessenich8985fc92020-03-03 10:25:07 -0700201 glslang::TBasicType typeProxy,
202 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -0600203 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
204 glslang::TBasicType typeProxy);
205 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
206 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600207 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600208 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
John Kessenich8985fc92020-03-03 10:25:07 -0700209 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId,
210 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
211 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
212 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands,
213 glslang::TBasicType typeProxy);
214 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
215 spv::Id typeId, std::vector<spv::Id>& operands);
216 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands,
217 glslang::TBasicType typeProxy);
218 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId,
219 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800220 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600221 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700222 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
qining08408382016-03-21 09:51:37 -0400223 spv::Id createSpvConstant(const glslang::TIntermTyped&);
John Kessenich8985fc92020-03-03 10:25:07 -0700224 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&,
225 int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600226 bool isTrivialLeaf(const glslang::TIntermTyped* node);
227 bool isTrivial(const glslang::TIntermTyped* node);
228 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800229 spv::Id getExtBuiltins(const char* name);
Daniel Kochdb32b242020-03-17 20:42:47 -0400230 std::pair<spv::Id, spv::Id> getForcedType(glslang::TBuiltInVariable builtIn, const glslang::TType&);
John Kessenich9c14f772019-06-17 08:38:35 -0600231 spv::Id translateForcedType(spv::Id object);
Jeff Bolz53134492019-06-25 13:31:10 -0500232 spv::Id createCompositeConstruct(spv::Id typeId, std::vector<spv::Id> constituents);
John Kessenich140f3df2015-06-26 16:58:36 -0600233
John Kessenich121853f2017-05-31 17:11:16 -0600234 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600235 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600236 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700237 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600238 int sequenceDepth;
239
Lei Zhang17535f72016-05-04 15:55:59 -0400240 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400241
John Kessenich140f3df2015-06-26 16:58:36 -0600242 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
243 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700244 bool inEntryPoint;
245 bool entryPointTerminated;
John Kessenich8985fc92020-03-03 10:25:07 -0700246 bool linkageOnly; // true when visiting the set of objects in the AST present only for
247 // establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700248 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600249 const glslang::TIntermediate* glslangIntermediate;
John Kessenich605afc72019-06-17 23:33:09 -0600250 bool nanMinMaxClamp; // true if use NMin/NMax/NClamp instead of FMin/FMax/FClamp
John Kessenich140f3df2015-06-26 16:58:36 -0600251 spv::Id stdBuiltins;
Jeff Bolz04d73732019-05-31 13:06:01 -0500252 spv::Id nonSemanticDebugPrintf;
Rex Xu9d93a232016-05-05 12:30:44 +0800253 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600254
John Kessenich2f273362015-07-18 22:34:27 -0600255 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich8985fc92020-03-03 10:25:07 -0700256 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues,
257 // rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600258 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700259 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700260 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
Roy05a5b532020-01-03 16:21:34 +0800261 std::unordered_map<int, std::vector<int>> memberRemapper;
262 // for mapping glslang symbol struct to symbol Id
263 std::unordered_map<const glslang::TTypeList*, int> glslangTypeToIdMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600264 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700265 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600266 // Map pointee types for EbtReference to their forward pointers
267 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich9c14f772019-06-17 08:38:35 -0600268 // Type forcing, for when SPIR-V wants a different type than the AST,
269 // requiring local translation to and from SPIR-V type on every access.
270 // Maps <builtin-variable-id -> AST-required-type-id>
271 std::unordered_map<spv::Id, spv::Id> forceType;
John Kessenich140f3df2015-06-26 16:58:36 -0600272};
273
274//
275// Helper functions for translating glslang representations to SPIR-V enumerants.
276//
277
278// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700279spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600280{
John Kessenich155d3512019-08-08 23:29:20 -0600281#ifdef GLSLANG_WEB
282 return spv::SourceLanguageESSL;
283#endif
284
John Kessenich66e2faf2016-03-12 18:34:36 -0700285 switch (source) {
286 case glslang::EShSourceGlsl:
287 switch (profile) {
288 case ENoProfile:
289 case ECoreProfile:
290 case ECompatibilityProfile:
291 return spv::SourceLanguageGLSL;
292 case EEsProfile:
293 return spv::SourceLanguageESSL;
294 default:
295 return spv::SourceLanguageUnknown;
296 }
297 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600298 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600299 default:
300 return spv::SourceLanguageUnknown;
301 }
302}
303
304// Translate glslang language (stage) to SPIR-V execution model.
305spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
306{
307 switch (stage) {
308 case EShLangVertex: return spv::ExecutionModelVertex;
John Kessenicha28f7a72019-08-06 07:00:58 -0600309 case EShLangFragment: return spv::ExecutionModelFragment;
John Kessenicha28f7a72019-08-06 07:00:58 -0600310 case EShLangCompute: return spv::ExecutionModelGLCompute;
John Kessenich51ed01c2019-10-10 11:40:11 -0600311#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -0600312 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
313 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
314 case EShLangGeometry: return spv::ExecutionModelGeometry;
Daniel Kochdb32b242020-03-17 20:42:47 -0400315 case EShLangRayGen: return spv::ExecutionModelRayGenerationKHR;
316 case EShLangIntersect: return spv::ExecutionModelIntersectionKHR;
317 case EShLangAnyHit: return spv::ExecutionModelAnyHitKHR;
318 case EShLangClosestHit: return spv::ExecutionModelClosestHitKHR;
319 case EShLangMiss: return spv::ExecutionModelMissKHR;
320 case EShLangCallable: return spv::ExecutionModelCallableKHR;
Chao Chen3c366992018-09-19 11:41:59 -0700321 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
322 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
323#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600324 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700325 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600326 return spv::ExecutionModelFragment;
327 }
328}
329
John Kessenich140f3df2015-06-26 16:58:36 -0600330// Translate glslang sampler type to SPIR-V dimensionality.
331spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
332{
333 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700334 case glslang::Esd1D: return spv::Dim1D;
335 case glslang::Esd2D: return spv::Dim2D;
336 case glslang::Esd3D: return spv::Dim3D;
337 case glslang::EsdCube: return spv::DimCube;
338 case glslang::EsdRect: return spv::DimRect;
339 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700340 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600341 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700342 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600343 return spv::Dim2D;
344 }
345}
346
John Kessenichf6640762016-08-01 19:44:00 -0600347// Translate glslang precision to SPIR-V precision decorations.
348spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600349{
John Kessenichf6640762016-08-01 19:44:00 -0600350 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700351 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600352 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600353 default:
354 return spv::NoPrecision;
355 }
356}
357
John Kessenichf6640762016-08-01 19:44:00 -0600358// Translate glslang type to SPIR-V precision decorations.
359spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
360{
361 return TranslatePrecisionDecoration(type.getQualifier().precision);
362}
363
John Kessenich140f3df2015-06-26 16:58:36 -0600364// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600365spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600366{
367 if (type.getBasicType() == glslang::EbtBlock) {
368 switch (type.getQualifier().storage) {
369 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600370 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600371 case glslang::EvqVaryingIn: return spv::DecorationBlock;
372 case glslang::EvqVaryingOut: return spv::DecorationBlock;
John Kessenicha28f7a72019-08-06 07:00:58 -0600373#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -0400374 case glslang::EvqPayload: return spv::DecorationBlock;
375 case glslang::EvqPayloadIn: return spv::DecorationBlock;
376 case glslang::EvqHitAttr: return spv::DecorationBlock;
377 case glslang::EvqCallableData: return spv::DecorationBlock;
378 case glslang::EvqCallableDataIn: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700379#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600380 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700381 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600382 break;
383 }
384 }
385
John Kessenich4016e382016-07-15 11:53:56 -0600386 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600387}
388
Rex Xu1da878f2016-02-21 20:59:01 +0800389// Translate glslang type to SPIR-V memory decorations.
John Kessenich8985fc92020-03-03 10:25:07 -0700390void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory,
391 bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800392{
Jeff Bolz36831c92018-09-05 10:11:41 -0500393 if (!useVulkanMemoryModel) {
John Kessenichf8d1d742019-10-21 06:55:11 -0600394 if (qualifier.isCoherent())
Jeff Bolz36831c92018-09-05 10:11:41 -0500395 memory.push_back(spv::DecorationCoherent);
John Kessenichf8d1d742019-10-21 06:55:11 -0600396 if (qualifier.isVolatile()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500397 memory.push_back(spv::DecorationVolatile);
398 memory.push_back(spv::DecorationCoherent);
399 }
John Kessenich14b85d32018-06-04 15:36:03 -0600400 }
John Kessenichf8d1d742019-10-21 06:55:11 -0600401 if (qualifier.isRestrict())
Rex Xu1da878f2016-02-21 20:59:01 +0800402 memory.push_back(spv::DecorationRestrict);
John Kessenichdeec1932019-08-13 08:00:30 -0600403 if (qualifier.isReadOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800404 memory.push_back(spv::DecorationNonWritable);
John Kessenichdeec1932019-08-13 08:00:30 -0600405 if (qualifier.isWriteOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800406 memory.push_back(spv::DecorationNonReadable);
407}
408
John Kessenich140f3df2015-06-26 16:58:36 -0600409// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700410spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600411{
412 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700413 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600414 case glslang::ElmRowMajor:
415 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700416 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600417 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700418 default:
419 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600420 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600421 }
422 } else {
423 switch (type.getBasicType()) {
424 default:
John Kessenich4016e382016-07-15 11:53:56 -0600425 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600426 break;
427 case glslang::EbtBlock:
428 switch (type.getQualifier().storage) {
429 case glslang::EvqUniform:
430 case glslang::EvqBuffer:
431 switch (type.getQualifier().layoutPacking) {
432 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600433 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
434 default:
John Kessenich4016e382016-07-15 11:53:56 -0600435 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600436 }
437 case glslang::EvqVaryingIn:
438 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700439 if (type.getQualifier().isTaskMemory()) {
440 switch (type.getQualifier().layoutPacking) {
441 case glslang::ElpShared: return spv::DecorationGLSLShared;
442 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
443 default: break;
444 }
445 } else {
446 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
447 }
John Kessenich4016e382016-07-15 11:53:56 -0600448 return spv::DecorationMax;
John Kessenicha28f7a72019-08-06 07:00:58 -0600449#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -0400450 case glslang::EvqPayload:
451 case glslang::EvqPayloadIn:
452 case glslang::EvqHitAttr:
453 case glslang::EvqCallableData:
454 case glslang::EvqCallableDataIn:
Chao Chenb50c02e2018-09-19 11:42:24 -0700455 return spv::DecorationMax;
456#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600457 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700458 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600459 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600460 }
461 }
462 }
463}
464
465// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600466// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700467// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800468spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600469{
Rex Xubbceed72016-05-21 09:40:44 +0800470 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700471 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600472 return spv::DecorationMax;
John Kessenich7015bd62019-08-01 03:28:08 -0600473 else if (qualifier.isNonPerspective())
John Kessenich55e7d112015-11-15 21:33:39 -0700474 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700475 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600476 return spv::DecorationFlat;
John Kessenicha28f7a72019-08-06 07:00:58 -0600477 else if (qualifier.isExplicitInterpolation()) {
Rex Xu17ff3432016-10-14 17:41:45 +0800478 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800479 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800480 }
Rex Xubbceed72016-05-21 09:40:44 +0800481 else
John Kessenich4016e382016-07-15 11:53:56 -0600482 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800483}
484
485// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600486// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800487// should be applied.
488spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
489{
John Kessenichb9197c82019-08-11 07:41:45 -0600490 if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600491 return spv::DecorationCentroid;
John Kessenichb9197c82019-08-11 07:41:45 -0600492#ifndef GLSLANG_WEB
493 else if (qualifier.patch)
494 return spv::DecorationPatch;
John Kessenich5e801132016-02-15 11:09:46 -0700495 else if (qualifier.sample) {
496 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600497 return spv::DecorationSample;
John Kessenichb9197c82019-08-11 07:41:45 -0600498 }
499#endif
500
501 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600502}
503
John Kessenich92187592016-02-01 13:45:25 -0700504// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700505spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600506{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700507 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600508 return spv::DecorationInvariant;
509 else
John Kessenich4016e382016-07-15 11:53:56 -0600510 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600511}
512
qining9220dbb2016-05-04 17:34:38 -0400513// If glslang type is noContraction, return SPIR-V NoContraction decoration.
514spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
515{
John Kessenichb9197c82019-08-11 07:41:45 -0600516#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -0600517 if (qualifier.isNoContraction())
qining9220dbb2016-05-04 17:34:38 -0400518 return spv::DecorationNoContraction;
519 else
John Kessenichb9197c82019-08-11 07:41:45 -0600520#endif
John Kessenich4016e382016-07-15 11:53:56 -0600521 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400522}
523
John Kessenich5611c6d2018-04-05 11:25:02 -0600524// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
525spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
526{
John Kessenichb9197c82019-08-11 07:41:45 -0600527#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -0600528 if (qualifier.isNonUniform()) {
John Kessenich8317e6c2019-08-18 23:58:08 -0600529 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -0600530 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
531 return spv::DecorationNonUniformEXT;
532 } else
John Kessenichb9197c82019-08-11 07:41:45 -0600533#endif
John Kessenich5611c6d2018-04-05 11:25:02 -0600534 return spv::DecorationMax;
535}
536
John Kessenichb9197c82019-08-11 07:41:45 -0600537spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(
538 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500539{
Jeff Bolz36831c92018-09-05 10:11:41 -0500540 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600541
542#ifndef GLSLANG_WEB
543 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage)
544 return mask;
545
Daniel Kochdb32b242020-03-17 20:42:47 -0400546 if (coherentFlags.isVolatile() || coherentFlags.anyCoherent()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500547 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
548 spv::MemoryAccessMakePointerVisibleKHRMask;
549 }
Daniel Kochdb32b242020-03-17 20:42:47 -0400550
Jeff Bolz36831c92018-09-05 10:11:41 -0500551 if (coherentFlags.nonprivate) {
552 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
553 }
554 if (coherentFlags.volatil) {
555 mask = mask | spv::MemoryAccessVolatileMask;
556 }
557 if (mask != spv::MemoryAccessMaskNone) {
558 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
559 }
John Kessenichb9197c82019-08-11 07:41:45 -0600560#endif
561
Jeff Bolz36831c92018-09-05 10:11:41 -0500562 return mask;
563}
564
John Kessenichb9197c82019-08-11 07:41:45 -0600565spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(
566 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500567{
Jeff Bolz36831c92018-09-05 10:11:41 -0500568 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600569
570#ifndef GLSLANG_WEB
571 if (!glslangIntermediate->usingVulkanMemoryModel())
572 return mask;
573
Jeff Bolz36831c92018-09-05 10:11:41 -0500574 if (coherentFlags.volatil ||
Daniel Kochdb32b242020-03-17 20:42:47 -0400575 coherentFlags.anyCoherent()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500576 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
577 spv::ImageOperandsMakeTexelVisibleKHRMask;
578 }
579 if (coherentFlags.nonprivate) {
580 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
581 }
582 if (coherentFlags.volatil) {
583 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
584 }
585 if (mask != spv::ImageOperandsMaskNone) {
586 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
587 }
John Kessenichb9197c82019-08-11 07:41:45 -0600588#endif
589
Jeff Bolz36831c92018-09-05 10:11:41 -0500590 return mask;
591}
592
593spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
594{
John Kessenichb9197c82019-08-11 07:41:45 -0600595 spv::Builder::AccessChain::CoherentFlags flags = {};
596#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -0500597 flags.coherent = type.getQualifier().coherent;
598 flags.devicecoherent = type.getQualifier().devicecoherent;
599 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
600 // shared variables are implicitly workgroupcoherent in GLSL.
601 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
602 type.getQualifier().storage == glslang::EvqShared;
603 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Daniel Kochdb32b242020-03-17 20:42:47 -0400604 flags.shadercallcoherent = type.getQualifier().shadercallcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600605 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500606 // *coherent variables are implicitly nonprivate in GLSL
607 flags.nonprivate = type.getQualifier().nonprivate ||
Daniel Kochdb32b242020-03-17 20:42:47 -0400608 flags.anyCoherent() ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600609 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500610 flags.isImage = type.getBasicType() == glslang::EbtSampler;
John Kessenichb9197c82019-08-11 07:41:45 -0600611#endif
Jeff Bolz36831c92018-09-05 10:11:41 -0500612 return flags;
613}
614
John Kessenichb9197c82019-08-11 07:41:45 -0600615spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(
616 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500617{
John Kessenichb9197c82019-08-11 07:41:45 -0600618 spv::Scope scope = spv::ScopeMax;
619
620#ifndef GLSLANG_WEB
Jeff Bolz38cbad12019-03-05 14:40:07 -0600621 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500622 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
623 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
624 } else if (coherentFlags.devicecoherent) {
625 scope = spv::ScopeDevice;
626 } else if (coherentFlags.queuefamilycoherent) {
627 scope = spv::ScopeQueueFamilyKHR;
628 } else if (coherentFlags.workgroupcoherent) {
629 scope = spv::ScopeWorkgroup;
630 } else if (coherentFlags.subgroupcoherent) {
631 scope = spv::ScopeSubgroup;
Daniel Kochdb32b242020-03-17 20:42:47 -0400632 } else if (coherentFlags.shadercallcoherent) {
633 scope = spv::ScopeShaderCallKHR;
Jeff Bolz36831c92018-09-05 10:11:41 -0500634 }
635 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
636 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
637 }
John Kessenichb9197c82019-08-11 07:41:45 -0600638#endif
639
Jeff Bolz36831c92018-09-05 10:11:41 -0500640 return scope;
641}
642
David Netoa901ffe2016-06-08 14:11:40 +0100643// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
644// associated capabilities when required. For some built-in variables, a capability
645// is generated only when using the variable in an executable instruction, but not when
646// just declaring a struct member variable with it. This is true for PointSize,
647// ClipDistance, and CullDistance.
John Kessenich8985fc92020-03-03 10:25:07 -0700648spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn,
649 bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600650{
651 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700652 case glslang::EbvPointSize:
John Kessenich155d3512019-08-08 23:29:20 -0600653#ifndef GLSLANG_WEB
John Kessenich78a45572016-07-08 14:05:15 -0600654 // Defer adding the capability until the built-in is actually used.
655 if (! memberDeclaration) {
656 switch (glslangIntermediate->getStage()) {
657 case EShLangGeometry:
658 builder.addCapability(spv::CapabilityGeometryPointSize);
659 break;
660 case EShLangTessControl:
661 case EShLangTessEvaluation:
662 builder.addCapability(spv::CapabilityTessellationPointSize);
663 break;
664 default:
665 break;
666 }
John Kessenich92187592016-02-01 13:45:25 -0700667 }
John Kessenich155d3512019-08-08 23:29:20 -0600668#endif
John Kessenich92187592016-02-01 13:45:25 -0700669 return spv::BuiltInPointSize;
670
John Kessenicha28f7a72019-08-06 07:00:58 -0600671 case glslang::EbvPosition: return spv::BuiltInPosition;
672 case glslang::EbvVertexId: return spv::BuiltInVertexId;
673 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
674 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
675 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
676
677 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
678 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
679 case glslang::EbvFace: return spv::BuiltInFrontFacing;
680 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
681
John Kessenich3dd1ce52019-10-17 07:08:40 -0600682 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
683 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
684 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
685 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
686 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
687 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
688
John Kessenicha28f7a72019-08-06 07:00:58 -0600689#ifndef GLSLANG_WEB
John Kessenichebb50532016-05-16 19:22:05 -0600690 // These *Distance capabilities logically belong here, but if the member is declared and
691 // then never used, consumers of SPIR-V prefer the capability not be declared.
692 // They are now generated when used, rather than here when declared.
693 // Potentially, the specification should be more clear what the minimum
694 // use needed is to trigger the capability.
695 //
John Kessenich92187592016-02-01 13:45:25 -0700696 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100697 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800698 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700699 return spv::BuiltInClipDistance;
700
701 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100702 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800703 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700704 return spv::BuiltInCullDistance;
705
706 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600707 builder.addCapability(spv::CapabilityMultiViewport);
708 if (glslangIntermediate->getStage() == EShLangVertex ||
709 glslangIntermediate->getStage() == EShLangTessControl ||
710 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800711
John Kessenich8317e6c2019-08-18 23:58:08 -0600712 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600713 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800714 }
John Kessenich92187592016-02-01 13:45:25 -0700715 return spv::BuiltInViewportIndex;
716
John Kessenich5e801132016-02-15 11:09:46 -0700717 case glslang::EbvSampleId:
718 builder.addCapability(spv::CapabilitySampleRateShading);
719 return spv::BuiltInSampleId;
720
721 case glslang::EbvSamplePosition:
722 builder.addCapability(spv::CapabilitySampleRateShading);
723 return spv::BuiltInSamplePosition;
724
725 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700726 return spv::BuiltInSampleMask;
727
John Kessenich78a45572016-07-08 14:05:15 -0600728 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700729 if (glslangIntermediate->getStage() == EShLangMeshNV) {
730 return spv::BuiltInLayer;
731 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600732 builder.addCapability(spv::CapabilityGeometry);
733 if (glslangIntermediate->getStage() == EShLangVertex ||
734 glslangIntermediate->getStage() == EShLangTessControl ||
735 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800736
John Kessenich8317e6c2019-08-18 23:58:08 -0600737 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600738 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800739 }
John Kessenich78a45572016-07-08 14:05:15 -0600740 return spv::BuiltInLayer;
741
John Kessenichda581a22015-10-14 14:10:30 -0600742 case glslang::EbvBaseVertex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600743 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800744 builder.addCapability(spv::CapabilityDrawParameters);
745 return spv::BuiltInBaseVertex;
746
John Kessenichda581a22015-10-14 14:10:30 -0600747 case glslang::EbvBaseInstance:
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::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200751
John Kessenichda581a22015-10-14 14:10:30 -0600752 case glslang::EbvDrawId:
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::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200756
757 case glslang::EbvPrimitiveId:
758 if (glslangIntermediate->getStage() == EShLangFragment)
759 builder.addCapability(spv::CapabilityGeometry);
760 return spv::BuiltInPrimitiveId;
761
Rex Xu37cdcee2017-06-29 17:46:34 +0800762 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800763 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
764 builder.addCapability(spv::CapabilityStencilExportEXT);
765 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800766
John Kessenich140f3df2015-06-26 16:58:36 -0600767 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600768 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
769 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
770 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
771 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
John Kessenich140f3df2015-06-26 16:58:36 -0600772 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
Rex Xu51596642016-09-21 18:56:12 +0800773
Rex Xu574ab042016-04-14 16:53:07 +0800774 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800775 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800776 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
777 return spv::BuiltInSubgroupSize;
778
Rex Xu574ab042016-04-14 16:53:07 +0800779 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800780 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800781 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
782 return spv::BuiltInSubgroupLocalInvocationId;
783
Rex Xu574ab042016-04-14 16:53:07 +0800784 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800785 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
786 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600787 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800788
Rex Xu574ab042016-04-14 16:53:07 +0800789 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800790 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
791 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600792 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800793
Rex Xu574ab042016-04-14 16:53:07 +0800794 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800795 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
796 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600797 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800798
Rex Xu574ab042016-04-14 16:53:07 +0800799 case glslang::EbvSubGroupLeMask:
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::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800803
Rex Xu574ab042016-04-14 16:53:07 +0800804 case glslang::EbvSubGroupLtMask:
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::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800808
John Kessenich66011cb2018-03-06 16:12:04 -0700809 case glslang::EbvNumSubgroups:
810 builder.addCapability(spv::CapabilityGroupNonUniform);
811 return spv::BuiltInNumSubgroups;
812
813 case glslang::EbvSubgroupID:
814 builder.addCapability(spv::CapabilityGroupNonUniform);
815 return spv::BuiltInSubgroupId;
816
817 case glslang::EbvSubgroupSize2:
818 builder.addCapability(spv::CapabilityGroupNonUniform);
819 return spv::BuiltInSubgroupSize;
820
821 case glslang::EbvSubgroupInvocation2:
822 builder.addCapability(spv::CapabilityGroupNonUniform);
823 return spv::BuiltInSubgroupLocalInvocationId;
824
825 case glslang::EbvSubgroupEqMask2:
826 builder.addCapability(spv::CapabilityGroupNonUniform);
827 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
828 return spv::BuiltInSubgroupEqMask;
829
830 case glslang::EbvSubgroupGeMask2:
831 builder.addCapability(spv::CapabilityGroupNonUniform);
832 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
833 return spv::BuiltInSubgroupGeMask;
834
835 case glslang::EbvSubgroupGtMask2:
836 builder.addCapability(spv::CapabilityGroupNonUniform);
837 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
838 return spv::BuiltInSubgroupGtMask;
839
840 case glslang::EbvSubgroupLeMask2:
841 builder.addCapability(spv::CapabilityGroupNonUniform);
842 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
843 return spv::BuiltInSubgroupLeMask;
844
845 case glslang::EbvSubgroupLtMask2:
846 builder.addCapability(spv::CapabilityGroupNonUniform);
847 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
848 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600849
Rex Xu17ff3432016-10-14 17:41:45 +0800850 case glslang::EbvBaryCoordNoPersp:
851 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
852 return spv::BuiltInBaryCoordNoPerspAMD;
853
854 case glslang::EbvBaryCoordNoPerspCentroid:
855 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
856 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
857
858 case glslang::EbvBaryCoordNoPerspSample:
859 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
860 return spv::BuiltInBaryCoordNoPerspSampleAMD;
861
862 case glslang::EbvBaryCoordSmooth:
863 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
864 return spv::BuiltInBaryCoordSmoothAMD;
865
866 case glslang::EbvBaryCoordSmoothCentroid:
867 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
868 return spv::BuiltInBaryCoordSmoothCentroidAMD;
869
870 case glslang::EbvBaryCoordSmoothSample:
871 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
872 return spv::BuiltInBaryCoordSmoothSampleAMD;
873
874 case glslang::EbvBaryCoordPullModel:
875 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
876 return spv::BuiltInBaryCoordPullModelAMD;
chaoc771d89f2017-01-13 01:10:53 -0800877
John Kessenich6c8aaac2017-02-27 01:20:51 -0700878 case glslang::EbvDeviceIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600879 builder.addIncorporatedExtension(spv::E_SPV_KHR_device_group, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700880 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700881 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700882
883 case glslang::EbvViewIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600884 builder.addIncorporatedExtension(spv::E_SPV_KHR_multiview, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700885 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700886 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700887
Daniel Koch5154db52018-11-26 10:01:58 -0500888 case glslang::EbvFragSizeEXT:
889 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
890 builder.addCapability(spv::CapabilityFragmentDensityEXT);
891 return spv::BuiltInFragSizeEXT;
892
893 case glslang::EbvFragInvocationCountEXT:
894 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
895 builder.addCapability(spv::CapabilityFragmentDensityEXT);
896 return spv::BuiltInFragInvocationCountEXT;
897
chaoc771d89f2017-01-13 01:10:53 -0800898 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800899 if (!memberDeclaration) {
900 builder.addExtension(spv::E_SPV_NV_viewport_array2);
901 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
902 }
chaoc771d89f2017-01-13 01:10:53 -0800903 return spv::BuiltInViewportMaskNV;
904 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800905 if (!memberDeclaration) {
906 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
907 builder.addCapability(spv::CapabilityShaderStereoViewNV);
908 }
chaoc771d89f2017-01-13 01:10:53 -0800909 return spv::BuiltInSecondaryPositionNV;
910 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800911 if (!memberDeclaration) {
912 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
913 builder.addCapability(spv::CapabilityShaderStereoViewNV);
914 }
chaoc771d89f2017-01-13 01:10:53 -0800915 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800916 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800917 if (!memberDeclaration) {
918 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
919 builder.addCapability(spv::CapabilityPerViewAttributesNV);
920 }
chaocdf3956c2017-02-14 14:52:34 -0800921 return spv::BuiltInPositionPerViewNV;
922 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800923 if (!memberDeclaration) {
924 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
925 builder.addCapability(spv::CapabilityPerViewAttributesNV);
926 }
chaocdf3956c2017-02-14 14:52:34 -0800927 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700928 case glslang::EbvFragFullyCoveredNV:
929 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
930 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
931 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700932 case glslang::EbvFragmentSizeNV:
933 builder.addExtension(spv::E_SPV_NV_shading_rate);
934 builder.addCapability(spv::CapabilityShadingRateNV);
935 return spv::BuiltInFragmentSizeNV;
936 case glslang::EbvInvocationsPerPixelNV:
937 builder.addExtension(spv::E_SPV_NV_shading_rate);
938 builder.addCapability(spv::CapabilityShadingRateNV);
939 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700940
Daniel Koch593a4e02019-05-27 16:46:31 -0400941 // ray tracing
Daniel Kochdb32b242020-03-17 20:42:47 -0400942 case glslang::EbvLaunchId:
943 return spv::BuiltInLaunchIdKHR;
944 case glslang::EbvLaunchSize:
945 return spv::BuiltInLaunchSizeKHR;
946 case glslang::EbvWorldRayOrigin:
947 return spv::BuiltInWorldRayOriginKHR;
948 case glslang::EbvWorldRayDirection:
949 return spv::BuiltInWorldRayDirectionKHR;
950 case glslang::EbvObjectRayOrigin:
951 return spv::BuiltInObjectRayOriginKHR;
952 case glslang::EbvObjectRayDirection:
953 return spv::BuiltInObjectRayDirectionKHR;
954 case glslang::EbvRayTmin:
955 return spv::BuiltInRayTminKHR;
956 case glslang::EbvRayTmax:
957 return spv::BuiltInRayTmaxKHR;
958 case glslang::EbvInstanceCustomIndex:
959 return spv::BuiltInInstanceCustomIndexKHR;
960 case glslang::EbvHitT:
961 return spv::BuiltInHitTKHR;
962 case glslang::EbvHitKind:
963 return spv::BuiltInHitKindKHR;
964 case glslang::EbvObjectToWorld:
965 case glslang::EbvObjectToWorld3x4:
966 return spv::BuiltInObjectToWorldKHR;
967 case glslang::EbvWorldToObject:
968 case glslang::EbvWorldToObject3x4:
969 return spv::BuiltInWorldToObjectKHR;
970 case glslang::EbvIncomingRayFlags:
971 return spv::BuiltInIncomingRayFlagsKHR;
972 case glslang::EbvGeometryIndex:
973 return spv::BuiltInRayGeometryIndexKHR;
Daniel Koch593a4e02019-05-27 16:46:31 -0400974
975 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700976 case glslang::EbvBaryCoordNV:
977 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
978 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
979 return spv::BuiltInBaryCoordNV;
980 case glslang::EbvBaryCoordNoPerspNV:
981 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
982 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
983 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400984
985 // mesh shaders
986 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700987 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400988 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700989 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400990 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700991 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400992 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700993 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400994 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700995 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400996 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700997 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400998 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700999 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001000 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -07001001 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch2cb2f192019-06-04 08:43:32 -04001002
1003 // sm builtins
1004 case glslang::EbvWarpsPerSM:
1005 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1006 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1007 return spv::BuiltInWarpsPerSMNV;
1008 case glslang::EbvSMCount:
1009 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1010 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1011 return spv::BuiltInSMCountNV;
1012 case glslang::EbvWarpID:
1013 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1014 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1015 return spv::BuiltInWarpIDNV;
1016 case glslang::EbvSMID:
1017 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1018 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1019 return spv::BuiltInSMIDNV;
John Kessenicha28f7a72019-08-06 07:00:58 -06001020#endif
1021
Rex Xu3e783f92017-02-22 16:44:48 +08001022 default:
1023 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -06001024 }
1025}
1026
Rex Xufc618912015-09-09 16:42:49 +08001027// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -07001028spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +08001029{
1030 assert(type.getBasicType() == glslang::EbtSampler);
1031
John Kessenichb9197c82019-08-11 07:41:45 -06001032#ifdef GLSLANG_WEB
1033 return spv::ImageFormatUnknown;
1034#endif
1035
John Kessenich5d0fa972016-02-15 11:57:00 -07001036 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -06001037 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -07001038 case glslang::ElfRg32f:
1039 case glslang::ElfRg16f:
1040 case glslang::ElfR11fG11fB10f:
1041 case glslang::ElfR16f:
1042 case glslang::ElfRgba16:
1043 case glslang::ElfRgb10A2:
1044 case glslang::ElfRg16:
1045 case glslang::ElfRg8:
1046 case glslang::ElfR16:
1047 case glslang::ElfR8:
1048 case glslang::ElfRgba16Snorm:
1049 case glslang::ElfRg16Snorm:
1050 case glslang::ElfRg8Snorm:
1051 case glslang::ElfR16Snorm:
1052 case glslang::ElfR8Snorm:
1053
1054 case glslang::ElfRg32i:
1055 case glslang::ElfRg16i:
1056 case glslang::ElfRg8i:
1057 case glslang::ElfR16i:
1058 case glslang::ElfR8i:
1059
1060 case glslang::ElfRgb10a2ui:
1061 case glslang::ElfRg32ui:
1062 case glslang::ElfRg16ui:
1063 case glslang::ElfRg8ui:
1064 case glslang::ElfR16ui:
1065 case glslang::ElfR8ui:
1066 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1067 break;
1068
1069 default:
1070 break;
1071 }
1072
1073 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001074 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001075 case glslang::ElfNone: return spv::ImageFormatUnknown;
1076 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1077 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1078 case glslang::ElfR32f: return spv::ImageFormatR32f;
1079 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1080 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1081 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1082 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1083 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1084 case glslang::ElfR16f: return spv::ImageFormatR16f;
1085 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1086 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1087 case glslang::ElfRg16: return spv::ImageFormatRg16;
1088 case glslang::ElfRg8: return spv::ImageFormatRg8;
1089 case glslang::ElfR16: return spv::ImageFormatR16;
1090 case glslang::ElfR8: return spv::ImageFormatR8;
1091 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1092 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1093 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1094 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1095 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1096 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1097 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1098 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1099 case glslang::ElfR32i: return spv::ImageFormatR32i;
1100 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1101 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1102 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1103 case glslang::ElfR16i: return spv::ImageFormatR16i;
1104 case glslang::ElfR8i: return spv::ImageFormatR8i;
1105 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1106 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1107 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1108 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1109 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1110 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1111 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1112 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1113 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1114 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001115 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001116 }
1117}
1118
John Kessenich8985fc92020-03-03 10:25:07 -07001119spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(
1120 const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001121{
John Kesseniche18fd202018-01-30 11:01:39 -07001122 if (selectionNode.getFlatten())
1123 return spv::SelectionControlFlattenMask;
1124 if (selectionNode.getDontFlatten())
1125 return spv::SelectionControlDontFlattenMask;
1126 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001127}
1128
John Kessenich8985fc92020-03-03 10:25:07 -07001129spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode)
1130 const
steve-lunargf1709e72017-05-02 20:14:50 -06001131{
John Kesseniche18fd202018-01-30 11:01:39 -07001132 if (switchNode.getFlatten())
1133 return spv::SelectionControlFlattenMask;
1134 if (switchNode.getDontFlatten())
1135 return spv::SelectionControlDontFlattenMask;
1136 return spv::SelectionControlMaskNone;
1137}
1138
John Kessenicha2858d92018-01-31 08:11:18 -07001139// return a non-0 dependency if the dependency argument must be set
1140spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001141 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001142{
1143 spv::LoopControlMask control = spv::LoopControlMaskNone;
1144
1145 if (loopNode.getDontUnroll())
1146 control = control | spv::LoopControlDontUnrollMask;
1147 if (loopNode.getUnroll())
1148 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001149 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001150 control = control | spv::LoopControlDependencyInfiniteMask;
1151 else if (loopNode.getLoopDependency() > 0) {
1152 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001153 operands.push_back((unsigned int)loopNode.getLoopDependency());
1154 }
1155 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1156 if (loopNode.getMinIterations() > 0) {
1157 control = control | spv::LoopControlMinIterationsMask;
1158 operands.push_back(loopNode.getMinIterations());
1159 }
1160 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1161 control = control | spv::LoopControlMaxIterationsMask;
1162 operands.push_back(loopNode.getMaxIterations());
1163 }
1164 if (loopNode.getIterationMultiple() > 1) {
1165 control = control | spv::LoopControlIterationMultipleMask;
1166 operands.push_back(loopNode.getIterationMultiple());
1167 }
1168 if (loopNode.getPeelCount() > 0) {
1169 control = control | spv::LoopControlPeelCountMask;
1170 operands.push_back(loopNode.getPeelCount());
1171 }
1172 if (loopNode.getPartialCount() > 0) {
1173 control = control | spv::LoopControlPartialCountMask;
1174 operands.push_back(loopNode.getPartialCount());
1175 }
John Kessenicha2858d92018-01-31 08:11:18 -07001176 }
John Kesseniche18fd202018-01-30 11:01:39 -07001177
1178 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001179}
1180
John Kessenicha5c5fb62017-05-05 05:09:58 -06001181// Translate glslang type to SPIR-V storage class.
1182spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1183{
1184 if (type.getQualifier().isPipeInput())
1185 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001186 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001187 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001188
1189 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001190 type.getQualifier().storage == glslang::EvqUniform) {
John Kessenichdeec1932019-08-13 08:00:30 -06001191 if (type.isAtomic())
John Kessenichbed4e4f2017-09-08 02:38:07 -06001192 return spv::StorageClassAtomicCounter;
1193 if (type.containsOpaque())
1194 return spv::StorageClassUniformConstant;
1195 }
1196
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001197 if (type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001198 type.getQualifier().isShaderRecord()) {
1199 return spv::StorageClassShaderRecordBufferKHR;
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001200 }
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001201
John Kessenichbed4e4f2017-09-08 02:38:07 -06001202 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001203 builder.addIncorporatedExtension(spv::E_SPV_KHR_storage_buffer_storage_class, spv::Spv_1_3);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001204 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001205 }
1206
1207 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich7015bd62019-08-01 03:28:08 -06001208 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001209 return spv::StorageClassPushConstant;
1210 if (type.getBasicType() == glslang::EbtBlock)
1211 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001212 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001213 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001214
1215 switch (type.getQualifier().storage) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001216 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1217 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1218 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenichdeec1932019-08-13 08:00:30 -06001219 case glslang::EvqShared: return spv::StorageClassWorkgroup;
John Kessenich3dd1ce52019-10-17 07:08:40 -06001220#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -04001221 case glslang::EvqPayload: return spv::StorageClassRayPayloadKHR;
1222 case glslang::EvqPayloadIn: return spv::StorageClassIncomingRayPayloadKHR;
1223 case glslang::EvqHitAttr: return spv::StorageClassHitAttributeKHR;
1224 case glslang::EvqCallableData: return spv::StorageClassCallableDataKHR;
1225 case glslang::EvqCallableDataIn: return spv::StorageClassIncomingCallableDataKHR;
Chao Chenb50c02e2018-09-19 11:42:24 -07001226#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001227 default:
1228 assert(0);
1229 break;
1230 }
1231
1232 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001233}
1234
John Kessenich5611c6d2018-04-05 11:25:02 -06001235// Add capabilities pertaining to how an array is indexed.
1236void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1237 const glslang::TType& indexType)
1238{
John Kessenichb9197c82019-08-11 07:41:45 -06001239#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06001240 if (indexType.getQualifier().isNonUniform()) {
1241 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001242 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001243 if (baseType.getBasicType() == glslang::EbtSampler) {
1244 if (baseType.getQualifier().hasAttachment())
1245 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001246 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001247 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001248 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001249 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1250 else if (baseType.isImage())
1251 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1252 else if (baseType.isTexture())
1253 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1254 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1255 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1256 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1257 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1258 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1259 }
1260 } else {
1261 // assume a dynamically uniform index
1262 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001263 if (baseType.getQualifier().hasAttachment()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001264 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001265 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001266 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001267 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001268 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001269 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001270 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001271 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001272 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001273 }
1274 }
John Kessenichb9197c82019-08-11 07:41:45 -06001275#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06001276}
1277
qining25262b32016-05-06 17:25:16 -04001278// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001279// descriptor set.
1280bool IsDescriptorResource(const glslang::TType& type)
1281{
John Kessenichf7497e22016-03-08 21:36:22 -07001282 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001283 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001284 return type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001285 ! type.getQualifier().isShaderRecord() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001286 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001287
1288 // non block...
1289 // basically samplerXXX/subpass/sampler/texture are all included
1290 // if they are the global-scope-class, not the function parameter
1291 // (or local, if they ever exist) class.
1292 if (type.getBasicType() == glslang::EbtSampler)
1293 return type.getQualifier().isUniformOrBuffer();
1294
1295 // None of the above.
1296 return false;
1297}
1298
John Kesseniche0b6cad2015-12-24 10:30:13 -07001299void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1300{
1301 if (child.layoutMatrix == glslang::ElmNone)
1302 child.layoutMatrix = parent.layoutMatrix;
1303
1304 if (parent.invariant)
1305 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001306 if (parent.flat)
1307 child.flat = true;
1308 if (parent.centroid)
1309 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001310#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001311 if (parent.nopersp)
1312 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001313 if (parent.explicitInterp)
1314 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001315 if (parent.perPrimitiveNV)
1316 child.perPrimitiveNV = true;
1317 if (parent.perViewNV)
1318 child.perViewNV = true;
1319 if (parent.perTaskNV)
1320 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001321 if (parent.patch)
1322 child.patch = true;
1323 if (parent.sample)
1324 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001325 if (parent.coherent)
1326 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001327 if (parent.devicecoherent)
1328 child.devicecoherent = true;
1329 if (parent.queuefamilycoherent)
1330 child.queuefamilycoherent = true;
1331 if (parent.workgroupcoherent)
1332 child.workgroupcoherent = true;
1333 if (parent.subgroupcoherent)
1334 child.subgroupcoherent = true;
Daniel Kochdb32b242020-03-17 20:42:47 -04001335 if (parent.shadercallcoherent)
1336 child.shadercallcoherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001337 if (parent.nonprivate)
1338 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001339 if (parent.volatil)
1340 child.volatil = true;
1341 if (parent.restrict)
1342 child.restrict = true;
1343 if (parent.readonly)
1344 child.readonly = true;
1345 if (parent.writeonly)
1346 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001347#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001348}
1349
John Kessenichf2b7f332016-09-01 17:05:23 -06001350bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001351{
John Kessenich7b9fa252016-01-21 18:56:57 -07001352 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001353 // - struct members might inherit from a struct declaration
1354 // (note that non-block structs don't explicitly inherit,
1355 // only implicitly, meaning no decoration involved)
1356 // - affect decorations on the struct members
1357 // (note smooth does not, and expecting something like volatile
1358 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001359 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001360 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001361}
1362
John Kessenich140f3df2015-06-26 16:58:36 -06001363//
1364// Implement the TGlslangToSpvTraverser class.
1365//
1366
John Kessenich8985fc92020-03-03 10:25:07 -07001367TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion,
1368 const glslang::TIntermediate* glslangIntermediate,
1369 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options) :
1370 TIntermTraverser(true, false, true),
1371 options(options),
1372 shaderEntry(nullptr), currentFunction(nullptr),
1373 sequenceDepth(0), logger(buildLogger),
1374 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
1375 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
1376 glslangIntermediate(glslangIntermediate),
Jeff Bolz04d73732019-05-31 13:06:01 -05001377 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp()),
1378 nonSemanticDebugPrintf(0)
John Kessenich140f3df2015-06-26 16:58:36 -06001379{
1380 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1381
1382 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001383 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1384 glslangIntermediate->getVersion());
1385
John Kessenich121853f2017-05-31 17:11:16 -06001386 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001387 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001388 builder.setSourceFile(glslangIntermediate->getSourceFile());
1389
1390 // Set the source shader's text. If for SPV version 1.0, include
1391 // a preamble in comments stating the OpModuleProcessed instructions.
1392 // Otherwise, emit those as actual instructions.
1393 std::string text;
1394 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1395 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001396 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001397 text.append("// OpModuleProcessed ");
1398 text.append(processes[p]);
1399 text.append("\n");
1400 } else
1401 builder.addModuleProcessed(processes[p]);
1402 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001403 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001404 text.append("#line 1\n");
1405 text.append(glslangIntermediate->getSourceText());
1406 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001407 // Pass name and text for all included files
1408 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1409 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1410 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001411 }
John Kessenich140f3df2015-06-26 16:58:36 -06001412 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001413
1414 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1415 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1416
1417 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1418 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
John Kessenich1ff0c182019-10-10 12:01:13 -06001419 builder.addIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001420 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
John Kessenich8985fc92020-03-03 10:25:07 -07001421 }
Jeff Bolz36831c92018-09-05 10:11:41 -05001422 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001423 memoryModel = spv::MemoryModelVulkanKHR;
1424 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001425 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001426 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001427 builder.setMemoryModel(addressingModel, memoryModel);
1428
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001429 if (glslangIntermediate->usingVariablePointers()) {
1430 builder.addCapability(spv::CapabilityVariablePointers);
1431 }
1432
John Kessenicheee9d532016-09-19 18:09:30 -06001433 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1434 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001435
1436 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001437 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1438 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001439 builder.addSourceExtension(it->c_str());
1440
1441 // Add the top-level modes for this shader.
1442
John Kessenich92187592016-02-01 13:45:25 -07001443 if (glslangIntermediate->getXfbMode()) {
1444 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001445 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001446 }
John Kessenich140f3df2015-06-26 16:58:36 -06001447
1448 unsigned int mode;
1449 switch (glslangIntermediate->getStage()) {
1450 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001451 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001452 break;
1453
John Kessenicha28f7a72019-08-06 07:00:58 -06001454 case EShLangFragment:
1455 builder.addCapability(spv::CapabilityShader);
1456 if (glslangIntermediate->getPixelCenterInteger())
1457 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1458
1459 if (glslangIntermediate->getOriginUpperLeft())
1460 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1461 else
1462 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1463
1464 if (glslangIntermediate->getEarlyFragmentTests())
1465 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1466
1467 if (glslangIntermediate->getPostDepthCoverage()) {
1468 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1469 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1470 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1471 }
1472
John Kessenichb9197c82019-08-11 07:41:45 -06001473 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1474 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1475
1476#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -06001477 switch(glslangIntermediate->getDepth()) {
1478 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1479 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1480 default: mode = spv::ExecutionModeMax; break;
1481 }
1482 if (mode != spv::ExecutionModeMax)
1483 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001484 switch (glslangIntermediate->getInterlockOrdering()) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001485 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT;
1486 break;
1487 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT;
1488 break;
1489 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT;
1490 break;
1491 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT;
1492 break;
1493 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT;
1494 break;
1495 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT;
1496 break;
1497 default: mode = spv::ExecutionModeMax;
1498 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001499 }
1500 if (mode != spv::ExecutionModeMax) {
1501 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1502 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1503 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1504 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1505 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1506 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1507 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1508 } else {
1509 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1510 }
1511 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1512 }
John Kessenichb9197c82019-08-11 07:41:45 -06001513#endif
John Kessenicha28f7a72019-08-06 07:00:58 -06001514 break;
1515
John Kessenicha28f7a72019-08-06 07:00:58 -06001516 case EShLangCompute:
1517 builder.addCapability(spv::CapabilityShader);
1518 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1519 glslangIntermediate->getLocalSize(1),
1520 glslangIntermediate->getLocalSize(2));
1521 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1522 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1523 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1524 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1525 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1526 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1527 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1528 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1529 }
1530 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001531#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001532 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001533 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001534 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001535
steve-lunarge7412492017-03-23 11:56:07 -06001536 glslang::TLayoutGeometry primitive;
1537
1538 if (glslangIntermediate->getStage() == EShLangTessControl) {
John Kessenich8985fc92020-03-03 10:25:07 -07001539 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1540 glslangIntermediate->getVertices());
steve-lunarge7412492017-03-23 11:56:07 -06001541 primitive = glslangIntermediate->getOutputPrimitive();
1542 } else {
1543 primitive = glslangIntermediate->getInputPrimitive();
1544 }
1545
1546 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001547 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1548 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1549 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001550 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001551 }
John Kessenich4016e382016-07-15 11:53:56 -06001552 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001553 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1554
John Kesseniche6903322015-10-13 16:29:02 -06001555 switch (glslangIntermediate->getVertexSpacing()) {
1556 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1557 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1558 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001559 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001560 }
John Kessenich4016e382016-07-15 11:53:56 -06001561 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001562 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1563
1564 switch (glslangIntermediate->getVertexOrder()) {
1565 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1566 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001567 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001568 }
John Kessenich4016e382016-07-15 11:53:56 -06001569 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001570 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1571
1572 if (glslangIntermediate->getPointMode())
1573 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001574 break;
1575
1576 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001577 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001578 switch (glslangIntermediate->getInputPrimitive()) {
1579 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1580 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1581 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001582 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001583 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001584 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001585 }
John Kessenich4016e382016-07-15 11:53:56 -06001586 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001587 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001588
John Kessenich140f3df2015-06-26 16:58:36 -06001589 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1590
1591 switch (glslangIntermediate->getOutputPrimitive()) {
1592 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1593 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1594 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001595 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001596 }
John Kessenich4016e382016-07-15 11:53:56 -06001597 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001598 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1599 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1600 break;
1601
Daniel Kochdb32b242020-03-17 20:42:47 -04001602 case EShLangRayGen:
1603 case EShLangIntersect:
1604 case EShLangAnyHit:
1605 case EShLangClosestHit:
1606 case EShLangMiss:
1607 case EShLangCallable:
1608 {
1609 auto& extensions = glslangIntermediate->getRequestedExtensions();
1610 if (extensions.find("GL_NV_ray_tracing") == extensions.end()) {
1611 builder.addCapability(spv::CapabilityRayTracingProvisionalKHR);
1612 builder.addExtension("SPV_KHR_ray_tracing");
1613 }
1614 else {
1615 builder.addCapability(spv::CapabilityRayTracingNV);
1616 builder.addExtension("SPV_NV_ray_tracing");
1617 }
Chao Chenb50c02e2018-09-19 11:42:24 -07001618 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04001619 }
Chao Chen3c366992018-09-19 11:41:59 -07001620 case EShLangTaskNV:
1621 case EShLangMeshNV:
1622 builder.addCapability(spv::CapabilityMeshShadingNV);
1623 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1624 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1625 glslangIntermediate->getLocalSize(1),
1626 glslangIntermediate->getLocalSize(2));
1627 if (glslangIntermediate->getStage() == EShLangMeshNV) {
John Kessenich8985fc92020-03-03 10:25:07 -07001628 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1629 glslangIntermediate->getVertices());
1630 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV,
1631 glslangIntermediate->getPrimitives());
Chao Chen3c366992018-09-19 11:41:59 -07001632
1633 switch (glslangIntermediate->getOutputPrimitive()) {
1634 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1635 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1636 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1637 default: mode = spv::ExecutionModeMax; break;
1638 }
1639 if (mode != spv::ExecutionModeMax)
1640 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1641 }
1642 break;
1643#endif
1644
John Kessenich140f3df2015-06-26 16:58:36 -06001645 default:
1646 break;
1647 }
John Kessenich140f3df2015-06-26 16:58:36 -06001648}
1649
John Kessenichfca82622016-11-26 13:23:20 -07001650// Finish creating SPV, after the traversal is complete.
1651void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001652{
John Kessenichf04c51b2018-08-03 15:56:12 -06001653 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001654 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001655 builder.setBuildPoint(shaderEntry->getLastBlock());
1656 builder.leaveFunction();
1657 }
1658
John Kessenich7ba63412015-12-20 17:37:07 -07001659 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001660 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1661 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001662
David Neto8c3d5b42019-10-21 14:50:31 -04001663 // Add capabilities, extensions, remove unneeded decorations, etc.,
John Kessenichf04c51b2018-08-03 15:56:12 -06001664 // based on the resulting SPIR-V.
David Neto8c3d5b42019-10-21 14:50:31 -04001665 // Note: WebGPU code generation must have the opportunity to aggressively
1666 // prune unreachable merge blocks and continue targets.
John Kessenichf04c51b2018-08-03 15:56:12 -06001667 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001668}
1669
John Kessenichfca82622016-11-26 13:23:20 -07001670// Write the SPV into 'out'.
1671void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001672{
John Kessenichfca82622016-11-26 13:23:20 -07001673 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001674}
1675
1676//
1677// Implement the traversal functions.
1678//
1679// Return true from interior nodes to have the external traversal
1680// continue on to children. Return false if children were
1681// already processed.
1682//
1683
1684//
qining25262b32016-05-06 17:25:16 -04001685// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001686// - uniform/input reads
1687// - output writes
1688// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1689// - something simple that degenerates into the last bullet
1690//
1691void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1692{
qining75d1d802016-04-06 14:42:01 -04001693 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
Roy05a5b532020-01-03 16:21:34 +08001694 if (symbol->getType().isStruct())
1695 glslangTypeToIdMap[symbol->getType().getStruct()] = symbol->getId();
1696
qining75d1d802016-04-06 14:42:01 -04001697 if (symbol->getType().getQualifier().isSpecConstant())
1698 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1699
John Kessenich140f3df2015-06-26 16:58:36 -06001700 // getSymbolId() will set up all the IO decorations on the first call.
1701 // Formal function parameters were mapped during makeFunctions().
1702 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001703
John Kessenich7ba63412015-12-20 17:37:07 -07001704 if (builder.isPointer(id)) {
John Kessenich9c14f772019-06-17 08:38:35 -06001705 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
John Kessenich7c7731e2019-01-04 16:47:06 +07001706 // Consider adding to the OpEntryPoint interface list.
1707 // Only looking at structures if they have at least one member.
1708 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1709 spv::StorageClass sc = builder.getStorageClass(id);
1710 // Before SPIR-V 1.4, we only want to include Input and Output.
1711 // Starting with SPIR-V 1.4, we want all globals.
1712 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1713 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001714 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001715 }
John Kessenich5f77d862017-09-19 11:09:59 -06001716 }
John Kessenich9c14f772019-06-17 08:38:35 -06001717
Daniel Kochdb32b242020-03-17 20:42:47 -04001718 // If the SPIR-V type is required to be different than the AST type
1719 // (for ex SubgroupMasks or 3x4 ObjectToWorld/WorldToObject matrices),
John Kessenich9c14f772019-06-17 08:38:35 -06001720 // translate now from the SPIR-V type to the AST type, for the consuming
1721 // operation.
1722 // Note this turns it from an l-value to an r-value.
1723 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1724 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1725 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001726 }
1727
1728 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001729 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001730 // Prepare to generate code for the access
1731
1732 // L-value chains will be computed left to right. We're on the symbol now,
1733 // which is the left-most part of the access chain, so now is "clear" time,
1734 // followed by setting the base.
1735 builder.clearAccessChain();
1736
1737 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001738 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001739 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001740 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001741 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001742 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001743 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001744 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001745 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1746 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001747 builder.setAccessChainRValue(id);
1748 else
1749 builder.setAccessChainLValue(id);
1750 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001751
John Kessenichb9197c82019-08-11 07:41:45 -06001752#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001753 // Process linkage-only nodes for any special additional interface work.
1754 if (linkageOnly) {
1755 if (glslangIntermediate->getHlslFunctionality1()) {
1756 // Map implicit counter buffers to their originating buffers, which should have been
1757 // seen by now, given earlier pruning of unused counters, and preservation of order
1758 // of declaration.
1759 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1760 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1761 // Save possible originating buffers for counter buffers, keyed by
1762 // making the potential counter-buffer name.
1763 std::string keyName = symbol->getName().c_str();
1764 keyName = glslangIntermediate->addCounterBufferName(keyName);
1765 counterOriginator[keyName] = symbol;
1766 } else {
1767 // Handle a counter buffer, by finding the saved originating buffer.
1768 std::string keyName = symbol->getName().c_str();
1769 auto it = counterOriginator.find(keyName);
1770 if (it != counterOriginator.end()) {
1771 id = getSymbolId(it->second);
1772 if (id != spv::NoResult) {
1773 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001774 if (counterId != spv::NoResult) {
1775 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001776 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001777 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001778 }
1779 }
1780 }
1781 }
1782 }
1783 }
John Kessenich155d3512019-08-08 23:29:20 -06001784#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001785}
1786
1787bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1788{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001789 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Roy05a5b532020-01-03 16:21:34 +08001790 if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
1791 glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
1792 }
1793 if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
1794 glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
1795 }
John Kesseniche485c7a2017-05-31 18:50:53 -06001796
qining40887662016-04-03 22:20:42 -04001797 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1798 if (node->getType().getQualifier().isSpecConstant())
1799 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1800
John Kessenich140f3df2015-06-26 16:58:36 -06001801 // First, handle special cases
1802 switch (node->getOp()) {
1803 case glslang::EOpAssign:
1804 case glslang::EOpAddAssign:
1805 case glslang::EOpSubAssign:
1806 case glslang::EOpMulAssign:
1807 case glslang::EOpVectorTimesMatrixAssign:
1808 case glslang::EOpVectorTimesScalarAssign:
1809 case glslang::EOpMatrixTimesScalarAssign:
1810 case glslang::EOpMatrixTimesMatrixAssign:
1811 case glslang::EOpDivAssign:
1812 case glslang::EOpModAssign:
1813 case glslang::EOpAndAssign:
1814 case glslang::EOpInclusiveOrAssign:
1815 case glslang::EOpExclusiveOrAssign:
1816 case glslang::EOpLeftShiftAssign:
1817 case glslang::EOpRightShiftAssign:
1818 // A bin-op assign "a += b" means the same thing as "a = a + b"
1819 // where a is evaluated before b. For a simple assignment, GLSL
1820 // says to evaluate the left before the right. So, always, left
1821 // node then right node.
1822 {
1823 // get the left l-value, save it away
1824 builder.clearAccessChain();
1825 node->getLeft()->traverse(this);
1826 spv::Builder::AccessChain lValue = builder.getAccessChain();
1827
1828 // evaluate the right
1829 builder.clearAccessChain();
1830 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001831 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001832
1833 if (node->getOp() != glslang::EOpAssign) {
1834 // the left is also an r-value
1835 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001836 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001837
1838 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001839 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001840 TranslateNoContractionDecoration(node->getType().getQualifier()),
1841 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001842 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001843 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1844 node->getType().getBasicType());
1845
1846 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001847 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001848 }
1849
1850 // store the result
1851 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001852 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001853
1854 // assignments are expressions having an rValue after they are evaluated...
1855 builder.clearAccessChain();
1856 builder.setAccessChainRValue(rValue);
1857 }
1858 return false;
1859 case glslang::EOpIndexDirect:
1860 case glslang::EOpIndexDirectStruct:
1861 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001862 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001863 // Get the left part of the access chain.
1864 node->getLeft()->traverse(this);
1865
1866 // Add the next element in the chain
1867
David Netoa901ffe2016-06-08 14:11:40 +01001868 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001869 if (! node->getLeft()->getType().isArray() &&
1870 node->getLeft()->getType().isVector() &&
1871 node->getOp() == glslang::EOpIndexDirect) {
1872 // This is essentially a hard-coded vector swizzle of size 1,
1873 // so short circuit the access-chain stuff with a swizzle.
1874 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001875 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001876 int dummySize;
1877 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1878 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001879 glslangIntermediate->getBaseAlignmentScalar(
1880 node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001881 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001882
1883 // Load through a block reference is performed with a dot operator that
1884 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1885 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001886 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001887 !node->getLeft()->getType().isArray() &&
1888 node->getOp() == glslang::EOpIndexDirectStruct)
1889 {
1890 spv::Id left = accessChainLoad(node->getLeft()->getType());
1891 builder.clearAccessChain();
1892 builder.setAccessChainLValue(left);
1893 }
1894
David Netoa901ffe2016-06-08 14:11:40 +01001895 int spvIndex = glslangIndex;
1896 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1897 node->getOp() == glslang::EOpIndexDirectStruct)
1898 {
1899 // This may be, e.g., an anonymous block-member selection, which generally need
1900 // index remapping due to hidden members in anonymous blocks.
Roy05a5b532020-01-03 16:21:34 +08001901 int glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
1902 if (memberRemapper.find(glslangId) != memberRemapper.end()) {
1903 std::vector<int>& remapper = memberRemapper[glslangId];
1904 assert(remapper.size() > 0);
1905 spvIndex = remapper[glslangIndex];
1906 }
David Netoa901ffe2016-06-08 14:11:40 +01001907 }
John Kessenichebb50532016-05-16 19:22:05 -06001908
David Netoa901ffe2016-06-08 14:11:40 +01001909 // normal case for indexing array or structure or block
John Kessenich8985fc92020-03-03 10:25:07 -07001910 builder.accessChainPush(builder.makeIntConstant(spvIndex),
1911 TranslateCoherent(node->getLeft()->getType()),
1912 node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001913
1914 // Add capabilities here for accessing PointSize and clip/cull distance.
1915 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001916 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001917 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001918 }
1919 }
1920 return false;
1921 case glslang::EOpIndexIndirect:
1922 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001923 // Array, matrix, or vector indirection with variable index.
1924 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001925 // matrices are arrays of vectors, so will also work for a matrix.
1926 // Will use the access chain's 'component' for variable index into a vector.
1927
1928 // This adapter is building access chains left to right.
1929 // Set up the access chain to the left.
1930 node->getLeft()->traverse(this);
1931
1932 // save it so that computing the right side doesn't trash it
1933 spv::Builder::AccessChain partial = builder.getAccessChain();
1934
1935 // compute the next index in the chain
1936 builder.clearAccessChain();
1937 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001938 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001939
John Kessenich5611c6d2018-04-05 11:25:02 -06001940 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1941
John Kessenich140f3df2015-06-26 16:58:36 -06001942 // restore the saved access chain
1943 builder.setAccessChain(partial);
1944
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001945 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1946 int dummySize;
1947 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1948 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001949 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1950 dummySize));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001951 } else
John Kessenich8985fc92020-03-03 10:25:07 -07001952 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()),
1953 node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001954 }
1955 return false;
1956 case glslang::EOpVectorSwizzle:
1957 {
1958 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001959 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001960 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001961 int dummySize;
1962 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1963 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001964 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1965 dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001966 }
1967 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001968 case glslang::EOpMatrixSwizzle:
1969 logger->missingFunctionality("matrix swizzle");
1970 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001971 case glslang::EOpLogicalOr:
1972 case glslang::EOpLogicalAnd:
1973 {
1974
1975 // These may require short circuiting, but can sometimes be done as straight
1976 // binary operations. The right operand must be short circuited if it has
1977 // side effects, and should probably be if it is complex.
1978 if (isTrivial(node->getRight()->getAsTyped()))
1979 break; // handle below as a normal binary operation
1980 // otherwise, we need to do dynamic short circuiting on the right operand
John Kessenich8985fc92020-03-03 10:25:07 -07001981 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(),
1982 *node->getRight()->getAsTyped());
John Kessenich7c1aa102015-10-15 13:29:11 -06001983 builder.clearAccessChain();
1984 builder.setAccessChainRValue(result);
1985 }
1986 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001987 default:
1988 break;
1989 }
1990
1991 // Assume generic binary op...
1992
John Kessenich32cfd492016-02-02 12:37:46 -07001993 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001994 builder.clearAccessChain();
1995 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001996 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001997
John Kessenich32cfd492016-02-02 12:37:46 -07001998 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001999 builder.clearAccessChain();
2000 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002001 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002002
John Kessenich32cfd492016-02-02 12:37:46 -07002003 // get result
John Kessenichead86222018-03-28 18:01:20 -06002004 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002005 TranslateNoContractionDecoration(node->getType().getQualifier()),
2006 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002007 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07002008 convertGlslangToSpvType(node->getType()), left, right,
2009 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002010
John Kessenich50e57562015-12-21 21:21:11 -07002011 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06002012 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002013 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07002014 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06002015 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06002016 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06002017 return false;
2018 }
John Kessenich140f3df2015-06-26 16:58:36 -06002019}
2020
John Kessenich9c14f772019-06-17 08:38:35 -06002021// Figure out what, if any, type changes are needed when accessing a specific built-in.
2022// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
2023// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
Daniel Kochdb32b242020-03-17 20:42:47 -04002024std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(glslang::TBuiltInVariable glslangBuiltIn,
John Kessenich9c14f772019-06-17 08:38:35 -06002025 const glslang::TType& glslangType)
2026{
Daniel Kochdb32b242020-03-17 20:42:47 -04002027 switch(glslangBuiltIn)
John Kessenich9c14f772019-06-17 08:38:35 -06002028 {
Daniel Kochdb32b242020-03-17 20:42:47 -04002029 case glslang::EbvSubGroupEqMask:
2030 case glslang::EbvSubGroupGeMask:
2031 case glslang::EbvSubGroupGtMask:
2032 case glslang::EbvSubGroupLeMask:
2033 case glslang::EbvSubGroupLtMask: {
John Kessenich9c14f772019-06-17 08:38:35 -06002034 // these require changing a 64-bit scaler -> a vector of 32-bit components
2035 if (glslangType.isVector())
2036 break;
2037 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
2038 builder.makeUintType(64));
2039 return ret;
2040 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002041 // There are no SPIR-V builtins defined for these and map onto original non-transposed
2042 // builtins. During visitBinary we insert a transpose
2043 case glslang::EbvWorldToObject3x4:
2044 case glslang::EbvObjectToWorld3x4: {
2045 std::pair<spv::Id, spv::Id> ret(builder.makeMatrixType(builder.makeFloatType(32), 4, 3),
2046 builder.makeMatrixType(builder.makeFloatType(32), 3, 4)
2047 );
2048 return ret;
2049 }
John Kessenich9c14f772019-06-17 08:38:35 -06002050 default:
2051 break;
2052 }
2053
2054 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2055 return ret;
2056}
2057
2058// For an object previously identified (see getForcedType() and forceType)
2059// as needing type translations, do the translation needed for a load, turning
2060// an L-value into in R-value.
2061spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2062{
2063 const auto forceIt = forceType.find(object);
2064 if (forceIt == forceType.end())
2065 return object;
2066
2067 spv::Id desiredTypeId = forceIt->second;
2068 spv::Id objectTypeId = builder.getTypeId(object);
2069 assert(builder.isPointerType(objectTypeId));
2070 objectTypeId = builder.getContainedTypeId(objectTypeId);
2071 if (builder.isVectorType(objectTypeId) &&
2072 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2073 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2074 // handle 32-bit v.xy* -> 64-bit
2075 builder.clearAccessChain();
2076 builder.setAccessChainLValue(object);
2077 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2078 std::vector<spv::Id> components;
2079 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2080 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2081
2082 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2083 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2084 builder.createCompositeConstruct(vecType, components));
2085 } else {
2086 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2087 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002088 } else if (builder.isMatrixType(objectTypeId)) {
2089 // There are no SPIR-V builtins defined for 3x4 variants of ObjectToWorld/WorldToObject
2090 // and we insert a transpose after loading the original non-transposed builtins
2091 builder.clearAccessChain();
2092 builder.setAccessChainLValue(object);
2093 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2094 return builder.createUnaryOp(spv::OpTranspose, desiredTypeId, object);
2095
2096 } else {
John Kessenich9c14f772019-06-17 08:38:35 -06002097 logger->missingFunctionality("forcing non 32-bit vector type");
2098 }
2099
2100 return object;
2101}
2102
John Kessenich140f3df2015-06-26 16:58:36 -06002103bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2104{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002105 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002106
qining40887662016-04-03 22:20:42 -04002107 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2108 if (node->getType().getQualifier().isSpecConstant())
2109 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2110
John Kessenichfc51d282015-08-19 13:34:18 -06002111 spv::Id result = spv::NoResult;
2112
2113 // try texturing first
2114 result = createImageTextureFunctionCall(node);
2115 if (result != spv::NoResult) {
2116 builder.clearAccessChain();
2117 builder.setAccessChainRValue(result);
2118
2119 return false; // done with this node
2120 }
2121
2122 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002123
2124 if (node->getOp() == glslang::EOpArrayLength) {
2125 // Quite special; won't want to evaluate the operand.
2126
John Kessenich5611c6d2018-04-05 11:25:02 -06002127 // Currently, the front-end does not allow .length() on an array until it is sized,
2128 // except for the last block membeor of an SSBO.
2129 // TODO: If this changes, link-time sized arrays might show up here, and need their
2130 // size extracted.
2131
John Kessenichc9a80832015-09-12 12:17:44 -06002132 // Normal .length() would have been constant folded by the front-end.
2133 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002134 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002135
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002136 spv::Id length;
2137 if (node->getOperand()->getType().isCoopMat()) {
2138 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2139
2140 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2141 assert(builder.isCooperativeMatrixType(typeId));
2142
2143 length = builder.createCooperativeMatrixLength(typeId);
2144 } else {
2145 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2146 block->traverse(this);
John Kessenich8985fc92020-03-03 10:25:07 -07002147 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()
2148 ->getConstArray()[0].getUConst();
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002149 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2150 }
John Kessenichc9a80832015-09-12 12:17:44 -06002151
John Kessenich8c869672018-11-28 07:01:37 -07002152 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2153 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2154 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002155 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2156 if (builder.isInSpecConstCodeGenMode()) {
2157 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2158 } else {
2159 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2160 }
2161 }
John Kessenich8c869672018-11-28 07:01:37 -07002162
John Kessenichc9a80832015-09-12 12:17:44 -06002163 builder.clearAccessChain();
2164 builder.setAccessChainRValue(length);
2165
2166 return false;
2167 }
2168
John Kessenichfc51d282015-08-19 13:34:18 -06002169 // Start by evaluating the operand
2170
John Kessenich8c8505c2016-07-26 12:50:38 -06002171 // Does it need a swizzle inversion? If so, evaluation is inverted;
2172 // operate first on the swizzle base, then apply the swizzle.
2173 spv::Id invertedType = spv::NoType;
John Kessenich8985fc92020-03-03 10:25:07 -07002174 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2175 invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenich8c8505c2016-07-26 12:50:38 -06002176 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2177 invertedType = getInvertedSwizzleType(*node->getOperand());
2178
John Kessenich140f3df2015-06-26 16:58:36 -06002179 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002180 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002181 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002182 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002183 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002184 operandNode = node->getOperand();
2185
2186 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002187
Rex Xufc618912015-09-09 16:42:49 +08002188 spv::Id operand = spv::NoResult;
2189
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002190 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2191
John Kessenichfb4f2332019-08-09 03:49:15 -06002192#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002193 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2194 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002195 node->getOp() == glslang::EOpAtomicCounter ||
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002196 node->getOp() == glslang::EOpInterpolateAtCentroid) {
Rex Xufc618912015-09-09 16:42:49 +08002197 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002198 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2199 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2200 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002201#endif
2202 {
John Kessenich32cfd492016-02-02 12:37:46 -07002203 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002204 }
John Kessenich140f3df2015-06-26 16:58:36 -06002205
John Kessenichead86222018-03-28 18:01:20 -06002206 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002207 TranslateNoContractionDecoration(node->getType().getQualifier()),
2208 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002209
2210 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002211 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002212 result = createConversion(node->getOp(), decorations, resultType(), operand,
2213 node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002214
2215 // if not, then possibly an operation
2216 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002217 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand,
2218 node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002219
2220 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002221 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002222 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002223 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002224 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002225
John Kessenich140f3df2015-06-26 16:58:36 -06002226 builder.clearAccessChain();
2227 builder.setAccessChainRValue(result);
2228
2229 return false; // done with this node
2230 }
2231
2232 // it must be a special case, check...
2233 switch (node->getOp()) {
2234 case glslang::EOpPostIncrement:
2235 case glslang::EOpPostDecrement:
2236 case glslang::EOpPreIncrement:
2237 case glslang::EOpPreDecrement:
2238 {
2239 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002240 spv::Id one = 0;
2241 if (node->getBasicType() == glslang::EbtFloat)
2242 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002243#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002244 else if (node->getBasicType() == glslang::EbtDouble)
2245 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002246 else if (node->getBasicType() == glslang::EbtFloat16)
2247 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002248 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2249 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002250 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2251 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002252 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2253 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002254#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002255 else
2256 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002257 glslang::TOperator op;
2258 if (node->getOp() == glslang::EOpPreIncrement ||
2259 node->getOp() == glslang::EOpPostIncrement)
2260 op = glslang::EOpAdd;
2261 else
2262 op = glslang::EOpSub;
2263
John Kessenichead86222018-03-28 18:01:20 -06002264 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002265 convertGlslangToSpvType(node->getType()), operand, one,
2266 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002267 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002268
2269 // The result of operation is always stored, but conditionally the
2270 // consumed result. The consumed result is always an r-value.
2271 builder.accessChainStore(result);
2272 builder.clearAccessChain();
2273 if (node->getOp() == glslang::EOpPreIncrement ||
2274 node->getOp() == glslang::EOpPreDecrement)
2275 builder.setAccessChainRValue(result);
2276 else
2277 builder.setAccessChainRValue(operand);
2278 }
2279
2280 return false;
2281
John Kessenich155d3512019-08-08 23:29:20 -06002282#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002283 case glslang::EOpEmitStreamVertex:
2284 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2285 return false;
2286 case glslang::EOpEndStreamPrimitive:
2287 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2288 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002289#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002290
2291 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002292 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002293 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002294 }
John Kessenich140f3df2015-06-26 16:58:36 -06002295}
2296
Jeff Bolz53134492019-06-25 13:31:10 -05002297// Construct a composite object, recursively copying members if their types don't match
2298spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2299{
2300 for (int c = 0; c < (int)constituents.size(); ++c) {
2301 spv::Id& constituent = constituents[c];
2302 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2303 spv::Id rType = builder.getTypeId(constituent);
2304 if (lType != rType) {
2305 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2306 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2307 } else if (builder.isStructType(rType)) {
2308 std::vector<spv::Id> rTypeConstituents;
2309 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2310 for (int i = 0; i < numrTypeConstituents; ++i) {
John Kessenich8985fc92020-03-03 10:25:07 -07002311 rTypeConstituents.push_back(builder.createCompositeExtract(constituent,
2312 builder.getContainedTypeId(rType, i), i));
Jeff Bolz53134492019-06-25 13:31:10 -05002313 }
2314 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2315 } else {
2316 assert(builder.isArrayType(rType));
2317 std::vector<spv::Id> rTypeConstituents;
2318 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2319
2320 spv::Id elementRType = builder.getContainedTypeId(rType);
2321 for (int i = 0; i < numrTypeConstituents; ++i) {
2322 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2323 }
2324 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2325 }
2326 }
2327 }
2328 return builder.createCompositeConstruct(resultTypeId, constituents);
2329}
2330
John Kessenich140f3df2015-06-26 16:58:36 -06002331bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2332{
qining27e04a02016-04-14 16:40:20 -04002333 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2334 if (node->getType().getQualifier().isSpecConstant())
2335 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2336
John Kessenichfc51d282015-08-19 13:34:18 -06002337 spv::Id result = spv::NoResult;
John Kessenichbbbd9a22020-03-03 07:21:37 -07002338 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
John Kessenich8985fc92020-03-03 10:25:07 -07002339 spv::Builder::AccessChain complexLvalue; // for holding swizzling l-values too complex for SPIR-V,
2340 // for at out parameter
John Kessenichbbbd9a22020-03-03 07:21:37 -07002341 spv::Id temporaryLvalue = spv::NoResult; // temporary to pass, as proxy for complexLValue
2342
John Kessenich8985fc92020-03-03 10:25:07 -07002343 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2344 invertedType :
2345 convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002346
2347 // try texturing
2348 result = createImageTextureFunctionCall(node);
2349 if (result != spv::NoResult) {
2350 builder.clearAccessChain();
2351 builder.setAccessChainRValue(result);
2352
2353 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002354 }
2355#ifndef GLSLANG_WEB
2356 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002357 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002358 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002359 // "imageStore" is a special case, which has no result
2360 return false;
2361 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002362#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002363
John Kessenich140f3df2015-06-26 16:58:36 -06002364 glslang::TOperator binOp = glslang::EOpNull;
2365 bool reduceComparison = true;
2366 bool isMatrix = false;
2367 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002368 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002369
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002370 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2371
John Kessenich140f3df2015-06-26 16:58:36 -06002372 assert(node->getOp());
2373
John Kessenichf6640762016-08-01 19:44:00 -06002374 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002375
2376 switch (node->getOp()) {
2377 case glslang::EOpSequence:
2378 {
2379 if (preVisit)
2380 ++sequenceDepth;
2381 else
2382 --sequenceDepth;
2383
2384 if (sequenceDepth == 1) {
2385 // If this is the parent node of all the functions, we want to see them
2386 // early, so all call points have actual SPIR-V functions to reference.
2387 // In all cases, still let the traverser visit the children for us.
2388 makeFunctions(node->getAsAggregate()->getSequence());
2389
John Kessenich6fccb3c2016-09-19 16:01:41 -06002390 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002391 // anything else gets there, so visit out of order, doing them all now.
2392 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2393
John Kessenich6a60c2f2016-12-08 21:01:59 -07002394 // 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 -06002395 // so do them manually.
2396 visitFunctions(node->getAsAggregate()->getSequence());
2397
2398 return false;
2399 }
2400
2401 return true;
2402 }
2403 case glslang::EOpLinkerObjects:
2404 {
2405 if (visit == glslang::EvPreVisit)
2406 linkageOnly = true;
2407 else
2408 linkageOnly = false;
2409
2410 return true;
2411 }
2412 case glslang::EOpComma:
2413 {
2414 // processing from left to right naturally leaves the right-most
2415 // lying around in the access chain
2416 glslang::TIntermSequence& glslangOperands = node->getSequence();
2417 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2418 glslangOperands[i]->traverse(this);
2419
2420 return false;
2421 }
2422 case glslang::EOpFunction:
2423 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002424 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002425 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002426 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002427 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002428 } else {
2429 handleFunctionEntry(node);
2430 }
2431 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002432 if (inEntryPoint)
2433 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002434 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002435 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002436 }
2437
2438 return true;
2439 case glslang::EOpParameters:
2440 // Parameters will have been consumed by EOpFunction processing, but not
2441 // the body, so we still visited the function node's children, making this
2442 // child redundant.
2443 return false;
2444 case glslang::EOpFunctionCall:
2445 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002446 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002447 if (node->isUserDefined())
2448 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07002449 if (result) {
2450 builder.clearAccessChain();
2451 builder.setAccessChainRValue(result);
2452 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002453 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002454
2455 return false;
2456 }
2457 case glslang::EOpConstructMat2x2:
2458 case glslang::EOpConstructMat2x3:
2459 case glslang::EOpConstructMat2x4:
2460 case glslang::EOpConstructMat3x2:
2461 case glslang::EOpConstructMat3x3:
2462 case glslang::EOpConstructMat3x4:
2463 case glslang::EOpConstructMat4x2:
2464 case glslang::EOpConstructMat4x3:
2465 case glslang::EOpConstructMat4x4:
2466 case glslang::EOpConstructDMat2x2:
2467 case glslang::EOpConstructDMat2x3:
2468 case glslang::EOpConstructDMat2x4:
2469 case glslang::EOpConstructDMat3x2:
2470 case glslang::EOpConstructDMat3x3:
2471 case glslang::EOpConstructDMat3x4:
2472 case glslang::EOpConstructDMat4x2:
2473 case glslang::EOpConstructDMat4x3:
2474 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002475 case glslang::EOpConstructIMat2x2:
2476 case glslang::EOpConstructIMat2x3:
2477 case glslang::EOpConstructIMat2x4:
2478 case glslang::EOpConstructIMat3x2:
2479 case glslang::EOpConstructIMat3x3:
2480 case glslang::EOpConstructIMat3x4:
2481 case glslang::EOpConstructIMat4x2:
2482 case glslang::EOpConstructIMat4x3:
2483 case glslang::EOpConstructIMat4x4:
2484 case glslang::EOpConstructUMat2x2:
2485 case glslang::EOpConstructUMat2x3:
2486 case glslang::EOpConstructUMat2x4:
2487 case glslang::EOpConstructUMat3x2:
2488 case glslang::EOpConstructUMat3x3:
2489 case glslang::EOpConstructUMat3x4:
2490 case glslang::EOpConstructUMat4x2:
2491 case glslang::EOpConstructUMat4x3:
2492 case glslang::EOpConstructUMat4x4:
2493 case glslang::EOpConstructBMat2x2:
2494 case glslang::EOpConstructBMat2x3:
2495 case glslang::EOpConstructBMat2x4:
2496 case glslang::EOpConstructBMat3x2:
2497 case glslang::EOpConstructBMat3x3:
2498 case glslang::EOpConstructBMat3x4:
2499 case glslang::EOpConstructBMat4x2:
2500 case glslang::EOpConstructBMat4x3:
2501 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002502 case glslang::EOpConstructF16Mat2x2:
2503 case glslang::EOpConstructF16Mat2x3:
2504 case glslang::EOpConstructF16Mat2x4:
2505 case glslang::EOpConstructF16Mat3x2:
2506 case glslang::EOpConstructF16Mat3x3:
2507 case glslang::EOpConstructF16Mat3x4:
2508 case glslang::EOpConstructF16Mat4x2:
2509 case glslang::EOpConstructF16Mat4x3:
2510 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002511 isMatrix = true;
2512 // fall through
2513 case glslang::EOpConstructFloat:
2514 case glslang::EOpConstructVec2:
2515 case glslang::EOpConstructVec3:
2516 case glslang::EOpConstructVec4:
2517 case glslang::EOpConstructDouble:
2518 case glslang::EOpConstructDVec2:
2519 case glslang::EOpConstructDVec3:
2520 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002521 case glslang::EOpConstructFloat16:
2522 case glslang::EOpConstructF16Vec2:
2523 case glslang::EOpConstructF16Vec3:
2524 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002525 case glslang::EOpConstructBool:
2526 case glslang::EOpConstructBVec2:
2527 case glslang::EOpConstructBVec3:
2528 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002529 case glslang::EOpConstructInt8:
2530 case glslang::EOpConstructI8Vec2:
2531 case glslang::EOpConstructI8Vec3:
2532 case glslang::EOpConstructI8Vec4:
2533 case glslang::EOpConstructUint8:
2534 case glslang::EOpConstructU8Vec2:
2535 case glslang::EOpConstructU8Vec3:
2536 case glslang::EOpConstructU8Vec4:
2537 case glslang::EOpConstructInt16:
2538 case glslang::EOpConstructI16Vec2:
2539 case glslang::EOpConstructI16Vec3:
2540 case glslang::EOpConstructI16Vec4:
2541 case glslang::EOpConstructUint16:
2542 case glslang::EOpConstructU16Vec2:
2543 case glslang::EOpConstructU16Vec3:
2544 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002545 case glslang::EOpConstructInt:
2546 case glslang::EOpConstructIVec2:
2547 case glslang::EOpConstructIVec3:
2548 case glslang::EOpConstructIVec4:
2549 case glslang::EOpConstructUint:
2550 case glslang::EOpConstructUVec2:
2551 case glslang::EOpConstructUVec3:
2552 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002553 case glslang::EOpConstructInt64:
2554 case glslang::EOpConstructI64Vec2:
2555 case glslang::EOpConstructI64Vec3:
2556 case glslang::EOpConstructI64Vec4:
2557 case glslang::EOpConstructUint64:
2558 case glslang::EOpConstructU64Vec2:
2559 case glslang::EOpConstructU64Vec3:
2560 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002561 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002562 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002563 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002564 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002565 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002566 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002567 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002568 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002569 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002570 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002571 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002572 else if (node->getOp() == glslang::EOpConstructStruct ||
2573 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2574 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002575 std::vector<spv::Id> constituents;
2576 for (int c = 0; c < (int)arguments.size(); ++c)
2577 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002578 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002579 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002580 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002581 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002582 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002583
2584 builder.clearAccessChain();
2585 builder.setAccessChainRValue(constructed);
2586
2587 return false;
2588 }
2589
2590 // These six are component-wise compares with component-wise results.
2591 // Forward on to createBinaryOperation(), requesting a vector result.
2592 case glslang::EOpLessThan:
2593 case glslang::EOpGreaterThan:
2594 case glslang::EOpLessThanEqual:
2595 case glslang::EOpGreaterThanEqual:
2596 case glslang::EOpVectorEqual:
2597 case glslang::EOpVectorNotEqual:
2598 {
2599 // Map the operation to a binary
2600 binOp = node->getOp();
2601 reduceComparison = false;
2602 switch (node->getOp()) {
2603 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2604 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2605 default: binOp = node->getOp(); break;
2606 }
2607
2608 break;
2609 }
2610 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002611 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002612 binOp = glslang::EOpMul;
2613 break;
2614 case glslang::EOpOuterProduct:
2615 // two vectors multiplied to make a matrix
2616 binOp = glslang::EOpOuterProduct;
2617 break;
2618 case glslang::EOpDot:
2619 {
qining25262b32016-05-06 17:25:16 -04002620 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002621 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002622 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002623 binOp = glslang::EOpMul;
2624 break;
2625 }
2626 case glslang::EOpMod:
2627 // when an aggregate, this is the floating-point mod built-in function,
2628 // which can be emitted by the one in createBinaryOperation()
2629 binOp = glslang::EOpMod;
2630 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002631
John Kessenich140f3df2015-06-26 16:58:36 -06002632 case glslang::EOpEmitVertex:
2633 case glslang::EOpEndPrimitive:
2634 case glslang::EOpBarrier:
2635 case glslang::EOpMemoryBarrier:
2636 case glslang::EOpMemoryBarrierAtomicCounter:
2637 case glslang::EOpMemoryBarrierBuffer:
2638 case glslang::EOpMemoryBarrierImage:
2639 case glslang::EOpMemoryBarrierShared:
2640 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002641 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002642 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002643 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002644 case glslang::EOpWorkgroupMemoryBarrier:
2645 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002646 case glslang::EOpSubgroupBarrier:
2647 case glslang::EOpSubgroupMemoryBarrier:
2648 case glslang::EOpSubgroupMemoryBarrierBuffer:
2649 case glslang::EOpSubgroupMemoryBarrierImage:
2650 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002651 noReturnValue = true;
2652 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2653 break;
2654
John Kessenich426394d2015-07-23 10:22:48 -06002655 case glslang::EOpAtomicAdd:
2656 case glslang::EOpAtomicMin:
2657 case glslang::EOpAtomicMax:
2658 case glslang::EOpAtomicAnd:
2659 case glslang::EOpAtomicOr:
2660 case glslang::EOpAtomicXor:
2661 case glslang::EOpAtomicExchange:
2662 case glslang::EOpAtomicCompSwap:
2663 atomic = true;
2664 break;
2665
John Kesseniche5eee8f2019-10-18 01:03:11 -06002666#ifndef GLSLANG_WEB
2667 case glslang::EOpAtomicStore:
2668 noReturnValue = true;
2669 // fallthrough
2670 case glslang::EOpAtomicLoad:
2671 atomic = true;
2672 break;
2673
John Kessenich0d0c6d32017-07-23 16:08:26 -06002674 case glslang::EOpAtomicCounterAdd:
2675 case glslang::EOpAtomicCounterSubtract:
2676 case glslang::EOpAtomicCounterMin:
2677 case glslang::EOpAtomicCounterMax:
2678 case glslang::EOpAtomicCounterAnd:
2679 case glslang::EOpAtomicCounterOr:
2680 case glslang::EOpAtomicCounterXor:
2681 case glslang::EOpAtomicCounterExchange:
2682 case glslang::EOpAtomicCounterCompSwap:
2683 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2684 builder.addCapability(spv::CapabilityAtomicStorageOps);
2685 atomic = true;
2686 break;
2687
Ian Romanickb3bd4022019-01-21 08:57:25 -08002688 case glslang::EOpAbsDifference:
2689 case glslang::EOpAddSaturate:
2690 case glslang::EOpSubSaturate:
2691 case glslang::EOpAverage:
2692 case glslang::EOpAverageRounded:
2693 case glslang::EOpMul32x16:
2694 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2695 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2696 binOp = node->getOp();
2697 break;
2698
Daniel Kochdb32b242020-03-17 20:42:47 -04002699 case glslang::EOpIgnoreIntersection:
2700 case glslang::EOpTerminateRay:
2701 case glslang::EOpTrace:
2702 case glslang::EOpExecuteCallable:
Chao Chen3c366992018-09-19 11:41:59 -07002703 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2704 noReturnValue = true;
2705 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002706 case glslang::EOpCooperativeMatrixLoad:
2707 case glslang::EOpCooperativeMatrixStore:
2708 noReturnValue = true;
2709 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002710 case glslang::EOpBeginInvocationInterlock:
2711 case glslang::EOpEndInvocationInterlock:
2712 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2713 noReturnValue = true;
2714 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002715#endif
Chao Chen3c366992018-09-19 11:41:59 -07002716
Jeff Bolz04d73732019-05-31 13:06:01 -05002717 case glslang::EOpDebugPrintf:
2718 noReturnValue = true;
2719 break;
2720
John Kessenich140f3df2015-06-26 16:58:36 -06002721 default:
2722 break;
2723 }
2724
2725 //
2726 // See if it maps to a regular operation.
2727 //
John Kessenich140f3df2015-06-26 16:58:36 -06002728 if (binOp != glslang::EOpNull) {
2729 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2730 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2731 assert(left && right);
2732
2733 builder.clearAccessChain();
2734 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002735 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002736
2737 builder.clearAccessChain();
2738 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002739 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002740
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002741 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002742 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002743 TranslateNoContractionDecoration(node->getType().getQualifier()),
2744 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002745 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002746 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002747 left->getType().getBasicType(), reduceComparison);
2748
2749 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002750 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002751 builder.clearAccessChain();
2752 builder.setAccessChainRValue(result);
2753
2754 return false;
2755 }
2756
John Kessenich426394d2015-07-23 10:22:48 -06002757 //
2758 // Create the list of operands.
2759 //
John Kessenich140f3df2015-06-26 16:58:36 -06002760 glslang::TIntermSequence& glslangOperands = node->getSequence();
2761 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002762 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002763 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002764 // special case l-value operands; there are just a few
2765 bool lvalue = false;
2766 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002767 case glslang::EOpModf:
2768 if (arg == 1)
2769 lvalue = true;
2770 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002771
2772 case glslang::EOpAtomicAdd:
2773 case glslang::EOpAtomicMin:
2774 case glslang::EOpAtomicMax:
2775 case glslang::EOpAtomicAnd:
2776 case glslang::EOpAtomicOr:
2777 case glslang::EOpAtomicXor:
2778 case glslang::EOpAtomicExchange:
2779 case glslang::EOpAtomicCompSwap:
2780 if (arg == 0)
2781 lvalue = true;
2782 break;
2783
John Kessenicha28f7a72019-08-06 07:00:58 -06002784#ifndef GLSLANG_WEB
2785 case glslang::EOpFrexp:
2786 if (arg == 1)
2787 lvalue = true;
2788 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002789 case glslang::EOpInterpolateAtSample:
2790 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002791 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002792 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002793 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002794
2795 // Does it need a swizzle inversion? If so, evaluation is inverted;
2796 // operate first on the swizzle base, then apply the swizzle.
John Kessenichbbbd9a22020-03-03 07:21:37 -07002797 // That is, we transform
2798 //
2799 // interpolate(v.zy) -> interpolate(v).zy
2800 //
John Kessenichecba76f2017-01-06 00:34:48 -07002801 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002802 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
John Kessenich8985fc92020-03-03 10:25:07 -07002803 invertedType = convertGlslangToSpvType(
2804 glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
John Kessenich8c8505c2016-07-26 12:50:38 -06002805 }
Rex Xu7a26c172015-12-08 17:12:09 +08002806 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002807 case glslang::EOpAtomicLoad:
2808 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002809 case glslang::EOpAtomicCounterAdd:
2810 case glslang::EOpAtomicCounterSubtract:
2811 case glslang::EOpAtomicCounterMin:
2812 case glslang::EOpAtomicCounterMax:
2813 case glslang::EOpAtomicCounterAnd:
2814 case glslang::EOpAtomicCounterOr:
2815 case glslang::EOpAtomicCounterXor:
2816 case glslang::EOpAtomicCounterExchange:
2817 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002818 if (arg == 0)
2819 lvalue = true;
2820 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002821 case glslang::EOpAddCarry:
2822 case glslang::EOpSubBorrow:
2823 if (arg == 2)
2824 lvalue = true;
2825 break;
2826 case glslang::EOpUMulExtended:
2827 case glslang::EOpIMulExtended:
2828 if (arg >= 2)
2829 lvalue = true;
2830 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002831 case glslang::EOpCooperativeMatrixLoad:
2832 if (arg == 0 || arg == 1)
2833 lvalue = true;
2834 break;
2835 case glslang::EOpCooperativeMatrixStore:
2836 if (arg == 1)
2837 lvalue = true;
2838 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002839#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002840 default:
2841 break;
2842 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002843 builder.clearAccessChain();
2844 if (invertedType != spv::NoType && arg == 0)
2845 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2846 else
2847 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002848
John Kessenichb9197c82019-08-11 07:41:45 -06002849#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002850 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2851 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2852
2853 if (arg == 1) {
2854 // fold "element" parameter into the access chain
2855 spv::Builder::AccessChain save = builder.getAccessChain();
2856 builder.clearAccessChain();
2857 glslangOperands[2]->traverse(this);
2858
2859 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2860
2861 builder.setAccessChain(save);
2862
2863 // Point to the first element of the array.
John Kessenich8985fc92020-03-03 10:25:07 -07002864 builder.accessChainPush(elementId,
2865 TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
2866 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002867
2868 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2869 unsigned int alignment = builder.getAccessChain().alignment;
2870
2871 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2872 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2873 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2874 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2875 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
John Kessenich8985fc92020-03-03 10:25:07 -07002876 if (builder.getStorageClass(builder.getAccessChain().base) ==
2877 spv::StorageClassPhysicalStorageBufferEXT) {
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002878 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2879 }
2880
2881 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2882
2883 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2884 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2885 }
2886
John Kessenich8985fc92020-03-03 10:25:07 -07002887 if (memoryAccess &
2888 (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2889 memoryAccessOperands.push_back(spv::IdImmediate(true,
2890 builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002891 }
2892 } else if (arg == 2) {
2893 continue;
2894 }
2895 }
John Kessenichb9197c82019-08-11 07:41:45 -06002896#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002897
John Kessenichbbbd9a22020-03-03 07:21:37 -07002898 // for l-values, pass the address, for r-values, pass the value
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002899 if (lvalue) {
John Kessenichbbbd9a22020-03-03 07:21:37 -07002900 if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
2901 // SPIR-V cannot represent an l-value containing a swizzle that doesn't
2902 // reduce to a simple access chain. So, we need a temporary vector to
2903 // receive the result, and must later swizzle that into the original
2904 // l-value.
2905 complexLvalue = builder.getAccessChain();
John Kessenich8985fc92020-03-03 10:25:07 -07002906 temporaryLvalue = builder.createVariable(spv::StorageClassFunction,
2907 builder.accessChainGetInferredType(), "swizzleTemp");
John Kessenichbbbd9a22020-03-03 07:21:37 -07002908 operands.push_back(temporaryLvalue);
2909 } else {
2910 operands.push_back(builder.accessChainGetLValue());
2911 }
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002912 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2913 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2914 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002915 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002916 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002917 }
John Kessenich140f3df2015-06-26 16:58:36 -06002918 }
John Kessenich426394d2015-07-23 10:22:48 -06002919
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002920 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06002921#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002922 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2923 std::vector<spv::IdImmediate> idImmOps;
2924
2925 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2926 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2927 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2928 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2929 // get the pointee type
2930 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2931 assert(builder.isCooperativeMatrixType(typeId));
2932 // do the op
2933 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2934 // store the result to the pointer (out param 'm')
2935 builder.createStore(result, operands[0]);
2936 result = 0;
2937 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2938 std::vector<spv::IdImmediate> idImmOps;
2939
2940 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2941 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2942 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2943 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2944 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2945
2946 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2947 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06002948 } else
2949#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06002950 if (atomic) {
2951 // Handle all atomics
John Kessenich8985fc92020-03-03 10:25:07 -07002952 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
2953 lvalueCoherentFlags);
Jeff Bolz04d73732019-05-31 13:06:01 -05002954 } else if (node->getOp() == glslang::EOpDebugPrintf) {
2955 if (!nonSemanticDebugPrintf) {
2956 nonSemanticDebugPrintf = builder.import("NonSemantic.DebugPrintf");
2957 }
2958 result = builder.createBuiltinCall(builder.makeVoidType(), nonSemanticDebugPrintf, spv::NonSemanticDebugPrintfDebugPrintf, operands);
2959 builder.addExtension(spv::E_SPV_KHR_non_semantic_info);
John Kesseniche5eee8f2019-10-18 01:03:11 -06002960 } else {
John Kessenich426394d2015-07-23 10:22:48 -06002961 // Pass through to generic operations.
2962 switch (glslangOperands.size()) {
2963 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002964 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002965 break;
2966 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002967 {
2968 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002969 TranslateNoContractionDecoration(node->getType().getQualifier()),
2970 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002971 result = createUnaryOperation(
2972 node->getOp(), decorations,
2973 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002974 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06002975 }
John Kessenich426394d2015-07-23 10:22:48 -06002976 break;
2977 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002978 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002979 break;
2980 }
John Kessenichbbbd9a22020-03-03 07:21:37 -07002981 if (invertedType != spv::NoResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06002982 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenichbbbd9a22020-03-03 07:21:37 -07002983 else if (temporaryLvalue != spv::NoResult) {
2984 builder.setAccessChain(complexLvalue);
2985 builder.accessChainStore(builder.createLoad(temporaryLvalue));
2986 }
John Kessenich140f3df2015-06-26 16:58:36 -06002987 }
2988
2989 if (noReturnValue)
2990 return false;
2991
2992 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002993 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002994 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002995 } else {
2996 builder.clearAccessChain();
2997 builder.setAccessChainRValue(result);
2998 return false;
2999 }
3000}
3001
John Kessenich433e9ff2017-01-26 20:31:11 -07003002// This path handles both if-then-else and ?:
3003// The if-then-else has a node type of void, while
3004// ?: has either a void or a non-void node type
3005//
3006// Leaving the result, when not void:
3007// GLSL only has r-values as the result of a :?, but
3008// if we have an l-value, that can be more efficient if it will
3009// become the base of a complex r-value expression, because the
3010// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06003011bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
3012{
John Kessenich0c1e71a2019-01-10 18:23:06 +07003013 // see if OpSelect can handle it
3014 const auto isOpSelectable = [&]() {
3015 if (node->getBasicType() == glslang::EbtVoid)
3016 return false;
3017 // OpSelect can do all other types starting with SPV 1.4
3018 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
3019 // pre-1.4, only scalars and vectors can be handled
3020 if ((!node->getType().isScalar() && !node->getType().isVector()))
3021 return false;
3022 }
3023 return true;
3024 };
3025
John Kessenich4bee5312018-02-20 21:29:05 -07003026 // See if it simple and safe, or required, to execute both sides.
3027 // Crucially, side effects must be either semantically required or avoided,
3028 // and there are performance trade-offs.
3029 // Return true if required or a good idea (and safe) to execute both sides,
3030 // false otherwise.
3031 const auto bothSidesPolicy = [&]() -> bool {
3032 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07003033 if (node->getTrueBlock() == nullptr ||
3034 node->getFalseBlock() == nullptr)
3035 return false;
3036
John Kessenich4bee5312018-02-20 21:29:05 -07003037 // required? (unless we write additional code to look for side effects
3038 // and make performance trade-offs if none are present)
3039 if (!node->getShortCircuit())
3040 return true;
3041
3042 // if not required to execute both, decide based on performance/practicality...
3043
John Kessenich0c1e71a2019-01-10 18:23:06 +07003044 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07003045 return false;
3046
John Kessenich433e9ff2017-01-26 20:31:11 -07003047 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
3048 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
3049
3050 // return true if a single operand to ? : is okay for OpSelect
3051 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003052 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07003053 };
3054
3055 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
3056 operandOkay(node->getFalseBlock()->getAsTyped());
3057 };
3058
John Kessenich4bee5312018-02-20 21:29:05 -07003059 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
3060 // emit the condition before doing anything with selection
3061 node->getCondition()->traverse(this);
3062 spv::Id condition = accessChainLoad(node->getCondition()->getType());
3063
3064 // Find a way of executing both sides and selecting the right result.
3065 const auto executeBothSides = [&]() -> void {
3066 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07003067 node->getTrueBlock()->traverse(this);
3068 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3069 node->getFalseBlock()->traverse(this);
3070 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3071
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003072 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003073
John Kessenich4bee5312018-02-20 21:29:05 -07003074 // done if void
3075 if (node->getBasicType() == glslang::EbtVoid)
3076 return;
John Kesseniche434ad92017-03-30 10:09:28 -06003077
John Kessenich4bee5312018-02-20 21:29:05 -07003078 // emit code to select between trueValue and falseValue
3079
3080 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07003081 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07003082 // Emit OpSelect for this selection.
3083
3084 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07003085 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
3086 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07003087 condition = builder.smearScalar(spv::NoPrecision, condition,
3088 builder.makeVectorType(builder.makeBoolType(),
3089 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07003090 }
John Kessenich4bee5312018-02-20 21:29:05 -07003091
3092 // OpSelect
3093 result = builder.createTriOp(spv::OpSelect,
3094 convertGlslangToSpvType(node->getType()), condition,
3095 trueValue, falseValue);
3096
3097 builder.clearAccessChain();
3098 builder.setAccessChainRValue(result);
3099 } else {
3100 // We need control flow to select the result.
3101 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
3102 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
3103
3104 // Selection control:
3105 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3106
3107 // make an "if" based on the value created by the condition
3108 spv::Builder::If ifBuilder(condition, control, builder);
3109
3110 // emit the "then" statement
3111 builder.createStore(trueValue, result);
3112 ifBuilder.makeBeginElse();
3113 // emit the "else" statement
3114 builder.createStore(falseValue, result);
3115
3116 // finish off the control flow
3117 ifBuilder.makeEndIf();
3118
3119 builder.clearAccessChain();
3120 builder.setAccessChainLValue(result);
3121 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003122 };
3123
John Kessenich4bee5312018-02-20 21:29:05 -07003124 // Execute the one side needed, as per the condition
3125 const auto executeOneSide = [&]() {
3126 // Always emit control flow.
3127 if (node->getBasicType() != glslang::EbtVoid)
3128 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07003129
John Kessenich4bee5312018-02-20 21:29:05 -07003130 // Selection control:
3131 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3132
3133 // make an "if" based on the value created by the condition
3134 spv::Builder::If ifBuilder(condition, control, builder);
3135
3136 // emit the "then" statement
3137 if (node->getTrueBlock() != nullptr) {
3138 node->getTrueBlock()->traverse(this);
3139 if (result != spv::NoResult)
3140 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3141 }
3142
3143 if (node->getFalseBlock() != nullptr) {
3144 ifBuilder.makeBeginElse();
3145 // emit the "else" statement
3146 node->getFalseBlock()->traverse(this);
3147 if (result != spv::NoResult)
3148 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3149 }
3150
3151 // finish off the control flow
3152 ifBuilder.makeEndIf();
3153
3154 if (result != spv::NoResult) {
3155 builder.clearAccessChain();
3156 builder.setAccessChainLValue(result);
3157 }
3158 };
3159
3160 // Try for OpSelect (or a requirement to execute both sides)
3161 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003162 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3163 if (node->getType().getQualifier().isSpecConstant())
3164 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003165 executeBothSides();
3166 } else
3167 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003168
3169 return false;
3170}
3171
3172bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3173{
3174 // emit and get the condition before doing anything with switch
3175 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003176 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003177
Rex Xu57e65922017-07-04 23:23:40 +08003178 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003179 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003180
John Kessenich140f3df2015-06-26 16:58:36 -06003181 // browse the children to sort out code segments
3182 int defaultSegment = -1;
3183 std::vector<TIntermNode*> codeSegments;
3184 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3185 std::vector<int> caseValues;
3186 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3187 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3188 TIntermNode* child = *c;
3189 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003190 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003191 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003192 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich8985fc92020-03-03 10:25:07 -07003193 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()
3194 ->getConstArray()[0].getIConst());
John Kessenich140f3df2015-06-26 16:58:36 -06003195 } else
3196 codeSegments.push_back(child);
3197 }
3198
qining25262b32016-05-06 17:25:16 -04003199 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003200 // statements between the last case and the end of the switch statement
3201 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3202 (int)codeSegments.size() == defaultSegment)
3203 codeSegments.push_back(nullptr);
3204
3205 // make the switch statement
3206 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
John Kessenich8985fc92020-03-03 10:25:07 -07003207 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment,
3208 segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003209
3210 // emit all the code in the segments
3211 breakForLoop.push(false);
3212 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3213 builder.nextSwitchSegment(segmentBlocks, s);
3214 if (codeSegments[s])
3215 codeSegments[s]->traverse(this);
3216 else
3217 builder.addSwitchBreak();
3218 }
3219 breakForLoop.pop();
3220
3221 builder.endSwitch(segmentBlocks);
3222
3223 return false;
3224}
3225
3226void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3227{
3228 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003229 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003230
3231 builder.clearAccessChain();
3232 builder.setAccessChainRValue(constant);
3233}
3234
3235bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3236{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003237 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003238 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003239
3240 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003241 std::vector<unsigned int> operands;
3242 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003243
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003244 // Spec requires back edges to target header blocks, and every header block
3245 // must dominate its merge block. Make a header block first to ensure these
3246 // conditions are met. By definition, it will contain OpLoopMerge, followed
3247 // by a block-ending branch. But we don't want to put any other body/test
3248 // instructions in it, since the body/test may have arbitrary instructions,
3249 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003250 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003251 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003252 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003253 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003254 spv::Block& test = builder.makeNewBlock();
3255 builder.createBranch(&test);
3256
3257 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003258 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003259 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003260 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3261
3262 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003263 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003264 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003265 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003266 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003267 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003268
3269 builder.setBuildPoint(&blocks.continue_target);
3270 if (node->getTerminal())
3271 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003272 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003273 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003274 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003275 builder.createBranch(&blocks.body);
3276
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003277 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003278 builder.setBuildPoint(&blocks.body);
3279 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003280 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003281 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003282 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003283
3284 builder.setBuildPoint(&blocks.continue_target);
3285 if (node->getTerminal())
3286 node->getTerminal()->traverse(this);
3287 if (node->getTest()) {
3288 node->getTest()->traverse(this);
3289 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003290 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003291 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003292 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003293 // TODO: unless there was a break/return/discard instruction
3294 // somewhere in the body, this is an infinite loop, so we should
3295 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003296 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003297 }
John Kessenich140f3df2015-06-26 16:58:36 -06003298 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003299 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003300 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003301 return false;
3302}
3303
3304bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3305{
3306 if (node->getExpression())
3307 node->getExpression()->traverse(this);
3308
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003309 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003310
John Kessenich140f3df2015-06-26 16:58:36 -06003311 switch (node->getFlowOp()) {
3312 case glslang::EOpKill:
3313 builder.makeDiscard();
3314 break;
3315 case glslang::EOpBreak:
3316 if (breakForLoop.top())
3317 builder.createLoopExit();
3318 else
3319 builder.addSwitchBreak();
3320 break;
3321 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003322 builder.createLoopContinue();
3323 break;
3324 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003325 if (node->getExpression()) {
3326 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3327 spv::Id returnId = accessChainLoad(glslangReturnType);
3328 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3329 builder.clearAccessChain();
3330 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3331 builder.setAccessChainLValue(copyId);
3332 multiTypeStore(glslangReturnType, returnId);
3333 returnId = builder.createLoad(copyId);
3334 }
3335 builder.makeReturn(false, returnId);
3336 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003337 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003338
3339 builder.clearAccessChain();
3340 break;
3341
John Kessenichb9197c82019-08-11 07:41:45 -06003342#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003343 case glslang::EOpDemote:
3344 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3345 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3346 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3347 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003348#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003349
John Kessenich140f3df2015-06-26 16:58:36 -06003350 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003351 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003352 break;
3353 }
3354
3355 return false;
3356}
3357
John Kessenich9c14f772019-06-17 08:38:35 -06003358spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003359{
qining25262b32016-05-06 17:25:16 -04003360 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003361 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003362 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003363 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003364 spv::Id result = createSpvConstant(*node);
3365 if (result != spv::NoResult)
3366 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003367 }
3368
3369 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003370 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003371 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3372 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003373
John Kessenichb9197c82019-08-11 07:41:45 -06003374 const bool contains16BitType = node->getType().contains16BitFloat() ||
3375 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003376 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003377 switch (storageClass) {
3378 case spv::StorageClassInput:
3379 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003380 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003381 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003382 break;
John Kessenich18310872018-05-14 22:08:53 -06003383 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003384 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003385 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3386 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003387 else
3388 builder.addCapability(spv::CapabilityStorageUniform16);
3389 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003390#ifndef GLSLANG_WEB
3391 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003392 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003393 builder.addCapability(spv::CapabilityStoragePushConstant16);
3394 break;
John Kessenich18310872018-05-14 22:08:53 -06003395 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003396 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003397 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003398 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3399 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003400#endif
John Kessenich18310872018-05-14 22:08:53 -06003401 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003402 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003403 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003404 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003405 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003406 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003407 }
3408 }
Rex Xuf89ad982017-04-07 23:22:33 +08003409
John Kessenichb9197c82019-08-11 07:41:45 -06003410 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003411 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003412 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003413 builder.addCapability(spv::CapabilityStoragePushConstant8);
3414 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003415 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003416 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003417 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003418 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003419 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003420 } else {
3421 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003422 }
3423 }
3424
John Kessenich140f3df2015-06-26 16:58:36 -06003425 const char* name = node->getName().c_str();
3426 if (glslang::IsAnonymous(name))
3427 name = "";
3428
3429 return builder.createVariable(storageClass, spvType, name);
3430}
3431
3432// Return type Id of the sampled type.
3433spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3434{
3435 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003436 case glslang::EbtInt: return builder.makeIntType(32);
3437 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003438 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003439#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003440 case glslang::EbtFloat16:
3441 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3442 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3443 return builder.makeFloatType(16);
3444#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003445 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003446 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003447 return builder.makeFloatType(32);
3448 }
3449}
3450
John Kessenich8c8505c2016-07-26 12:50:38 -06003451// If node is a swizzle operation, return the type that should be used if
3452// the swizzle base is first consumed by another operation, before the swizzle
3453// is applied.
3454spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3455{
John Kessenichecba76f2017-01-06 00:34:48 -07003456 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003457 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3458 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3459 else
3460 return spv::NoType;
3461}
3462
3463// When inverting a swizzle with a parent op, this function
3464// will apply the swizzle operation to a completed parent operation.
John Kessenich8985fc92020-03-03 10:25:07 -07003465spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
3466 spv::Id parentResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003467{
3468 std::vector<unsigned> swizzle;
3469 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3470 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3471}
3472
John Kessenich8c8505c2016-07-26 12:50:38 -06003473// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3474void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3475{
3476 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3477 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3478 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3479}
3480
John Kessenich3ac051e2015-12-20 11:29:16 -07003481// Convert from a glslang type to an SPV type, by calling into a
3482// recursive version of this function. This establishes the inherited
3483// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003484spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003485{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003486 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003487}
3488
3489// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003490// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003491// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003492spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003493 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3494 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003495{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003496 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003497
3498 switch (type.getBasicType()) {
3499 case glslang::EbtVoid:
3500 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003501 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003502 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003503 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003504 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3505 // a 32-bit int where non-0 means true.
3506 if (explicitLayout != glslang::ElpNone)
3507 spvType = builder.makeUintType(32);
3508 else
3509 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003510 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003511 case glslang::EbtInt:
3512 spvType = builder.makeIntType(32);
3513 break;
3514 case glslang::EbtUint:
3515 spvType = builder.makeUintType(32);
3516 break;
3517 case glslang::EbtFloat:
3518 spvType = builder.makeFloatType(32);
3519 break;
3520#ifndef GLSLANG_WEB
3521 case glslang::EbtDouble:
3522 spvType = builder.makeFloatType(64);
3523 break;
3524 case glslang::EbtFloat16:
3525 spvType = builder.makeFloatType(16);
3526 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003527 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003528 spvType = builder.makeIntType(8);
3529 break;
3530 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003531 spvType = builder.makeUintType(8);
3532 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003533 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003534 spvType = builder.makeIntType(16);
3535 break;
3536 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003537 spvType = builder.makeUintType(16);
3538 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003539 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003540 spvType = builder.makeIntType(64);
3541 break;
3542 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003543 spvType = builder.makeUintType(64);
3544 break;
John Kessenich426394d2015-07-23 10:22:48 -06003545 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003546 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003547 spvType = builder.makeUintType(32);
3548 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04003549 case glslang::EbtAccStruct:
3550 spvType = builder.makeAccelerationStructureType();
Chao Chenb50c02e2018-09-19 11:42:24 -07003551 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003552 case glslang::EbtReference:
3553 {
3554 // Make the forward pointer, then recurse to convert the structure type, then
3555 // patch up the forward pointer with a real pointer type.
3556 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3557 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3558 forwardPointers[type.getReferentType()] = forwardId;
3559 }
3560 spvType = forwardPointers[type.getReferentType()];
3561 if (!forwardReferenceOnly) {
3562 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3563 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3564 forwardPointers[type.getReferentType()],
3565 referentType);
3566 }
3567 }
3568 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003569#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003570 case glslang::EbtSampler:
3571 {
3572 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003573 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003574 spvType = builder.makeSamplerType();
3575 } else {
3576 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003577 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3578 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3579 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3580 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003581 // already has both image and sampler, make the combined type
3582 spvType = builder.makeSampledImageType(spvType);
3583 }
John Kessenich55e7d112015-11-15 21:33:39 -07003584 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003585 }
John Kessenich140f3df2015-06-26 16:58:36 -06003586 break;
3587 case glslang::EbtStruct:
3588 case glslang::EbtBlock:
3589 {
3590 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003591 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003592
3593 // Try to share structs for different layouts, but not yet for other
3594 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003595 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003596 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003597 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003598 break;
3599
3600 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003601 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003602 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003603 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003604 }
3605 break;
Jeff Bolz04d73732019-05-31 13:06:01 -05003606 case glslang::EbtString:
3607 // no type used for OpString
3608 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003609 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003610 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003611 break;
3612 }
3613
3614 if (type.isMatrix())
3615 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3616 else {
3617 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3618 if (type.getVectorSize() > 1)
3619 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3620 }
3621
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003622 if (type.isCoopMat()) {
3623 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3624 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3625 if (type.getBasicType() == glslang::EbtFloat16)
3626 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003627 if (type.getBasicType() == glslang::EbtUint8 ||
3628 type.getBasicType() == glslang::EbtInt8) {
3629 builder.addCapability(spv::CapabilityInt8);
3630 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003631
3632 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3633 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3634 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3635
3636 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3637 }
3638
John Kessenich140f3df2015-06-26 16:58:36 -06003639 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003640 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3641
John Kessenichc9a80832015-09-12 12:17:44 -06003642 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003643 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003644 // We need to decorate array strides for types needing explicit layout, except blocks.
3645 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003646 // Use a dummy glslang type for querying internal strides of
3647 // arrays of arrays, but using just a one-dimensional array.
3648 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003649 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3650 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003651
3652 // Will compute the higher-order strides here, rather than making a whole
3653 // pile of types and doing repetitive recursion on their contents.
3654 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3655 }
John Kessenichf8842e52016-01-04 19:22:56 -07003656
3657 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003658 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003659 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003660 if (stride > 0)
3661 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003662 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003663 }
3664 } else {
3665 // single-dimensional array, and don't yet have stride
3666
John Kessenichf8842e52016-01-04 19:22:56 -07003667 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003668 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3669 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003670 }
John Kessenich31ed4832015-09-09 17:51:38 -06003671
John Kessenichead86222018-03-28 18:01:20 -06003672 // Do the outer dimension, which might not be known for a runtime-sized array.
3673 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3674 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003675 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003676 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003677#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003678 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003679 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003680 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3681 }
John Kessenichb9197c82019-08-11 07:41:45 -06003682#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003683 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003684 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003685 if (stride > 0)
3686 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003687 }
3688
3689 return spvType;
3690}
3691
John Kessenich0e737842017-03-24 18:38:16 -06003692// TODO: this functionality should exist at a higher level, in creating the AST
3693//
3694// Identify interface members that don't have their required extension turned on.
3695//
3696bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3697{
John Kessenicha28f7a72019-08-06 07:00:58 -06003698#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003699 auto& extensions = glslangIntermediate->getRequestedExtensions();
3700
Rex Xubcf291a2017-03-29 23:01:36 +08003701 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3702 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3703 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003704 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3705 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3706 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003707
3708 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3709 if (member.getFieldName() == "gl_ViewportMask" &&
3710 extensions.find("GL_NV_viewport_array2") == extensions.end())
3711 return true;
3712 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3713 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3714 return true;
3715 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3716 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3717 return true;
3718 }
3719#endif
John Kessenich0e737842017-03-24 18:38:16 -06003720
3721 return false;
3722};
3723
John Kessenich6090df02016-06-30 21:18:02 -06003724// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3725// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3726// Mutually recursive with convertGlslangToSpvType().
3727spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3728 const glslang::TTypeList* glslangMembers,
3729 glslang::TLayoutPacking explicitLayout,
3730 const glslang::TQualifier& qualifier)
3731{
3732 // Create a vector of struct types for SPIR-V to consume
3733 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07003734 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
3735 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003736 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003737 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3738 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3739 if (glslangMember.hiddenMember()) {
3740 ++memberDelta;
3741 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003742 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06003743 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003744 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003745 if (filterMember(glslangMember)) {
3746 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08003747 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003748 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003749 }
Roy05a5b532020-01-03 16:21:34 +08003750 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003751 }
John Kessenich6090df02016-06-30 21:18:02 -06003752 // modify just this child's view of the qualifier
3753 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3754 InheritQualifiers(memberQualifier, qualifier);
3755
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003756 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003757 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003758 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003759
3760 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003761 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3762 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003763
3764 // Make forward pointers for any pointer members, and create a list of members to
3765 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003766 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003767 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3768 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3769 }
3770 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003771 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3772 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003773 } else {
3774 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003775 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3776 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003777 }
John Kessenich6090df02016-06-30 21:18:02 -06003778 }
3779 }
3780
3781 // Make the SPIR-V type
3782 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003783 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003784 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3785
3786 // Decorate it
3787 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3788
John Kessenichd72f4882019-01-16 14:55:37 +07003789 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003790 auto it = deferredForwardPointers[i];
3791 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3792 }
3793
John Kessenich6090df02016-06-30 21:18:02 -06003794 return spvType;
3795}
3796
3797void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3798 const glslang::TTypeList* glslangMembers,
3799 glslang::TLayoutPacking explicitLayout,
3800 const glslang::TQualifier& qualifier,
3801 spv::Id spvType)
3802{
3803 // Name and decorate the non-hidden members
3804 int offset = -1;
3805 int locationOffset = 0; // for use within the members of this struct
3806 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3807 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3808 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003809 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08003810 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06003811 if (filterMember(glslangMember))
3812 continue;
3813 }
John Kessenich6090df02016-06-30 21:18:02 -06003814
3815 // modify just this child's view of the qualifier
3816 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3817 InheritQualifiers(memberQualifier, qualifier);
3818
3819 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003820 if (member < 0)
3821 continue;
3822
3823 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3824 builder.addMemberDecoration(spvType, member,
3825 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3826 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3827 // Add interpolation and auxiliary storage decorations only to
3828 // top-level members of Input and Output storage classes
3829 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3830 type.getQualifier().storage == glslang::EvqVaryingOut) {
3831 if (type.getBasicType() == glslang::EbtBlock ||
3832 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3833 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3834 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003835#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003836 addMeshNVDecoration(spvType, member, memberQualifier);
3837#endif
John Kessenich6090df02016-06-30 21:18:02 -06003838 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003839 }
3840 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003841
John Kessenichb9197c82019-08-11 07:41:45 -06003842#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003843 if (type.getBasicType() == glslang::EbtBlock &&
3844 qualifier.storage == glslang::EvqBuffer) {
3845 // Add memory decorations only to top-level members of shader storage block
3846 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003847 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003848 for (unsigned int i = 0; i < memory.size(); ++i)
3849 builder.addMemberDecoration(spvType, member, memory[i]);
3850 }
John Kessenichf8d1d742019-10-21 06:55:11 -06003851
John Kessenichb9197c82019-08-11 07:41:45 -06003852#endif
John Kessenich6090df02016-06-30 21:18:02 -06003853
John Kessenich5d610ee2018-03-07 18:05:55 -07003854 // Location assignment was already completed correctly by the front end,
3855 // just track whether a member needs to be decorated.
3856 // Ignore member locations if the container is an array, as that's
3857 // ill-specified and decisions have been made to not allow this.
3858 if (! type.isArray() && memberQualifier.hasLocation())
3859 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003860
John Kessenich5d610ee2018-03-07 18:05:55 -07003861 if (qualifier.hasLocation()) // track for upcoming inheritance
3862 locationOffset += glslangIntermediate->computeTypeLocationSize(
3863 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003864
John Kessenich5d610ee2018-03-07 18:05:55 -07003865 // component, XFB, others
3866 if (glslangMember.getQualifier().hasComponent())
3867 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3868 glslangMember.getQualifier().layoutComponent);
3869 if (glslangMember.getQualifier().hasXfbOffset())
3870 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3871 glslangMember.getQualifier().layoutXfbOffset);
3872 else if (explicitLayout != glslang::ElpNone) {
3873 // figure out what to do with offset, which is accumulating
3874 int nextOffset;
3875 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3876 if (offset >= 0)
3877 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3878 offset = nextOffset;
3879 }
John Kessenich6090df02016-06-30 21:18:02 -06003880
John Kessenich5d610ee2018-03-07 18:05:55 -07003881 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3882 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3883 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003884
John Kessenich5d610ee2018-03-07 18:05:55 -07003885 // built-in variable decorations
3886 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3887 if (builtIn != spv::BuiltInMax)
3888 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003889
John Kessenichb9197c82019-08-11 07:41:45 -06003890#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003891 // nonuniform
3892 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3893
John Kessenichead86222018-03-28 18:01:20 -06003894 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3895 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3896 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3897 memberQualifier.semanticName);
3898 }
3899
John Kessenich5d610ee2018-03-07 18:05:55 -07003900 if (builtIn == spv::BuiltInLayer) {
3901 // SPV_NV_viewport_array2 extension
3902 if (glslangMember.getQualifier().layoutViewportRelative){
3903 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3904 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3905 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003906 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003907 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3908 builder.addMemberDecoration(spvType, member,
3909 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3910 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3911 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3912 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003913 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003914 }
3915 if (glslangMember.getQualifier().layoutPassthrough) {
3916 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3917 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3918 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3919 }
chaoc771d89f2017-01-13 01:10:53 -08003920#endif
John Kessenich6090df02016-06-30 21:18:02 -06003921 }
3922
3923 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003924 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3925 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003926}
3927
John Kessenich6c292d32016-02-15 20:58:50 -07003928// Turn the expression forming the array size into an id.
3929// This is not quite trivial, because of specialization constants.
3930// Sometimes, a raw constant is turned into an Id, and sometimes
3931// a specialization constant expression is.
3932spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3933{
3934 // First, see if this is sized with a node, meaning a specialization constant:
3935 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3936 if (specNode != nullptr) {
3937 builder.clearAccessChain();
3938 specNode->traverse(this);
3939 return accessChainLoad(specNode->getAsTyped()->getType());
3940 }
qining25262b32016-05-06 17:25:16 -04003941
John Kessenich6c292d32016-02-15 20:58:50 -07003942 // Otherwise, need a compile-time (front end) size, get it:
3943 int size = arraySizes.getDimSize(dim);
3944 assert(size > 0);
3945 return builder.makeUintConstant(size);
3946}
3947
John Kessenich103bef92016-02-08 21:38:15 -07003948// Wrap the builder's accessChainLoad to:
3949// - localize handling of RelaxedPrecision
3950// - use the SPIR-V inferred type instead of another conversion of the glslang type
3951// (avoids unnecessary work and possible type punning for structures)
3952// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003953spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3954{
John Kessenich103bef92016-02-08 21:38:15 -07003955 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003956
3957 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3958 coherentFlags |= TranslateCoherent(type);
3959
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003960 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003961 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003962
John Kessenich5611c6d2018-04-05 11:25:02 -06003963 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
John Kessenich8985fc92020-03-03 10:25:07 -07003964 TranslateNonUniformDecoration(type.getQualifier()),
3965 nominalTypeId,
3966 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
3967 TranslateMemoryScope(coherentFlags),
3968 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003969
3970 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003971 if (type.getBasicType() == glslang::EbtBool) {
3972 if (builder.isScalarType(nominalTypeId)) {
3973 // Conversion for bool
3974 spv::Id boolType = builder.makeBoolType();
3975 if (nominalTypeId != boolType)
3976 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3977 } else if (builder.isVectorType(nominalTypeId)) {
3978 // Conversion for bvec
3979 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3980 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3981 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07003982 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
3983 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003984 }
3985 }
John Kessenich103bef92016-02-08 21:38:15 -07003986
3987 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003988}
3989
Rex Xu27253232016-02-23 17:51:09 +08003990// Wrap the builder's accessChainStore to:
3991// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003992//
3993// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003994void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3995{
3996 // Need to convert to abstract types when necessary
3997 if (type.getBasicType() == glslang::EbtBool) {
3998 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3999
4000 if (builder.isScalarType(nominalTypeId)) {
4001 // Conversion for bool
4002 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06004003 if (nominalTypeId != boolType) {
4004 // keep these outside arguments, for determinant order-of-evaluation
4005 spv::Id one = builder.makeUintConstant(1);
4006 spv::Id zero = builder.makeUintConstant(0);
4007 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
4008 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06004009 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08004010 } else if (builder.isVectorType(nominalTypeId)) {
4011 // Conversion for bvec
4012 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4013 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06004014 if (nominalTypeId != bvecType) {
4015 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06004016 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
4017 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
4018 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06004019 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06004020 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
4021 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004022 }
4023 }
4024
Jeff Bolz36831c92018-09-05 10:11:41 -05004025 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4026 coherentFlags |= TranslateCoherent(type);
4027
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004028 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004029 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004030
Jeff Bolz36831c92018-09-05 10:11:41 -05004031 builder.accessChainStore(rvalue,
John Kessenich8985fc92020-03-03 10:25:07 -07004032 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
4033 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004034 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08004035}
4036
John Kessenich4bf71552016-09-02 11:20:21 -06004037// For storing when types match at the glslang level, but not might match at the
4038// SPIR-V level.
4039//
4040// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004041// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004042// as in a member-decorated way.
4043//
4044// NOTE: This function can handle any store request; if it's not special it
4045// simplifies to a simple OpStore.
4046//
4047// Implicitly uses the existing builder.accessChain as the storage target.
4048void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4049{
John Kessenichb3e24e42016-09-11 12:33:43 -06004050 // we only do the complex path here if it's an aggregate
4051 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004052 accessChainStore(type, rValue);
4053 return;
4054 }
4055
John Kessenichb3e24e42016-09-11 12:33:43 -06004056 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004057 spv::Id rType = builder.getTypeId(rValue);
4058 spv::Id lValue = builder.accessChainGetLValue();
4059 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4060 if (lType == rType) {
4061 accessChainStore(type, rValue);
4062 return;
4063 }
4064
John Kessenichb3e24e42016-09-11 12:33:43 -06004065 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004066 // where the two types were the same type in GLSL. This requires member
4067 // by member copy, recursively.
4068
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004069 // SPIR-V 1.4 added an instruction to do help do this.
4070 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4071 // However, bool in uniform space is changed to int, so
4072 // OpCopyLogical does not work for that.
4073 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4074 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4075 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4076 if (lBool == rBool) {
4077 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4078 accessChainStore(type, logicalCopy);
4079 return;
4080 }
4081 }
4082
John Kessenichb3e24e42016-09-11 12:33:43 -06004083 // If an array, copy element by element.
4084 if (type.isArray()) {
4085 glslang::TType glslangElementType(type, 0);
4086 spv::Id elementRType = builder.getContainedTypeId(rType);
4087 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4088 // get the source member
4089 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004090
John Kessenichb3e24e42016-09-11 12:33:43 -06004091 // set up the target storage
4092 builder.clearAccessChain();
4093 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004094 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4095 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004096
John Kessenichb3e24e42016-09-11 12:33:43 -06004097 // store the member
4098 multiTypeStore(glslangElementType, elementRValue);
4099 }
4100 } else {
4101 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004102
John Kessenichb3e24e42016-09-11 12:33:43 -06004103 // loop over structure members
4104 const glslang::TTypeList& members = *type.getStruct();
4105 for (int m = 0; m < (int)members.size(); ++m) {
4106 const glslang::TType& glslangMemberType = *members[m].type;
4107
4108 // get the source member
4109 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4110 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4111
4112 // set up the target storage
4113 builder.clearAccessChain();
4114 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004115 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4116 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004117
4118 // store the member
4119 multiTypeStore(glslangMemberType, memberRValue);
4120 }
John Kessenich4bf71552016-09-02 11:20:21 -06004121 }
4122}
4123
John Kessenichf85e8062015-12-19 13:57:10 -07004124// Decide whether or not this type should be
4125// decorated with offsets and strides, and if so
4126// whether std140 or std430 rules should be applied.
4127glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004128{
John Kessenichf85e8062015-12-19 13:57:10 -07004129 // has to be a block
4130 if (type.getBasicType() != glslang::EbtBlock)
4131 return glslang::ElpNone;
4132
Chao Chen3c366992018-09-19 11:41:59 -07004133 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004134 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004135 type.getQualifier().storage != glslang::EvqBuffer &&
4136 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004137 return glslang::ElpNone;
4138
4139 // return the layout to use
4140 switch (type.getQualifier().layoutPacking) {
4141 case glslang::ElpStd140:
4142 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004143 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004144 return type.getQualifier().layoutPacking;
4145 default:
4146 return glslang::ElpNone;
4147 }
John Kessenich31ed4832015-09-09 17:51:38 -06004148}
4149
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004150// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004151int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4152 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004153{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004154 int size;
John Kessenich49987892015-12-29 17:11:44 -07004155 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004156 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4157 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004158
4159 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004160}
4161
John Kessenich49987892015-12-29 17:11:44 -07004162// 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 -07004163// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004164int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4165 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004166{
John Kessenich49987892015-12-29 17:11:44 -07004167 glslang::TType elementType;
4168 elementType.shallowCopy(matrixType);
4169 elementType.clearArraySizes();
4170
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004171 int size;
John Kessenich49987892015-12-29 17:11:44 -07004172 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004173 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4174 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004175
4176 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004177}
4178
John Kessenich5e4b1242015-08-06 22:53:06 -06004179// Given a member type of a struct, realign the current offset for it, and compute
4180// the next (not yet aligned) offset for the next member, which will get aligned
4181// on the next call.
4182// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4183// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4184// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004185void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4186 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004187{
4188 // this will get a positive value when deemed necessary
4189 nextOffset = -1;
4190
John Kessenich5e4b1242015-08-06 22:53:06 -06004191 // override anything in currentOffset with user-set offset
4192 if (memberType.getQualifier().hasOffset())
4193 currentOffset = memberType.getQualifier().layoutOffset;
4194
4195 // It could be that current linker usage in glslang updated all the layoutOffset,
4196 // in which case the following code does not matter. But, that's not quite right
4197 // once cross-compilation unit GLSL validation is done, as the original user
4198 // settings are needed in layoutOffset, and then the following will come into play.
4199
John Kessenichf85e8062015-12-19 13:57:10 -07004200 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004201 if (! memberType.getQualifier().hasOffset())
4202 currentOffset = -1;
4203
4204 return;
4205 }
4206
John Kessenichf85e8062015-12-19 13:57:10 -07004207 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004208 if (currentOffset < 0)
4209 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004210
John Kessenich5e4b1242015-08-06 22:53:06 -06004211 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4212 // but possibly not yet correctly aligned.
4213
4214 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004215 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004216 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4217 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004218
4219 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004220 // TODO: make this consistent in early phases of code:
4221 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4222 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4223 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004224 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004225 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004226 int dummySize;
4227 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4228 if (componentAlignment <= 4)
4229 memberAlignment = componentAlignment;
4230 }
4231
4232 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004233 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004234
4235 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004236 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4237 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004238 glslang::RoundToPow2(currentOffset, 16);
4239
John Kessenich5e4b1242015-08-06 22:53:06 -06004240 nextOffset = currentOffset + memberSize;
4241}
4242
David Netoa901ffe2016-06-08 14:11:40 +01004243void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004244{
David Netoa901ffe2016-06-08 14:11:40 +01004245 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4246 switch (glslangBuiltIn)
4247 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004248 case glslang::EbvPointSize:
4249#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004250 case glslang::EbvClipDistance:
4251 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004252 case glslang::EbvViewportMaskNV:
4253 case glslang::EbvSecondaryPositionNV:
4254 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004255 case glslang::EbvPositionPerViewNV:
4256 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004257 case glslang::EbvTaskCountNV:
4258 case glslang::EbvPrimitiveCountNV:
4259 case glslang::EbvPrimitiveIndicesNV:
4260 case glslang::EbvClipDistancePerViewNV:
4261 case glslang::EbvCullDistancePerViewNV:
4262 case glslang::EbvLayerPerViewNV:
4263 case glslang::EbvMeshViewCountNV:
4264 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004265#endif
David Netoa901ffe2016-06-08 14:11:40 +01004266 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4267 // Alternately, we could just call this for any glslang built-in, since the
4268 // capability already guards against duplicates.
4269 TranslateBuiltInDecoration(glslangBuiltIn, false);
4270 break;
4271 default:
4272 // Capabilities were already generated when the struct was declared.
4273 break;
4274 }
John Kessenichebb50532016-05-16 19:22:05 -06004275}
4276
John Kessenich6fccb3c2016-09-19 16:01:41 -06004277bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004278{
John Kessenicheee9d532016-09-19 18:09:30 -06004279 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004280}
4281
John Kessenichd41993d2017-09-10 15:21:05 -06004282// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004283// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4284// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004285bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004286{
John Kessenich6a14f782017-12-04 02:48:10 -07004287 assert(qualifier == glslang::EvqIn ||
4288 qualifier == glslang::EvqOut ||
4289 qualifier == glslang::EvqInOut ||
4290 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004291 return qualifier != glslang::EvqConstReadOnly;
4292}
4293
4294// Is parameter pass-by-original?
4295bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4296 bool implicitThisParam)
4297{
4298 if (implicitThisParam) // implicit this
4299 return true;
4300 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004301 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004302 return paramType.containsOpaque() || // sampler, etc.
4303 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4304}
4305
John Kessenich140f3df2015-06-26 16:58:36 -06004306// Make all the functions, skeletally, without actually visiting their bodies.
4307void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4308{
John Kessenich8985fc92020-03-03 10:25:07 -07004309 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4310 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004311 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4312 if (paramPrecision != spv::NoPrecision)
4313 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004314 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004315 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004316 // Original and non-writable params pass the pointer directly and
4317 // use restrict/aliased, others are stored to a pointer in Function
4318 // memory and use RestrictPointer/AliasedPointer.
4319 if (originalParam(type.getQualifier().storage, type, false) ||
4320 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004321 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4322 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004323 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004324 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4325 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004326 }
4327 }
John Kessenichfad62972017-07-18 02:35:46 -06004328 };
4329
John Kessenich140f3df2015-06-26 16:58:36 -06004330 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4331 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004332 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004333 continue;
4334
4335 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004336 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004337 //
qining25262b32016-05-06 17:25:16 -04004338 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004339 // function. What it is an address of varies:
4340 //
John Kessenich4bf71552016-09-02 11:20:21 -06004341 // - "in" parameters not marked as "const" can be written to without modifying the calling
4342 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004343 //
4344 // - "const in" parameters can just be the r-value, as no writes need occur.
4345 //
John Kessenich4bf71552016-09-02 11:20:21 -06004346 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4347 // 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 -06004348
4349 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004350 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004351 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4352
John Kessenich155d3512019-08-08 23:29:20 -06004353#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004354 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4355 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004356#else
4357 bool implicitThis = false;
4358#endif
John Kessenich37789792017-03-21 23:56:40 -06004359
John Kessenichfad62972017-07-18 02:35:46 -06004360 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004361 for (int p = 0; p < (int)parameters.size(); ++p) {
4362 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4363 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004364 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004365 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004366 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004367 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4368 else
John Kessenich4bf71552016-09-02 11:20:21 -06004369 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004370 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004371 paramTypes.push_back(typeId);
4372 }
4373
4374 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004375 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4376 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004377 glslFunction->getName().c_str(), paramTypes,
4378 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004379 if (implicitThis)
4380 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004381
4382 // Track function to emit/call later
4383 functionMap[glslFunction->getName().c_str()] = function;
4384
4385 // Set the parameter id's
4386 for (int p = 0; p < (int)parameters.size(); ++p) {
4387 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4388 // give a name too
4389 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004390
4391 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004392 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004393 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004394 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004395 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004396 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004397 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004398 }
4399 }
4400}
4401
4402// Process all the initializers, while skipping the functions and link objects
4403void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4404{
4405 builder.setBuildPoint(shaderEntry->getLastBlock());
4406 for (int i = 0; i < (int)initializers.size(); ++i) {
4407 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004408 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4409 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004410
4411 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004412 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004413 initializer->traverse(this);
4414 }
4415 }
4416}
4417
4418// Process all the functions, while skipping initializers.
4419void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4420{
4421 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4422 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004423 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004424 node->traverse(this);
4425 }
4426}
4427
4428void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4429{
qining25262b32016-05-06 17:25:16 -04004430 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004431 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004432 currentFunction = functionMap[node->getName().c_str()];
4433 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004434 builder.setBuildPoint(functionBlock);
4435}
4436
John Kessenich8985fc92020-03-03 10:25:07 -07004437void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4438 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004439{
Rex Xufc618912015-09-09 16:42:49 +08004440 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004441
4442 glslang::TSampler sampler = {};
4443 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004444#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004445 bool f16ShadowCompare = false;
4446#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004447 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004448 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4449 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004450#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004451 f16ShadowCompare = sampler.shadow &&
4452 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004453#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004454 }
4455
John Kessenich140f3df2015-06-26 16:58:36 -06004456 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4457 builder.clearAccessChain();
4458 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004459
John Kessenicha28f7a72019-08-06 07:00:58 -06004460#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004461 // Special case l-value operands
4462 bool lvalue = false;
4463 switch (node.getOp()) {
4464 case glslang::EOpImageAtomicAdd:
4465 case glslang::EOpImageAtomicMin:
4466 case glslang::EOpImageAtomicMax:
4467 case glslang::EOpImageAtomicAnd:
4468 case glslang::EOpImageAtomicOr:
4469 case glslang::EOpImageAtomicXor:
4470 case glslang::EOpImageAtomicExchange:
4471 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004472 case glslang::EOpImageAtomicLoad:
4473 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004474 if (i == 0)
4475 lvalue = true;
4476 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004477 case glslang::EOpSparseImageLoad:
4478 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4479 lvalue = true;
4480 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004481 case glslang::EOpSparseTexture:
4482 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4483 lvalue = true;
4484 break;
4485 case glslang::EOpSparseTextureClamp:
4486 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4487 lvalue = true;
4488 break;
4489 case glslang::EOpSparseTextureLod:
4490 case glslang::EOpSparseTextureOffset:
4491 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4492 lvalue = true;
4493 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004494 case glslang::EOpSparseTextureFetch:
4495 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4496 lvalue = true;
4497 break;
4498 case glslang::EOpSparseTextureFetchOffset:
4499 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4500 lvalue = true;
4501 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004502 case glslang::EOpSparseTextureLodOffset:
4503 case glslang::EOpSparseTextureGrad:
4504 case glslang::EOpSparseTextureOffsetClamp:
4505 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4506 lvalue = true;
4507 break;
4508 case glslang::EOpSparseTextureGradOffset:
4509 case glslang::EOpSparseTextureGradClamp:
4510 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4511 lvalue = true;
4512 break;
4513 case glslang::EOpSparseTextureGradOffsetClamp:
4514 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4515 lvalue = true;
4516 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004517 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004518 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4519 lvalue = true;
4520 break;
4521 case glslang::EOpSparseTextureGatherOffset:
4522 case glslang::EOpSparseTextureGatherOffsets:
4523 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4524 lvalue = true;
4525 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004526 case glslang::EOpSparseTextureGatherLod:
4527 if (i == 3)
4528 lvalue = true;
4529 break;
4530 case glslang::EOpSparseTextureGatherLodOffset:
4531 case glslang::EOpSparseTextureGatherLodOffsets:
4532 if (i == 4)
4533 lvalue = true;
4534 break;
Rex Xu129799a2017-07-05 17:23:28 +08004535 case glslang::EOpSparseImageLoadLod:
4536 if (i == 3)
4537 lvalue = true;
4538 break;
Chao Chen3a137962018-09-19 11:41:27 -07004539 case glslang::EOpImageSampleFootprintNV:
4540 if (i == 4)
4541 lvalue = true;
4542 break;
4543 case glslang::EOpImageSampleFootprintClampNV:
4544 case glslang::EOpImageSampleFootprintLodNV:
4545 if (i == 5)
4546 lvalue = true;
4547 break;
4548 case glslang::EOpImageSampleFootprintGradNV:
4549 if (i == 6)
4550 lvalue = true;
4551 break;
4552 case glslang::EOpImageSampleFootprintGradClampNV:
4553 if (i == 7)
4554 lvalue = true;
4555 break;
Rex Xufc618912015-09-09 16:42:49 +08004556 default:
4557 break;
4558 }
4559
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004560 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004561 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004562 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4563 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4564 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004565#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004566 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004567 }
4568}
4569
John Kessenichfc51d282015-08-19 13:34:18 -06004570void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004571{
John Kessenichfc51d282015-08-19 13:34:18 -06004572 builder.clearAccessChain();
4573 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004574 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004575}
John Kessenich140f3df2015-06-26 16:58:36 -06004576
John Kessenichfc51d282015-08-19 13:34:18 -06004577spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4578{
John Kesseniche485c7a2017-05-31 18:50:53 -06004579 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004580 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004581
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004582 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004583
John Kessenichfc51d282015-08-19 13:34:18 -06004584 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004585
John Kessenichf43c7392019-03-31 10:51:57 -06004586 const glslang::TType &imageType = node->getAsAggregate()
4587 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4588 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004589 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004590#ifdef GLSLANG_WEB
4591 const bool f16ShadowCompare = false;
4592#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004593 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004594 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4595 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004596#endif
4597
John Kessenichf43c7392019-03-31 10:51:57 -06004598 const auto signExtensionMask = [&]() {
4599 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4600 if (sampler.type == glslang::EbtUint)
4601 return spv::ImageOperandsZeroExtendMask;
4602 else if (sampler.type == glslang::EbtInt)
4603 return spv::ImageOperandsSignExtendMask;
4604 }
4605 return spv::ImageOperandsMaskNone;
4606 };
4607
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004608 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4609
John Kessenichfc51d282015-08-19 13:34:18 -06004610 std::vector<spv::Id> arguments;
4611 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004612 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004613 else
4614 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004615 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004616
4617 spv::Builder::TextureParameters params = { };
4618 params.sampler = arguments[0];
4619
Rex Xu04db3f52015-09-16 11:44:02 +08004620 glslang::TCrackedTextureOp cracked;
4621 node->crackTexture(sampler, cracked);
4622
amhagan05506bb2017-06-13 16:53:02 -04004623 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004624
John Kessenichfc51d282015-08-19 13:34:18 -06004625 // Check for queries
4626 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004627 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4628 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004629 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004630
John Kessenichfc51d282015-08-19 13:34:18 -06004631 switch (node->getOp()) {
4632 case glslang::EOpImageQuerySize:
4633 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004634 if (arguments.size() > 1) {
4635 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004636 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004637 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004638 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004639#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004640 case glslang::EOpImageQuerySamples:
4641 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004642 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004643 case glslang::EOpTextureQueryLod:
4644 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004645 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004646 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004647 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004648 case glslang::EOpSparseTexelsResident:
4649 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004650#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004651 default:
4652 assert(0);
4653 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004654 }
John Kessenich140f3df2015-06-26 16:58:36 -06004655 }
4656
LoopDawg4425f242018-02-18 11:40:01 -07004657 int components = node->getType().getVectorSize();
4658
4659 if (node->getOp() == glslang::EOpTextureFetch) {
4660 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4661 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4662 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4663 // here around e.g. which ones return scalars or other types.
4664 components = 4;
4665 }
4666
4667 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4668
4669 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4670
Rex Xufc618912015-09-09 16:42:49 +08004671 // Check for image functions other than queries
4672 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004673 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004674 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004675 spv::IdImmediate image = { true, *(opIt++) };
4676 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004677
4678 // Handle subpass operations
4679 // TODO: GLSL should change to have the "MS" only on the type rather than the
4680 // built-in function.
4681 if (cracked.subpass) {
4682 // add on the (0,0) coordinate
4683 spv::Id zero = builder.makeIntConstant(0);
4684 std::vector<spv::Id> comps;
4685 comps.push_back(zero);
4686 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004687 spv::IdImmediate coord = { true,
4688 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4689 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004690 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4691 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004692 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004693 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4694 }
4695 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004696 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004697 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004698 spv::IdImmediate imageOperand = { true, *(opIt++) };
4699 operands.push_back(imageOperand);
4700 }
John Kessenich6c292d32016-02-15 20:58:50 -07004701 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004702 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4703 builder.setPrecision(result, precision);
4704 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004705 }
4706
John Kessenich149afc32018-08-14 13:31:43 -06004707 spv::IdImmediate coord = { true, *(opIt++) };
4708 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004709 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004710 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004711 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004712 mask = mask | spv::ImageOperandsSampleMask;
4713 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004714 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004715 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4716 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004717 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004718 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004719 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4720 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004721 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004722 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004723 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4724 operands.push_back(imageOperands);
4725 }
4726 if (mask & spv::ImageOperandsSampleMask) {
4727 spv::IdImmediate imageOperand = { true, *opIt++ };
4728 operands.push_back(imageOperand);
4729 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004730 if (mask & spv::ImageOperandsLodMask) {
4731 spv::IdImmediate imageOperand = { true, *opIt++ };
4732 operands.push_back(imageOperand);
4733 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004734 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004735 spv::IdImmediate imageOperand = { true,
4736 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004737 operands.push_back(imageOperand);
4738 }
4739
John Kessenich149afc32018-08-14 13:31:43 -06004740 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004741 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004742
John Kessenich149afc32018-08-14 13:31:43 -06004743 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004744 builder.setPrecision(result[0], precision);
4745
4746 // If needed, add a conversion constructor to the proper size.
4747 if (components != node->getType().getVectorSize())
4748 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4749
4750 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004751 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004752
Jeff Bolz36831c92018-09-05 10:11:41 -05004753 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004754 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004755 spv::IdImmediate texel = { true, *(opIt + 1) };
4756 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004757 } else {
4758 spv::IdImmediate texel = { true, *opIt };
4759 operands.push_back(texel);
4760 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004761
4762 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004763 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004764 mask = mask | spv::ImageOperandsSampleMask;
4765 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004766 if (cracked.lod) {
4767 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4768 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4769 mask = mask | spv::ImageOperandsLodMask;
4770 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004771 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4772 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004773 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004774 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004775 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4776 operands.push_back(imageOperands);
4777 }
4778 if (mask & spv::ImageOperandsSampleMask) {
4779 spv::IdImmediate imageOperand = { true, *opIt++ };
4780 operands.push_back(imageOperand);
4781 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004782 if (mask & spv::ImageOperandsLodMask) {
4783 spv::IdImmediate imageOperand = { true, *opIt++ };
4784 operands.push_back(imageOperand);
4785 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004786 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004787 spv::IdImmediate imageOperand = { true,
4788 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004789 operands.push_back(imageOperand);
4790 }
4791
John Kessenich56bab042015-09-16 10:54:31 -06004792 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004793 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004794 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004795 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004796 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4797 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004798 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004799 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004800 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4801
Jeff Bolz36831c92018-09-05 10:11:41 -05004802 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004803 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004804 mask = mask | spv::ImageOperandsSampleMask;
4805 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004806 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004807 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4808 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4809
Jeff Bolz36831c92018-09-05 10:11:41 -05004810 mask = mask | spv::ImageOperandsLodMask;
4811 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004812 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4813 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004814 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004815 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004816 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004817 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004818 }
4819 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004820 spv::IdImmediate imageOperand = { true, *opIt++ };
4821 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004822 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004823 if (mask & spv::ImageOperandsLodMask) {
4824 spv::IdImmediate imageOperand = { true, *opIt++ };
4825 operands.push_back(imageOperand);
4826 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004827 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07004828 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
4829 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004830 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004831 }
4832
4833 // Create the return type that was a special structure
4834 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004835 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004836 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4837 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4838
4839 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4840
4841 // Decode the return type
4842 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4843 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004844 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004845 // Process image atomic operations
4846
4847 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4848 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004849 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004850 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004851 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004852
Jeff Bolz36831c92018-09-05 10:11:41 -05004853 spv::Id resultTypeId;
4854 // imageAtomicStore has a void return type so base the pointer type on
4855 // the type of the value operand.
4856 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08004857 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05004858 } else {
4859 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4860 }
John Kessenich56bab042015-09-16 10:54:31 -06004861 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Jeff Bolz39ffdaf2020-03-09 10:48:12 -05004862 if (imageType.getQualifier().nonUniform) {
4863 builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
4864 }
Rex Xufc618912015-09-09 16:42:49 +08004865
4866 std::vector<spv::Id> operands;
4867 operands.push_back(pointer);
4868 for (; opIt != arguments.end(); ++opIt)
4869 operands.push_back(*opIt);
4870
John Kessenich8985fc92020-03-03 10:25:07 -07004871 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
4872 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004873 }
4874 }
4875
John Kessenicha28f7a72019-08-06 07:00:58 -06004876#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004877 // Check for fragment mask functions other than queries
4878 if (cracked.fragMask) {
4879 assert(sampler.ms);
4880
4881 auto opIt = arguments.begin();
4882 std::vector<spv::Id> operands;
4883
4884 // Extract the image if necessary
4885 if (builder.isSampledImage(params.sampler))
4886 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4887
4888 operands.push_back(params.sampler);
4889 ++opIt;
4890
4891 if (sampler.isSubpass()) {
4892 // add on the (0,0) coordinate
4893 spv::Id zero = builder.makeIntConstant(0);
4894 std::vector<spv::Id> comps;
4895 comps.push_back(zero);
4896 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07004897 operands.push_back(builder.makeCompositeConstant(
4898 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04004899 }
4900
4901 for (; opIt != arguments.end(); ++opIt)
4902 operands.push_back(*opIt);
4903
4904 spv::Op fragMaskOp = spv::OpNop;
4905 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4906 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4907 else if (node->getOp() == glslang::EOpFragmentFetch)
4908 fragMaskOp = spv::OpFragmentFetchAMD;
4909
4910 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4911 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4912 return builder.createOp(fragMaskOp, resultType(), operands);
4913 }
4914#endif
4915
Rex Xufc618912015-09-09 16:42:49 +08004916 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004917 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004918 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004919 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08004920
John Kessenichfc51d282015-08-19 13:34:18 -06004921 // check for bias argument
4922 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004923 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004924 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004925 if (cracked.gather)
4926 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004927
4928 if (f16ShadowCompare)
4929 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004930 if (cracked.offset)
4931 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004932 else if (cracked.offsets)
4933 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004934 if (cracked.grad)
4935 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004936 if (cracked.lodClamp)
4937 ++nonBiasArgCount;
4938 if (sparse)
4939 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004940 if (imageFootprint)
4941 //Following three extra arguments
4942 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4943 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06004944 if ((int)arguments.size() > nonBiasArgCount)
4945 bias = true;
4946 }
4947
John Kessenicha5c33d62016-06-02 23:45:21 -06004948 // See if the sampler param should really be just the SPV image part
4949 if (cracked.fetch) {
4950 // a fetch needs to have the image extracted first
4951 if (builder.isSampledImage(params.sampler))
4952 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4953 }
4954
John Kessenicha28f7a72019-08-06 07:00:58 -06004955#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08004956 if (cracked.gather) {
4957 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4958 if (bias || cracked.lod ||
4959 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4960 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004961 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004962 }
4963 }
4964#endif
4965
John Kessenichfc51d282015-08-19 13:34:18 -06004966 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004967
John Kessenichfc51d282015-08-19 13:34:18 -06004968 params.coords = arguments[1];
4969 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004970 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004971
4972 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004973 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004974 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004975 ++extraArgs;
4976 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004977 params.Dref = arguments[2];
4978 ++extraArgs;
4979 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004980 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004981 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004982 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004983 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004984 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004985 dRefComp = builder.getNumComponents(params.coords) - 1;
4986 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07004987 params.Dref = builder.createCompositeExtract(params.coords,
4988 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06004989 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004990
4991 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004992 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004993 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004994 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06004995 } else if (glslangIntermediate->getStage() != EShLangFragment &&
4996 !(glslangIntermediate->getStage() == EShLangCompute &&
4997 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07004998 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4999 noImplicitLod = true;
5000 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005001
5002 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005003 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005004 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08005005 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005006 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005007
5008 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06005009 if (cracked.grad) {
5010 params.gradX = arguments[2 + extraArgs];
5011 params.gradY = arguments[3 + extraArgs];
5012 extraArgs += 2;
5013 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005014
5015 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07005016 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06005017 params.offset = arguments[2 + extraArgs];
5018 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005019 } else if (cracked.offsets) {
5020 params.offsets = arguments[2 + extraArgs];
5021 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005022 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005023
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005024#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005025 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005026 if (cracked.lodClamp) {
5027 params.lodClamp = arguments[2 + extraArgs];
5028 ++extraArgs;
5029 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005030 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005031 if (sparse) {
5032 params.texelOut = arguments[2 + extraArgs];
5033 ++extraArgs;
5034 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005035 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005036 if (cracked.gather && ! sampler.shadow) {
5037 // default component is 0, if missing, otherwise an argument
5038 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005039 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005040 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005041 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005042 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005043 }
Chao Chen3a137962018-09-19 11:41:27 -07005044 spv::Id resultStruct = spv::NoResult;
5045 if (imageFootprint) {
5046 //Following three extra arguments
5047 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5048 params.granularity = arguments[2 + extraArgs];
5049 params.coarse = arguments[3 + extraArgs];
5050 resultStruct = arguments[4 + extraArgs];
5051 extraArgs += 3;
5052 }
5053#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005054 // bias
5055 if (bias) {
5056 params.bias = arguments[2 + extraArgs];
5057 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005058 }
John Kessenichfc51d282015-08-19 13:34:18 -06005059
John Kessenicha28f7a72019-08-06 07:00:58 -06005060#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005061 if (imageFootprint) {
5062 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5063 builder.addCapability(spv::CapabilityImageFootprintNV);
5064
5065
5066 //resultStructType(OpenGL type) contains 5 elements:
5067 //struct gl_TextureFootprint2DNV {
5068 // uvec2 anchor;
5069 // uvec2 offset;
5070 // uvec2 mask;
5071 // uint lod;
5072 // uint granularity;
5073 //};
5074 //or
5075 //struct gl_TextureFootprint3DNV {
5076 // uvec3 anchor;
5077 // uvec3 offset;
5078 // uvec2 mask;
5079 // uint lod;
5080 // uint granularity;
5081 //};
5082 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5083 assert(builder.isStructType(resultStructType));
5084
5085 //resType (SPIR-V type) contains 6 elements:
5086 //Member 0 must be a Boolean type scalar(LOD),
5087 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5088 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5089 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5090 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5091 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5092 std::vector<spv::Id> members;
5093 members.push_back(resultType());
5094 for (int i = 0; i < 5; i++) {
5095 members.push_back(builder.getContainedTypeId(resultStructType, i));
5096 }
5097 spv::Id resType = builder.makeStructType(members, "ResType");
5098
5099 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005100 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5101 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005102
5103 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5104 for (int i = 0; i < 5; i++) {
5105 builder.clearAccessChain();
5106 builder.setAccessChainLValue(resultStruct);
5107
5108 //Accessing to a struct we created, no coherent flag is set
5109 spv::Builder::AccessChain::CoherentFlags flags;
5110 flags.clear();
5111
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005112 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005113 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
5114 i+1));
Chao Chen3a137962018-09-19 11:41:27 -07005115 }
5116 return builder.createCompositeExtract(res, resultType(), 0);
5117 }
5118#endif
5119
John Kessenich65336482016-06-16 14:06:26 -06005120 // projective component (might not to move)
5121 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5122 // are divided by the last component of P."
5123 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5124 // unused components will appear after all used components."
5125 if (cracked.proj) {
5126 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5127 int projTargetComp;
5128 switch (sampler.dim) {
5129 case glslang::Esd1D: projTargetComp = 1; break;
5130 case glslang::Esd2D: projTargetComp = 2; break;
5131 case glslang::EsdRect: projTargetComp = 2; break;
5132 default: projTargetComp = projSourceComp; break;
5133 }
5134 // copy the projective coordinate if we have to
5135 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005136 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005137 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005138 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005139 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005140 }
5141 }
5142
John Kessenichf8d1d742019-10-21 06:55:11 -06005143#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005144 // nonprivate
5145 if (imageType.getQualifier().nonprivate) {
5146 params.nonprivate = true;
5147 }
5148
5149 // volatile
5150 if (imageType.getQualifier().volatil) {
5151 params.volatil = true;
5152 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005153#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005154
St0fFa1184dd2018-04-09 21:08:14 +02005155 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005156 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5157 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005158 );
LoopDawg4425f242018-02-18 11:40:01 -07005159
5160 if (components != node->getType().getVectorSize())
5161 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5162
5163 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005164}
5165
5166spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5167{
5168 // Grab the function's pointer from the previously created function
5169 spv::Function* function = functionMap[node->getName().c_str()];
5170 if (! function)
5171 return 0;
5172
5173 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5174 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5175
5176 // See comments in makeFunctions() for details about the semantics for parameter passing.
5177 //
5178 // These imply we need a four step process:
5179 // 1. Evaluate the arguments
5180 // 2. Allocate and make copies of in, out, and inout arguments
5181 // 3. Make the call
5182 // 4. Copy back the results
5183
John Kessenichd3ed90b2018-05-04 11:43:03 -06005184 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005185 std::vector<spv::Builder::AccessChain> lValues;
5186 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005187 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005188 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005189 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005190 // build l-value
5191 builder.clearAccessChain();
5192 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005193 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005194 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005195 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005196 // save l-value
5197 lValues.push_back(builder.getAccessChain());
5198 } else {
5199 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005200 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005201 }
5202 }
5203
5204 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5205 // copy the original into that space.
5206 //
5207 // Also, build up the list of actual arguments to pass in for the call
5208 int lValueCount = 0;
5209 int rValueCount = 0;
5210 std::vector<spv::Id> spvArgs;
5211 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5212 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005213 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005214 builder.setAccessChain(lValues[lValueCount]);
5215 arg = builder.accessChainGetLValue();
5216 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005217 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005218 // need space to hold the copy
John Kessenich8985fc92020-03-03 10:25:07 -07005219 arg = builder.createVariable(spv::StorageClassFunction,
5220 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005221 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5222 // need to copy the input into output space
5223 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005224 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005225 builder.clearAccessChain();
5226 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005227 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005228 }
5229 ++lValueCount;
5230 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005231 // process r-value, which involves a copy for a type mismatch
5232 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5233 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5234 builder.clearAccessChain();
5235 builder.setAccessChainLValue(argCopy);
5236 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5237 arg = builder.createLoad(argCopy);
5238 } else
5239 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005240 ++rValueCount;
5241 }
5242 spvArgs.push_back(arg);
5243 }
5244
5245 // 3. Make the call.
5246 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005247 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005248
5249 // 4. Copy back out an "out" arguments.
5250 lValueCount = 0;
5251 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005252 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005253 ++lValueCount;
5254 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005255 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5256 spv::Id copy = builder.createLoad(spvArgs[a]);
5257 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005258 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005259 }
5260 ++lValueCount;
5261 }
5262 }
5263
5264 return result;
5265}
5266
5267// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005268spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005269 spv::Id typeId, spv::Id left, spv::Id right,
5270 glslang::TBasicType typeProxy, bool reduceComparison)
5271{
John Kessenich66011cb2018-03-06 16:12:04 -07005272 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5273 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005274 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005275
5276 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005277 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005278 bool comparison = false;
5279
5280 switch (op) {
5281 case glslang::EOpAdd:
5282 case glslang::EOpAddAssign:
5283 if (isFloat)
5284 binOp = spv::OpFAdd;
5285 else
5286 binOp = spv::OpIAdd;
5287 break;
5288 case glslang::EOpSub:
5289 case glslang::EOpSubAssign:
5290 if (isFloat)
5291 binOp = spv::OpFSub;
5292 else
5293 binOp = spv::OpISub;
5294 break;
5295 case glslang::EOpMul:
5296 case glslang::EOpMulAssign:
5297 if (isFloat)
5298 binOp = spv::OpFMul;
5299 else
5300 binOp = spv::OpIMul;
5301 break;
5302 case glslang::EOpVectorTimesScalar:
5303 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005304 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005305 if (builder.isVector(right))
5306 std::swap(left, right);
5307 assert(builder.isScalar(right));
5308 needMatchingVectors = false;
5309 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005310 } else if (isFloat)
5311 binOp = spv::OpFMul;
5312 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005313 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005314 break;
5315 case glslang::EOpVectorTimesMatrix:
5316 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005317 binOp = spv::OpVectorTimesMatrix;
5318 break;
5319 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005320 binOp = spv::OpMatrixTimesVector;
5321 break;
5322 case glslang::EOpMatrixTimesScalar:
5323 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005324 binOp = spv::OpMatrixTimesScalar;
5325 break;
5326 case glslang::EOpMatrixTimesMatrix:
5327 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005328 binOp = spv::OpMatrixTimesMatrix;
5329 break;
5330 case glslang::EOpOuterProduct:
5331 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005332 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005333 break;
5334
5335 case glslang::EOpDiv:
5336 case glslang::EOpDivAssign:
5337 if (isFloat)
5338 binOp = spv::OpFDiv;
5339 else if (isUnsigned)
5340 binOp = spv::OpUDiv;
5341 else
5342 binOp = spv::OpSDiv;
5343 break;
5344 case glslang::EOpMod:
5345 case glslang::EOpModAssign:
5346 if (isFloat)
5347 binOp = spv::OpFMod;
5348 else if (isUnsigned)
5349 binOp = spv::OpUMod;
5350 else
5351 binOp = spv::OpSMod;
5352 break;
5353 case glslang::EOpRightShift:
5354 case glslang::EOpRightShiftAssign:
5355 if (isUnsigned)
5356 binOp = spv::OpShiftRightLogical;
5357 else
5358 binOp = spv::OpShiftRightArithmetic;
5359 break;
5360 case glslang::EOpLeftShift:
5361 case glslang::EOpLeftShiftAssign:
5362 binOp = spv::OpShiftLeftLogical;
5363 break;
5364 case glslang::EOpAnd:
5365 case glslang::EOpAndAssign:
5366 binOp = spv::OpBitwiseAnd;
5367 break;
5368 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005369 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005370 binOp = spv::OpLogicalAnd;
5371 break;
5372 case glslang::EOpInclusiveOr:
5373 case glslang::EOpInclusiveOrAssign:
5374 binOp = spv::OpBitwiseOr;
5375 break;
5376 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005377 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005378 binOp = spv::OpLogicalOr;
5379 break;
5380 case glslang::EOpExclusiveOr:
5381 case glslang::EOpExclusiveOrAssign:
5382 binOp = spv::OpBitwiseXor;
5383 break;
5384 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005385 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005386 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005387 break;
5388
Ian Romanickb3bd4022019-01-21 08:57:25 -08005389 case glslang::EOpAbsDifference:
5390 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5391 break;
5392
5393 case glslang::EOpAddSaturate:
5394 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5395 break;
5396
5397 case glslang::EOpSubSaturate:
5398 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5399 break;
5400
5401 case glslang::EOpAverage:
5402 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5403 break;
5404
5405 case glslang::EOpAverageRounded:
5406 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5407 break;
5408
5409 case glslang::EOpMul32x16:
5410 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5411 break;
5412
John Kessenich140f3df2015-06-26 16:58:36 -06005413 case glslang::EOpLessThan:
5414 case glslang::EOpGreaterThan:
5415 case glslang::EOpLessThanEqual:
5416 case glslang::EOpGreaterThanEqual:
5417 case glslang::EOpEqual:
5418 case glslang::EOpNotEqual:
5419 case glslang::EOpVectorEqual:
5420 case glslang::EOpVectorNotEqual:
5421 comparison = true;
5422 break;
5423 default:
5424 break;
5425 }
5426
John Kessenich7c1aa102015-10-15 13:29:11 -06005427 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005428 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005429 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005430 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5431 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005432 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005433
5434 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005435 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005436 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005437
qining25262b32016-05-06 17:25:16 -04005438 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005439 decorations.addNoContraction(builder, result);
5440 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005441 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005442 }
5443
5444 if (! comparison)
5445 return 0;
5446
John Kessenich7c1aa102015-10-15 13:29:11 -06005447 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005448
John Kessenich4583b612016-08-07 19:14:22 -06005449 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005450 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5451 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005452 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005453 return result;
5454 }
John Kessenich140f3df2015-06-26 16:58:36 -06005455
5456 switch (op) {
5457 case glslang::EOpLessThan:
5458 if (isFloat)
5459 binOp = spv::OpFOrdLessThan;
5460 else if (isUnsigned)
5461 binOp = spv::OpULessThan;
5462 else
5463 binOp = spv::OpSLessThan;
5464 break;
5465 case glslang::EOpGreaterThan:
5466 if (isFloat)
5467 binOp = spv::OpFOrdGreaterThan;
5468 else if (isUnsigned)
5469 binOp = spv::OpUGreaterThan;
5470 else
5471 binOp = spv::OpSGreaterThan;
5472 break;
5473 case glslang::EOpLessThanEqual:
5474 if (isFloat)
5475 binOp = spv::OpFOrdLessThanEqual;
5476 else if (isUnsigned)
5477 binOp = spv::OpULessThanEqual;
5478 else
5479 binOp = spv::OpSLessThanEqual;
5480 break;
5481 case glslang::EOpGreaterThanEqual:
5482 if (isFloat)
5483 binOp = spv::OpFOrdGreaterThanEqual;
5484 else if (isUnsigned)
5485 binOp = spv::OpUGreaterThanEqual;
5486 else
5487 binOp = spv::OpSGreaterThanEqual;
5488 break;
5489 case glslang::EOpEqual:
5490 case glslang::EOpVectorEqual:
5491 if (isFloat)
5492 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005493 else if (isBool)
5494 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005495 else
5496 binOp = spv::OpIEqual;
5497 break;
5498 case glslang::EOpNotEqual:
5499 case glslang::EOpVectorNotEqual:
5500 if (isFloat)
5501 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005502 else if (isBool)
5503 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005504 else
5505 binOp = spv::OpINotEqual;
5506 break;
5507 default:
5508 break;
5509 }
5510
qining25262b32016-05-06 17:25:16 -04005511 if (binOp != spv::OpNop) {
5512 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005513 decorations.addNoContraction(builder, result);
5514 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005515 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005516 }
John Kessenich140f3df2015-06-26 16:58:36 -06005517
5518 return 0;
5519}
5520
John Kessenich04bb8a02015-12-12 12:28:14 -07005521//
5522// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5523// These can be any of:
5524//
5525// matrix * scalar
5526// scalar * matrix
5527// matrix * matrix linear algebraic
5528// matrix * vector
5529// vector * matrix
5530// matrix * matrix componentwise
5531// matrix op matrix op in {+, -, /}
5532// matrix op scalar op in {+, -, /}
5533// scalar op matrix op in {+, -, /}
5534//
John Kessenichead86222018-03-28 18:01:20 -06005535spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5536 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005537{
5538 bool firstClass = true;
5539
5540 // First, handle first-class matrix operations (* and matrix/scalar)
5541 switch (op) {
5542 case spv::OpFDiv:
5543 if (builder.isMatrix(left) && builder.isScalar(right)) {
5544 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005545 spv::Id resultType = builder.getTypeId(right);
5546 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005547 op = spv::OpMatrixTimesScalar;
5548 } else
5549 firstClass = false;
5550 break;
5551 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005552 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005553 std::swap(left, right);
5554 assert(builder.isScalar(right));
5555 break;
5556 case spv::OpVectorTimesMatrix:
5557 assert(builder.isVector(left));
5558 assert(builder.isMatrix(right));
5559 break;
5560 case spv::OpMatrixTimesVector:
5561 assert(builder.isMatrix(left));
5562 assert(builder.isVector(right));
5563 break;
5564 case spv::OpMatrixTimesMatrix:
5565 assert(builder.isMatrix(left));
5566 assert(builder.isMatrix(right));
5567 break;
5568 default:
5569 firstClass = false;
5570 break;
5571 }
5572
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005573 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5574 firstClass = true;
5575
qining25262b32016-05-06 17:25:16 -04005576 if (firstClass) {
5577 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005578 decorations.addNoContraction(builder, result);
5579 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005580 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005581 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005582
LoopDawg592860c2016-06-09 08:57:35 -06005583 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005584 // The result type of all of them is the same type as the (a) matrix operand.
5585 // The algorithm is to:
5586 // - break the matrix(es) into vectors
5587 // - smear any scalar to a vector
5588 // - do vector operations
5589 // - make a matrix out the vector results
5590 switch (op) {
5591 case spv::OpFAdd:
5592 case spv::OpFSub:
5593 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005594 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005595 case spv::OpFMul:
5596 {
5597 // one time set up...
5598 bool leftMat = builder.isMatrix(left);
5599 bool rightMat = builder.isMatrix(right);
5600 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5601 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5602 spv::Id scalarType = builder.getScalarTypeId(typeId);
5603 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5604 std::vector<spv::Id> results;
5605 spv::Id smearVec = spv::NoResult;
5606 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005607 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005608 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005609 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005610
5611 // do each vector op
5612 for (unsigned int c = 0; c < numCols; ++c) {
5613 std::vector<unsigned int> indexes;
5614 indexes.push_back(c);
5615 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5616 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005617 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005618 decorations.addNoContraction(builder, result);
5619 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005620 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005621 }
5622
5623 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005624 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005625 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005626 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005627 }
5628 default:
5629 assert(0);
5630 return spv::NoResult;
5631 }
5632}
5633
John Kessenichead86222018-03-28 18:01:20 -06005634spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005635 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005636{
5637 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005638 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005639 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005640 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5641 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005642
5643 switch (op) {
5644 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005645 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005646 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005647 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005648 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005649 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005650 unaryOp = spv::OpSNegate;
5651 break;
5652
5653 case glslang::EOpLogicalNot:
5654 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005655 unaryOp = spv::OpLogicalNot;
5656 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005657 case glslang::EOpBitwiseNot:
5658 unaryOp = spv::OpNot;
5659 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005660
John Kessenich140f3df2015-06-26 16:58:36 -06005661 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005662 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005663 break;
5664 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005665 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005666 break;
5667 case glslang::EOpTranspose:
5668 unaryOp = spv::OpTranspose;
5669 break;
5670
5671 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005672 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005673 break;
5674 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005675 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005676 break;
5677 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005678 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005679 break;
5680 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005681 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005682 break;
5683 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005684 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005685 break;
5686 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005687 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005688 break;
5689 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005690 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005691 break;
5692 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005693 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005694 break;
5695
5696 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005697 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005698 break;
5699 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005700 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005701 break;
5702 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005703 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005704 break;
5705 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005706 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005707 break;
5708 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005709 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005710 break;
5711 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005712 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005713 break;
5714
5715 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005716 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005717 break;
5718 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005719 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005720 break;
5721
5722 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005723 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005724 break;
5725 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005726 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005727 break;
5728 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005729 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005730 break;
5731 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005732 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005733 break;
5734 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005735 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005736 break;
5737 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005738 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005739 break;
5740
5741 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005742 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005743 break;
5744 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005745 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005746 break;
5747 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005748 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005749 break;
5750 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005751 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005752 break;
5753 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005754 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005755 break;
5756 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005757 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005758 break;
5759
5760 case glslang::EOpIsNan:
5761 unaryOp = spv::OpIsNan;
5762 break;
5763 case glslang::EOpIsInf:
5764 unaryOp = spv::OpIsInf;
5765 break;
LoopDawg592860c2016-06-09 08:57:35 -06005766 case glslang::EOpIsFinite:
5767 unaryOp = spv::OpIsFinite;
5768 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005769
Rex Xucbc426e2015-12-15 16:03:10 +08005770 case glslang::EOpFloatBitsToInt:
5771 case glslang::EOpFloatBitsToUint:
5772 case glslang::EOpIntBitsToFloat:
5773 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005774 case glslang::EOpDoubleBitsToInt64:
5775 case glslang::EOpDoubleBitsToUint64:
5776 case glslang::EOpInt64BitsToDouble:
5777 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005778 case glslang::EOpFloat16BitsToInt16:
5779 case glslang::EOpFloat16BitsToUint16:
5780 case glslang::EOpInt16BitsToFloat16:
5781 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005782 unaryOp = spv::OpBitcast;
5783 break;
5784
John Kessenich140f3df2015-06-26 16:58:36 -06005785 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005786 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005787 break;
5788 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005789 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005790 break;
5791 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005792 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005793 break;
5794 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005795 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005796 break;
5797 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005798 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005799 break;
5800 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005801 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005802 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005803#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005804 case glslang::EOpPackSnorm4x8:
5805 libCall = spv::GLSLstd450PackSnorm4x8;
5806 break;
5807 case glslang::EOpUnpackSnorm4x8:
5808 libCall = spv::GLSLstd450UnpackSnorm4x8;
5809 break;
5810 case glslang::EOpPackUnorm4x8:
5811 libCall = spv::GLSLstd450PackUnorm4x8;
5812 break;
5813 case glslang::EOpUnpackUnorm4x8:
5814 libCall = spv::GLSLstd450UnpackUnorm4x8;
5815 break;
5816 case glslang::EOpPackDouble2x32:
5817 libCall = spv::GLSLstd450PackDouble2x32;
5818 break;
5819 case glslang::EOpUnpackDouble2x32:
5820 libCall = spv::GLSLstd450UnpackDouble2x32;
5821 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005822#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005823
Rex Xu8ff43de2016-04-22 16:51:45 +08005824 case glslang::EOpPackInt2x32:
5825 case glslang::EOpUnpackInt2x32:
5826 case glslang::EOpPackUint2x32:
5827 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005828 case glslang::EOpPack16:
5829 case glslang::EOpPack32:
5830 case glslang::EOpPack64:
5831 case glslang::EOpUnpack32:
5832 case glslang::EOpUnpack16:
5833 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005834 case glslang::EOpPackInt2x16:
5835 case glslang::EOpUnpackInt2x16:
5836 case glslang::EOpPackUint2x16:
5837 case glslang::EOpUnpackUint2x16:
5838 case glslang::EOpPackInt4x16:
5839 case glslang::EOpUnpackInt4x16:
5840 case glslang::EOpPackUint4x16:
5841 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005842 case glslang::EOpPackFloat2x16:
5843 case glslang::EOpUnpackFloat2x16:
5844 unaryOp = spv::OpBitcast;
5845 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005846
John Kessenich140f3df2015-06-26 16:58:36 -06005847 case glslang::EOpDPdx:
5848 unaryOp = spv::OpDPdx;
5849 break;
5850 case glslang::EOpDPdy:
5851 unaryOp = spv::OpDPdy;
5852 break;
5853 case glslang::EOpFwidth:
5854 unaryOp = spv::OpFwidth;
5855 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005856
John Kessenich140f3df2015-06-26 16:58:36 -06005857 case glslang::EOpAny:
5858 unaryOp = spv::OpAny;
5859 break;
5860 case glslang::EOpAll:
5861 unaryOp = spv::OpAll;
5862 break;
5863
5864 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005865 if (isFloat)
5866 libCall = spv::GLSLstd450FAbs;
5867 else
5868 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005869 break;
5870 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005871 if (isFloat)
5872 libCall = spv::GLSLstd450FSign;
5873 else
5874 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005875 break;
5876
John Kessenicha28f7a72019-08-06 07:00:58 -06005877#ifndef GLSLANG_WEB
5878 case glslang::EOpDPdxFine:
5879 unaryOp = spv::OpDPdxFine;
5880 break;
5881 case glslang::EOpDPdyFine:
5882 unaryOp = spv::OpDPdyFine;
5883 break;
5884 case glslang::EOpFwidthFine:
5885 unaryOp = spv::OpFwidthFine;
5886 break;
5887 case glslang::EOpDPdxCoarse:
5888 unaryOp = spv::OpDPdxCoarse;
5889 break;
5890 case glslang::EOpDPdyCoarse:
5891 unaryOp = spv::OpDPdyCoarse;
5892 break;
5893 case glslang::EOpFwidthCoarse:
5894 unaryOp = spv::OpFwidthCoarse;
5895 break;
5896 case glslang::EOpInterpolateAtCentroid:
5897 if (typeProxy == glslang::EbtFloat16)
5898 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5899 libCall = spv::GLSLstd450InterpolateAtCentroid;
5900 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005901 case glslang::EOpAtomicCounterIncrement:
5902 case glslang::EOpAtomicCounterDecrement:
5903 case glslang::EOpAtomicCounter:
5904 {
5905 // Handle all of the atomics in one place, in createAtomicOperation()
5906 std::vector<spv::Id> operands;
5907 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005908 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005909 }
5910
John Kessenichfc51d282015-08-19 13:34:18 -06005911 case glslang::EOpBitFieldReverse:
5912 unaryOp = spv::OpBitReverse;
5913 break;
5914 case glslang::EOpBitCount:
5915 unaryOp = spv::OpBitCount;
5916 break;
5917 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005918 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005919 break;
5920 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005921 if (isUnsigned)
5922 libCall = spv::GLSLstd450FindUMsb;
5923 else
5924 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005925 break;
5926
Ian Romanickb3bd4022019-01-21 08:57:25 -08005927 case glslang::EOpCountLeadingZeros:
5928 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
5929 builder.addExtension("SPV_INTEL_shader_integer_functions2");
5930 unaryOp = spv::OpUCountLeadingZerosINTEL;
5931 break;
5932
5933 case glslang::EOpCountTrailingZeros:
5934 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
5935 builder.addExtension("SPV_INTEL_shader_integer_functions2");
5936 unaryOp = spv::OpUCountTrailingZerosINTEL;
5937 break;
5938
Rex Xu574ab042016-04-14 16:53:07 +08005939 case glslang::EOpBallot:
5940 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005941 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005942 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005943 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005944 case glslang::EOpMinInvocations:
5945 case glslang::EOpMaxInvocations:
5946 case glslang::EOpAddInvocations:
5947 case glslang::EOpMinInvocationsNonUniform:
5948 case glslang::EOpMaxInvocationsNonUniform:
5949 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005950 case glslang::EOpMinInvocationsInclusiveScan:
5951 case glslang::EOpMaxInvocationsInclusiveScan:
5952 case glslang::EOpAddInvocationsInclusiveScan:
5953 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5954 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5955 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5956 case glslang::EOpMinInvocationsExclusiveScan:
5957 case glslang::EOpMaxInvocationsExclusiveScan:
5958 case glslang::EOpAddInvocationsExclusiveScan:
5959 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5960 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5961 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08005962 {
5963 std::vector<spv::Id> operands;
5964 operands.push_back(operand);
5965 return createInvocationsOperation(op, typeId, operands, typeProxy);
5966 }
John Kessenich66011cb2018-03-06 16:12:04 -07005967 case glslang::EOpSubgroupAll:
5968 case glslang::EOpSubgroupAny:
5969 case glslang::EOpSubgroupAllEqual:
5970 case glslang::EOpSubgroupBroadcastFirst:
5971 case glslang::EOpSubgroupBallot:
5972 case glslang::EOpSubgroupInverseBallot:
5973 case glslang::EOpSubgroupBallotBitCount:
5974 case glslang::EOpSubgroupBallotInclusiveBitCount:
5975 case glslang::EOpSubgroupBallotExclusiveBitCount:
5976 case glslang::EOpSubgroupBallotFindLSB:
5977 case glslang::EOpSubgroupBallotFindMSB:
5978 case glslang::EOpSubgroupAdd:
5979 case glslang::EOpSubgroupMul:
5980 case glslang::EOpSubgroupMin:
5981 case glslang::EOpSubgroupMax:
5982 case glslang::EOpSubgroupAnd:
5983 case glslang::EOpSubgroupOr:
5984 case glslang::EOpSubgroupXor:
5985 case glslang::EOpSubgroupInclusiveAdd:
5986 case glslang::EOpSubgroupInclusiveMul:
5987 case glslang::EOpSubgroupInclusiveMin:
5988 case glslang::EOpSubgroupInclusiveMax:
5989 case glslang::EOpSubgroupInclusiveAnd:
5990 case glslang::EOpSubgroupInclusiveOr:
5991 case glslang::EOpSubgroupInclusiveXor:
5992 case glslang::EOpSubgroupExclusiveAdd:
5993 case glslang::EOpSubgroupExclusiveMul:
5994 case glslang::EOpSubgroupExclusiveMin:
5995 case glslang::EOpSubgroupExclusiveMax:
5996 case glslang::EOpSubgroupExclusiveAnd:
5997 case glslang::EOpSubgroupExclusiveOr:
5998 case glslang::EOpSubgroupExclusiveXor:
5999 case glslang::EOpSubgroupQuadSwapHorizontal:
6000 case glslang::EOpSubgroupQuadSwapVertical:
6001 case glslang::EOpSubgroupQuadSwapDiagonal: {
6002 std::vector<spv::Id> operands;
6003 operands.push_back(operand);
6004 return createSubgroupOperation(op, typeId, operands, typeProxy);
6005 }
Rex Xu9d93a232016-05-05 12:30:44 +08006006 case glslang::EOpMbcnt:
6007 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6008 libCall = spv::MbcntAMD;
6009 break;
6010
6011 case glslang::EOpCubeFaceIndex:
6012 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6013 libCall = spv::CubeFaceIndexAMD;
6014 break;
6015
6016 case glslang::EOpCubeFaceCoord:
6017 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6018 libCall = spv::CubeFaceCoordAMD;
6019 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006020 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006021 unaryOp = spv::OpGroupNonUniformPartitionNV;
6022 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006023 case glslang::EOpConstructReference:
6024 unaryOp = spv::OpBitcast;
6025 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006026#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006027
6028 case glslang::EOpCopyObject:
6029 unaryOp = spv::OpCopyObject;
6030 break;
6031
John Kessenich140f3df2015-06-26 16:58:36 -06006032 default:
6033 return 0;
6034 }
6035
6036 spv::Id id;
6037 if (libCall >= 0) {
6038 std::vector<spv::Id> args;
6039 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006040 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006041 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006042 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006043 }
John Kessenich140f3df2015-06-26 16:58:36 -06006044
John Kessenichb9197c82019-08-11 07:41:45 -06006045 decorations.addNoContraction(builder, id);
6046 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006047 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006048}
6049
John Kessenich7a53f762016-01-20 11:19:27 -07006050// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006051spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6052 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006053{
6054 // Handle unary operations vector by vector.
6055 // The result type is the same type as the original type.
6056 // The algorithm is to:
6057 // - break the matrix into vectors
6058 // - apply the operation to each vector
6059 // - make a matrix out the vector results
6060
6061 // get the types sorted out
6062 int numCols = builder.getNumColumns(operand);
6063 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006064 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6065 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006066 std::vector<spv::Id> results;
6067
6068 // do each vector op
6069 for (int c = 0; c < numCols; ++c) {
6070 std::vector<unsigned int> indexes;
6071 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006072 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6073 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006074 decorations.addNoContraction(builder, destVec);
6075 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006076 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006077 }
6078
6079 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006080 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006081 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006082 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006083}
6084
John Kessenichad7645f2018-06-04 19:11:25 -06006085// For converting integers where both the bitwidth and the signedness could
6086// change, but only do the width change here. The caller is still responsible
6087// for the signedness conversion.
6088spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006089{
John Kessenichad7645f2018-06-04 19:11:25 -06006090 // Get the result type width, based on the type to convert to.
6091 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006092 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006093 case glslang::EOpConvInt16ToUint8:
6094 case glslang::EOpConvIntToUint8:
6095 case glslang::EOpConvInt64ToUint8:
6096 case glslang::EOpConvUint16ToInt8:
6097 case glslang::EOpConvUintToInt8:
6098 case glslang::EOpConvUint64ToInt8:
6099 width = 8;
6100 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006101 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006102 case glslang::EOpConvIntToUint16:
6103 case glslang::EOpConvInt64ToUint16:
6104 case glslang::EOpConvUint8ToInt16:
6105 case glslang::EOpConvUintToInt16:
6106 case glslang::EOpConvUint64ToInt16:
6107 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006108 break;
6109 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006110 case glslang::EOpConvInt16ToUint:
6111 case glslang::EOpConvInt64ToUint:
6112 case glslang::EOpConvUint8ToInt:
6113 case glslang::EOpConvUint16ToInt:
6114 case glslang::EOpConvUint64ToInt:
6115 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006116 break;
6117 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006118 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006119 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006120 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006121 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006122 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006123 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006124 break;
6125
6126 default:
6127 assert(false && "Default missing");
6128 break;
6129 }
6130
John Kessenichad7645f2018-06-04 19:11:25 -06006131 // Get the conversion operation and result type,
6132 // based on the target width, but the source type.
6133 spv::Id type = spv::NoType;
6134 spv::Op convOp = spv::OpNop;
6135 switch(op) {
6136 case glslang::EOpConvInt8ToUint16:
6137 case glslang::EOpConvInt8ToUint:
6138 case glslang::EOpConvInt8ToUint64:
6139 case glslang::EOpConvInt16ToUint8:
6140 case glslang::EOpConvInt16ToUint:
6141 case glslang::EOpConvInt16ToUint64:
6142 case glslang::EOpConvIntToUint8:
6143 case glslang::EOpConvIntToUint16:
6144 case glslang::EOpConvIntToUint64:
6145 case glslang::EOpConvInt64ToUint8:
6146 case glslang::EOpConvInt64ToUint16:
6147 case glslang::EOpConvInt64ToUint:
6148 convOp = spv::OpSConvert;
6149 type = builder.makeIntType(width);
6150 break;
6151 default:
6152 convOp = spv::OpUConvert;
6153 type = builder.makeUintType(width);
6154 break;
6155 }
6156
John Kessenich66011cb2018-03-06 16:12:04 -07006157 if (vectorSize > 0)
6158 type = builder.makeVectorType(type, vectorSize);
6159
John Kessenichad7645f2018-06-04 19:11:25 -06006160 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006161}
6162
John Kessenichead86222018-03-28 18:01:20 -06006163spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6164 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006165{
6166 spv::Op convOp = spv::OpNop;
6167 spv::Id zero = 0;
6168 spv::Id one = 0;
6169
6170 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6171
6172 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006173 case glslang::EOpConvIntToBool:
6174 case glslang::EOpConvUintToBool:
6175 zero = builder.makeUintConstant(0);
6176 zero = makeSmearedConstant(zero, vectorSize);
6177 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006178 case glslang::EOpConvFloatToBool:
6179 zero = builder.makeFloatConstant(0.0F);
6180 zero = makeSmearedConstant(zero, vectorSize);
6181 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006182 case glslang::EOpConvBoolToFloat:
6183 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006184 zero = builder.makeFloatConstant(0.0F);
6185 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006186 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006187
John Kessenich140f3df2015-06-26 16:58:36 -06006188 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006189 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006190#ifndef GLSLANG_WEB
6191 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006192 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006193 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006194 } else
6195#endif
6196 {
6197 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006198 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006199 }
Rex Xucabbb782017-03-24 13:41:14 +08006200
John Kessenich140f3df2015-06-26 16:58:36 -06006201 convOp = spv::OpSelect;
6202 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006203
John Kessenich140f3df2015-06-26 16:58:36 -06006204 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006205 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006206#ifndef GLSLANG_WEB
6207 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006208 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006209 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006210 } else
6211#endif
6212 {
6213 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006214 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006215 }
Rex Xucabbb782017-03-24 13:41:14 +08006216
John Kessenich140f3df2015-06-26 16:58:36 -06006217 convOp = spv::OpSelect;
6218 break;
6219
John Kessenich66011cb2018-03-06 16:12:04 -07006220 case glslang::EOpConvInt8ToFloat16:
6221 case glslang::EOpConvInt8ToFloat:
6222 case glslang::EOpConvInt8ToDouble:
6223 case glslang::EOpConvInt16ToFloat16:
6224 case glslang::EOpConvInt16ToFloat:
6225 case glslang::EOpConvInt16ToDouble:
6226 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006227 case glslang::EOpConvIntToFloat:
6228 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006229 case glslang::EOpConvInt64ToFloat:
6230 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006231 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006232 convOp = spv::OpConvertSToF;
6233 break;
6234
John Kessenich66011cb2018-03-06 16:12:04 -07006235 case glslang::EOpConvUint8ToFloat16:
6236 case glslang::EOpConvUint8ToFloat:
6237 case glslang::EOpConvUint8ToDouble:
6238 case glslang::EOpConvUint16ToFloat16:
6239 case glslang::EOpConvUint16ToFloat:
6240 case glslang::EOpConvUint16ToDouble:
6241 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006242 case glslang::EOpConvUintToFloat:
6243 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006244 case glslang::EOpConvUint64ToFloat:
6245 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006246 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006247 convOp = spv::OpConvertUToF;
6248 break;
6249
John Kessenich66011cb2018-03-06 16:12:04 -07006250 case glslang::EOpConvFloat16ToInt8:
6251 case glslang::EOpConvFloatToInt8:
6252 case glslang::EOpConvDoubleToInt8:
6253 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006254 case glslang::EOpConvFloatToInt16:
6255 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006256 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006257 case glslang::EOpConvFloatToInt:
6258 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006259 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006260 case glslang::EOpConvFloatToInt64:
6261 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006262 convOp = spv::OpConvertFToS;
6263 break;
6264
John Kessenich66011cb2018-03-06 16:12:04 -07006265 case glslang::EOpConvUint8ToInt8:
6266 case glslang::EOpConvInt8ToUint8:
6267 case glslang::EOpConvUint16ToInt16:
6268 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006269 case glslang::EOpConvUintToInt:
6270 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006271 case glslang::EOpConvUint64ToInt64:
6272 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006273 if (builder.isInSpecConstCodeGenMode()) {
6274 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006275#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006276 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6277 zero = builder.makeUint8Constant(0);
6278 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006279 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006280 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6281 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006282 } else
6283#endif
6284 {
Rex Xucabbb782017-03-24 13:41:14 +08006285 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006286 }
qining189b2032016-04-12 23:16:20 -04006287 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006288 // Use OpIAdd, instead of OpBitcast to do the conversion when
6289 // generating for OpSpecConstantOp instruction.
6290 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6291 }
6292 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006293 convOp = spv::OpBitcast;
6294 break;
6295
John Kessenich66011cb2018-03-06 16:12:04 -07006296 case glslang::EOpConvFloat16ToUint8:
6297 case glslang::EOpConvFloatToUint8:
6298 case glslang::EOpConvDoubleToUint8:
6299 case glslang::EOpConvFloat16ToUint16:
6300 case glslang::EOpConvFloatToUint16:
6301 case glslang::EOpConvDoubleToUint16:
6302 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006303 case glslang::EOpConvFloatToUint:
6304 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006305 case glslang::EOpConvFloatToUint64:
6306 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006307 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006308 convOp = spv::OpConvertFToU;
6309 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006310
John Kessenich39697cd2019-08-08 10:35:51 -06006311#ifndef GLSLANG_WEB
6312 case glslang::EOpConvInt8ToBool:
6313 case glslang::EOpConvUint8ToBool:
6314 zero = builder.makeUint8Constant(0);
6315 zero = makeSmearedConstant(zero, vectorSize);
6316 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6317 case glslang::EOpConvInt16ToBool:
6318 case glslang::EOpConvUint16ToBool:
6319 zero = builder.makeUint16Constant(0);
6320 zero = makeSmearedConstant(zero, vectorSize);
6321 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6322 case glslang::EOpConvInt64ToBool:
6323 case glslang::EOpConvUint64ToBool:
6324 zero = builder.makeUint64Constant(0);
6325 zero = makeSmearedConstant(zero, vectorSize);
6326 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6327 case glslang::EOpConvDoubleToBool:
6328 zero = builder.makeDoubleConstant(0.0);
6329 zero = makeSmearedConstant(zero, vectorSize);
6330 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6331 case glslang::EOpConvFloat16ToBool:
6332 zero = builder.makeFloat16Constant(0.0F);
6333 zero = makeSmearedConstant(zero, vectorSize);
6334 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6335 case glslang::EOpConvBoolToDouble:
6336 convOp = spv::OpSelect;
6337 zero = builder.makeDoubleConstant(0.0);
6338 one = builder.makeDoubleConstant(1.0);
6339 break;
6340 case glslang::EOpConvBoolToFloat16:
6341 convOp = spv::OpSelect;
6342 zero = builder.makeFloat16Constant(0.0F);
6343 one = builder.makeFloat16Constant(1.0F);
6344 break;
6345 case glslang::EOpConvBoolToInt8:
6346 zero = builder.makeInt8Constant(0);
6347 one = builder.makeInt8Constant(1);
6348 convOp = spv::OpSelect;
6349 break;
6350 case glslang::EOpConvBoolToUint8:
6351 zero = builder.makeUint8Constant(0);
6352 one = builder.makeUint8Constant(1);
6353 convOp = spv::OpSelect;
6354 break;
6355 case glslang::EOpConvBoolToInt16:
6356 zero = builder.makeInt16Constant(0);
6357 one = builder.makeInt16Constant(1);
6358 convOp = spv::OpSelect;
6359 break;
6360 case glslang::EOpConvBoolToUint16:
6361 zero = builder.makeUint16Constant(0);
6362 one = builder.makeUint16Constant(1);
6363 convOp = spv::OpSelect;
6364 break;
6365 case glslang::EOpConvDoubleToFloat:
6366 case glslang::EOpConvFloatToDouble:
6367 case glslang::EOpConvDoubleToFloat16:
6368 case glslang::EOpConvFloat16ToDouble:
6369 case glslang::EOpConvFloatToFloat16:
6370 case glslang::EOpConvFloat16ToFloat:
6371 convOp = spv::OpFConvert;
6372 if (builder.isMatrixType(destType))
6373 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6374 break;
6375
John Kessenich66011cb2018-03-06 16:12:04 -07006376 case glslang::EOpConvInt8ToInt16:
6377 case glslang::EOpConvInt8ToInt:
6378 case glslang::EOpConvInt8ToInt64:
6379 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006380 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006381 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006382 case glslang::EOpConvIntToInt8:
6383 case glslang::EOpConvIntToInt16:
6384 case glslang::EOpConvIntToInt64:
6385 case glslang::EOpConvInt64ToInt8:
6386 case glslang::EOpConvInt64ToInt16:
6387 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006388 convOp = spv::OpSConvert;
6389 break;
6390
John Kessenich66011cb2018-03-06 16:12:04 -07006391 case glslang::EOpConvUint8ToUint16:
6392 case glslang::EOpConvUint8ToUint:
6393 case glslang::EOpConvUint8ToUint64:
6394 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006395 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006396 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006397 case glslang::EOpConvUintToUint8:
6398 case glslang::EOpConvUintToUint16:
6399 case glslang::EOpConvUintToUint64:
6400 case glslang::EOpConvUint64ToUint8:
6401 case glslang::EOpConvUint64ToUint16:
6402 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006403 convOp = spv::OpUConvert;
6404 break;
6405
John Kessenich66011cb2018-03-06 16:12:04 -07006406 case glslang::EOpConvInt8ToUint16:
6407 case glslang::EOpConvInt8ToUint:
6408 case glslang::EOpConvInt8ToUint64:
6409 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006410 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006411 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006412 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006413 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006414 case glslang::EOpConvIntToUint64:
6415 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006416 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006417 case glslang::EOpConvInt64ToUint:
6418 case glslang::EOpConvUint8ToInt16:
6419 case glslang::EOpConvUint8ToInt:
6420 case glslang::EOpConvUint8ToInt64:
6421 case glslang::EOpConvUint16ToInt8:
6422 case glslang::EOpConvUint16ToInt:
6423 case glslang::EOpConvUint16ToInt64:
6424 case glslang::EOpConvUintToInt8:
6425 case glslang::EOpConvUintToInt16:
6426 case glslang::EOpConvUintToInt64:
6427 case glslang::EOpConvUint64ToInt8:
6428 case glslang::EOpConvUint64ToInt16:
6429 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006430 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006431 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006432
6433 if (builder.isInSpecConstCodeGenMode()) {
6434 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006435 switch(op) {
6436 case glslang::EOpConvInt16ToUint8:
6437 case glslang::EOpConvIntToUint8:
6438 case glslang::EOpConvInt64ToUint8:
6439 case glslang::EOpConvUint16ToInt8:
6440 case glslang::EOpConvUintToInt8:
6441 case glslang::EOpConvUint64ToInt8:
6442 zero = builder.makeUint8Constant(0);
6443 break;
6444 case glslang::EOpConvInt8ToUint16:
6445 case glslang::EOpConvIntToUint16:
6446 case glslang::EOpConvInt64ToUint16:
6447 case glslang::EOpConvUint8ToInt16:
6448 case glslang::EOpConvUintToInt16:
6449 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006450 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006451 break;
6452 case glslang::EOpConvInt8ToUint:
6453 case glslang::EOpConvInt16ToUint:
6454 case glslang::EOpConvInt64ToUint:
6455 case glslang::EOpConvUint8ToInt:
6456 case glslang::EOpConvUint16ToInt:
6457 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006458 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006459 break;
6460 case glslang::EOpConvInt8ToUint64:
6461 case glslang::EOpConvInt16ToUint64:
6462 case glslang::EOpConvIntToUint64:
6463 case glslang::EOpConvUint8ToInt64:
6464 case glslang::EOpConvUint16ToInt64:
6465 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006466 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006467 break;
6468 default:
6469 assert(false && "Default missing");
6470 break;
6471 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006472 zero = makeSmearedConstant(zero, vectorSize);
6473 // Use OpIAdd, instead of OpBitcast to do the conversion when
6474 // generating for OpSpecConstantOp instruction.
6475 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6476 }
6477 // For normal run-time conversion instruction, use OpBitcast.
6478 convOp = spv::OpBitcast;
6479 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006480 case glslang::EOpConvUint64ToPtr:
6481 convOp = spv::OpConvertUToPtr;
6482 break;
6483 case glslang::EOpConvPtrToUint64:
6484 convOp = spv::OpConvertPtrToU;
6485 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006486 case glslang::EOpConvPtrToUvec2:
6487 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006488 if (builder.isVector(operand))
6489 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6490 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006491 convOp = spv::OpBitcast;
6492 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006493#endif
6494
John Kessenich140f3df2015-06-26 16:58:36 -06006495 default:
6496 break;
6497 }
6498
6499 spv::Id result = 0;
6500 if (convOp == spv::OpNop)
6501 return result;
6502
6503 if (convOp == spv::OpSelect) {
6504 zero = makeSmearedConstant(zero, vectorSize);
6505 one = makeSmearedConstant(one, vectorSize);
6506 result = builder.createTriOp(convOp, destType, operand, one, zero);
6507 } else
6508 result = builder.createUnaryOp(convOp, destType, operand);
6509
John Kessenichead86222018-03-28 18:01:20 -06006510 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006511 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006512 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006513}
6514
6515spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6516{
6517 if (vectorSize == 0)
6518 return constant;
6519
6520 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6521 std::vector<spv::Id> components;
6522 for (int c = 0; c < vectorSize; ++c)
6523 components.push_back(constant);
6524 return builder.makeCompositeConstant(vectorTypeId, components);
6525}
6526
John Kessenich426394d2015-07-23 10:22:48 -06006527// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006528spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6529 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6530 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006531{
6532 spv::Op opCode = spv::OpNop;
6533
6534 switch (op) {
6535 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006536 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006537 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006538 opCode = spv::OpAtomicIAdd;
6539 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006540 case glslang::EOpAtomicCounterSubtract:
6541 opCode = spv::OpAtomicISub;
6542 break;
John Kessenich426394d2015-07-23 10:22:48 -06006543 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006544 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006545 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006546 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6547 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006548 break;
6549 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006550 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006551 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006552 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6553 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006554 break;
6555 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006556 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006557 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006558 opCode = spv::OpAtomicAnd;
6559 break;
6560 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006561 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006562 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006563 opCode = spv::OpAtomicOr;
6564 break;
6565 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006566 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006567 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006568 opCode = spv::OpAtomicXor;
6569 break;
6570 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006571 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006572 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006573 opCode = spv::OpAtomicExchange;
6574 break;
6575 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006576 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006577 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006578 opCode = spv::OpAtomicCompareExchange;
6579 break;
6580 case glslang::EOpAtomicCounterIncrement:
6581 opCode = spv::OpAtomicIIncrement;
6582 break;
6583 case glslang::EOpAtomicCounterDecrement:
6584 opCode = spv::OpAtomicIDecrement;
6585 break;
6586 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006587 case glslang::EOpImageAtomicLoad:
6588 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006589 opCode = spv::OpAtomicLoad;
6590 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006591 case glslang::EOpAtomicStore:
6592 case glslang::EOpImageAtomicStore:
6593 opCode = spv::OpAtomicStore;
6594 break;
John Kessenich426394d2015-07-23 10:22:48 -06006595 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006596 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006597 break;
6598 }
6599
Rex Xue8fe8b02017-09-26 15:42:56 +08006600 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6601 builder.addCapability(spv::CapabilityInt64Atomics);
6602
John Kessenich426394d2015-07-23 10:22:48 -06006603 // Sort out the operands
6604 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006605 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006606 // - compare-exchange swaps the value and comparator
6607 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006608 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006609 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6610 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6611 spv::Id scopeId;
6612 if (glslangIntermediate->usingVulkanMemoryModel()) {
6613 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6614 } else {
6615 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6616 }
6617 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006618 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6619 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006620 spv::MemorySemanticsVolatileMask :
6621 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006622 spv::Id semanticsId2 = semanticsId;
6623
6624 pointerId = operands[0];
6625 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6626 // no additional operands
6627 } else if (opCode == spv::OpAtomicCompareExchange) {
6628 compareId = operands[1];
6629 valueId = operands[2];
6630 if (operands.size() > 3) {
6631 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006632 semanticsId = builder.makeUintConstant(
6633 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6634 semanticsId2 = builder.makeUintConstant(
6635 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006636 }
6637 } else if (opCode == spv::OpAtomicLoad) {
6638 if (operands.size() > 1) {
6639 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006640 semanticsId = builder.makeUintConstant(
6641 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006642 }
6643 } else {
6644 // atomic store or RMW
6645 valueId = operands[1];
6646 if (operands.size() > 2) {
6647 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006648 semanticsId = builder.makeUintConstant
6649 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006650 }
Rex Xu04db3f52015-09-16 11:44:02 +08006651 }
John Kessenich426394d2015-07-23 10:22:48 -06006652
Jeff Bolz36831c92018-09-05 10:11:41 -05006653 // Check for capabilities
6654 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006655 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6656 spv::MemorySemanticsMakeVisibleKHRMask |
6657 spv::MemorySemanticsOutputMemoryKHRMask |
6658 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006659 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6660 }
John Kessenich426394d2015-07-23 10:22:48 -06006661
Jeff Bolz36831c92018-09-05 10:11:41 -05006662 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6663 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6664 }
John Kessenich48d6e792017-10-06 21:21:48 -06006665
Jeff Bolz36831c92018-09-05 10:11:41 -05006666 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6667 spvAtomicOperands.push_back(pointerId);
6668 spvAtomicOperands.push_back(scopeId);
6669 spvAtomicOperands.push_back(semanticsId);
6670 if (opCode == spv::OpAtomicCompareExchange) {
6671 spvAtomicOperands.push_back(semanticsId2);
6672 spvAtomicOperands.push_back(valueId);
6673 spvAtomicOperands.push_back(compareId);
6674 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6675 spvAtomicOperands.push_back(valueId);
6676 }
John Kessenich48d6e792017-10-06 21:21:48 -06006677
Jeff Bolz36831c92018-09-05 10:11:41 -05006678 if (opCode == spv::OpAtomicStore) {
6679 builder.createNoResultOp(opCode, spvAtomicOperands);
6680 return 0;
6681 } else {
6682 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6683
6684 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6685 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6686 if (op == glslang::EOpAtomicCounterDecrement)
6687 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6688
6689 return resultId;
6690 }
John Kessenich426394d2015-07-23 10:22:48 -06006691}
6692
John Kessenich91cef522016-05-05 16:45:40 -06006693// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07006694spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
6695 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006696{
John Kessenich66011cb2018-03-06 16:12:04 -07006697 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6698 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006699
Rex Xu51596642016-09-21 18:56:12 +08006700 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006701 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006702 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6703
chaocf200da82016-12-20 12:44:35 -08006704 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6705 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006706 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6707 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006708 } else if (op == glslang::EOpAnyInvocation ||
6709 op == glslang::EOpAllInvocations ||
6710 op == glslang::EOpAllInvocationsEqual) {
6711 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6712 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006713 } else {
6714 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006715 if (op == glslang::EOpMinInvocationsNonUniform ||
6716 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006717 op == glslang::EOpAddInvocationsNonUniform ||
6718 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6719 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6720 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6721 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6722 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6723 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006724 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006725
Rex Xu430ef402016-10-14 17:22:23 +08006726 switch (op) {
6727 case glslang::EOpMinInvocations:
6728 case glslang::EOpMaxInvocations:
6729 case glslang::EOpAddInvocations:
6730 case glslang::EOpMinInvocationsNonUniform:
6731 case glslang::EOpMaxInvocationsNonUniform:
6732 case glslang::EOpAddInvocationsNonUniform:
6733 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006734 break;
6735 case glslang::EOpMinInvocationsInclusiveScan:
6736 case glslang::EOpMaxInvocationsInclusiveScan:
6737 case glslang::EOpAddInvocationsInclusiveScan:
6738 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6739 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6740 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6741 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006742 break;
6743 case glslang::EOpMinInvocationsExclusiveScan:
6744 case glslang::EOpMaxInvocationsExclusiveScan:
6745 case glslang::EOpAddInvocationsExclusiveScan:
6746 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6747 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6748 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6749 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006750 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006751 default:
6752 break;
Rex Xu430ef402016-10-14 17:22:23 +08006753 }
John Kessenich149afc32018-08-14 13:31:43 -06006754 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6755 spvGroupOperands.push_back(scope);
6756 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006757 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006758 spvGroupOperands.push_back(groupOp);
6759 }
Rex Xu51596642016-09-21 18:56:12 +08006760 }
6761
John Kessenich149afc32018-08-14 13:31:43 -06006762 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6763 spv::IdImmediate op = { true, *opIt };
6764 spvGroupOperands.push_back(op);
6765 }
John Kessenich91cef522016-05-05 16:45:40 -06006766
6767 switch (op) {
6768 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006769 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006770 break;
John Kessenich91cef522016-05-05 16:45:40 -06006771 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006772 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006773 break;
John Kessenich91cef522016-05-05 16:45:40 -06006774 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006775 opCode = spv::OpSubgroupAllEqualKHR;
6776 break;
Rex Xu51596642016-09-21 18:56:12 +08006777 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006778 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006779 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006780 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006781 break;
6782 case glslang::EOpReadFirstInvocation:
6783 opCode = spv::OpSubgroupFirstInvocationKHR;
6784 break;
6785 case glslang::EOpBallot:
6786 {
6787 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6788 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6789 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6790 //
6791 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6792 //
6793 spv::Id uintType = builder.makeUintType(32);
6794 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6795 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6796
6797 std::vector<spv::Id> components;
6798 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6799 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6800
6801 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6802 return builder.createUnaryOp(spv::OpBitcast, typeId,
6803 builder.createCompositeConstruct(uvec2Type, components));
6804 }
6805
Rex Xu9d93a232016-05-05 12:30:44 +08006806 case glslang::EOpMinInvocations:
6807 case glslang::EOpMaxInvocations:
6808 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006809 case glslang::EOpMinInvocationsInclusiveScan:
6810 case glslang::EOpMaxInvocationsInclusiveScan:
6811 case glslang::EOpAddInvocationsInclusiveScan:
6812 case glslang::EOpMinInvocationsExclusiveScan:
6813 case glslang::EOpMaxInvocationsExclusiveScan:
6814 case glslang::EOpAddInvocationsExclusiveScan:
6815 if (op == glslang::EOpMinInvocations ||
6816 op == glslang::EOpMinInvocationsInclusiveScan ||
6817 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006818 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006819 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006820 else {
6821 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006822 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006823 else
Rex Xu51596642016-09-21 18:56:12 +08006824 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006825 }
Rex Xu430ef402016-10-14 17:22:23 +08006826 } else if (op == glslang::EOpMaxInvocations ||
6827 op == glslang::EOpMaxInvocationsInclusiveScan ||
6828 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006829 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006830 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006831 else {
6832 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006833 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006834 else
Rex Xu51596642016-09-21 18:56:12 +08006835 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006836 }
6837 } else {
6838 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006839 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006840 else
Rex Xu51596642016-09-21 18:56:12 +08006841 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006842 }
6843
Rex Xu2bbbe062016-08-23 15:41:05 +08006844 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006845 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006846
6847 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006848 case glslang::EOpMinInvocationsNonUniform:
6849 case glslang::EOpMaxInvocationsNonUniform:
6850 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006851 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6852 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6853 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6854 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6855 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6856 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6857 if (op == glslang::EOpMinInvocationsNonUniform ||
6858 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6859 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006860 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006861 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006862 else {
6863 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006864 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006865 else
Rex Xu51596642016-09-21 18:56:12 +08006866 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006867 }
6868 }
Rex Xu430ef402016-10-14 17:22:23 +08006869 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6870 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6871 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006872 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006873 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006874 else {
6875 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006876 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006877 else
Rex Xu51596642016-09-21 18:56:12 +08006878 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006879 }
6880 }
6881 else {
6882 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006883 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006884 else
Rex Xu51596642016-09-21 18:56:12 +08006885 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006886 }
6887
Rex Xu2bbbe062016-08-23 15:41:05 +08006888 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006889 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006890
6891 break;
John Kessenich91cef522016-05-05 16:45:40 -06006892 default:
6893 logger->missingFunctionality("invocation operation");
6894 return spv::NoResult;
6895 }
Rex Xu51596642016-09-21 18:56:12 +08006896
6897 assert(opCode != spv::OpNop);
6898 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006899}
6900
Rex Xu2bbbe062016-08-23 15:41:05 +08006901// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006902spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6903 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006904{
6905 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6906 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006907 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006908 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07006909 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
6910 op == spv::OpGroupSMinNonUniformAMD ||
6911 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
6912 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006913 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
6914
6915 // Handle group invocation operations scalar by scalar.
6916 // The result type is the same type as the original type.
6917 // The algorithm is to:
6918 // - break the vector into scalars
6919 // - apply the operation to each scalar
6920 // - make a vector out the scalar results
6921
6922 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006923 int numComponents = builder.getNumComponents(operands[0]);
6924 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006925 std::vector<spv::Id> results;
6926
6927 // do each scalar op
6928 for (int comp = 0; comp < numComponents; ++comp) {
6929 std::vector<unsigned int> indexes;
6930 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006931 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6932 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006933 if (op == spv::OpSubgroupReadInvocationKHR) {
6934 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006935 spv::IdImmediate operand = { true, operands[1] };
6936 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006937 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006938 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6939 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006940 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006941 spv::IdImmediate operand = { true, operands[1] };
6942 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006943 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006944 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6945 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006946 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006947 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006948 spvGroupOperands.push_back(scalar);
6949 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006950
Rex Xub7072052016-09-26 15:53:40 +08006951 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006952 }
6953
6954 // put the pieces together
6955 return builder.createCompositeConstruct(typeId, results);
6956}
Rex Xu2bbbe062016-08-23 15:41:05 +08006957
John Kessenich66011cb2018-03-06 16:12:04 -07006958// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006959spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6960 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006961{
6962 // Add the required capabilities.
6963 switch (op) {
6964 case glslang::EOpSubgroupElect:
6965 builder.addCapability(spv::CapabilityGroupNonUniform);
6966 break;
6967 case glslang::EOpSubgroupAll:
6968 case glslang::EOpSubgroupAny:
6969 case glslang::EOpSubgroupAllEqual:
6970 builder.addCapability(spv::CapabilityGroupNonUniform);
6971 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6972 break;
6973 case glslang::EOpSubgroupBroadcast:
6974 case glslang::EOpSubgroupBroadcastFirst:
6975 case glslang::EOpSubgroupBallot:
6976 case glslang::EOpSubgroupInverseBallot:
6977 case glslang::EOpSubgroupBallotBitExtract:
6978 case glslang::EOpSubgroupBallotBitCount:
6979 case glslang::EOpSubgroupBallotInclusiveBitCount:
6980 case glslang::EOpSubgroupBallotExclusiveBitCount:
6981 case glslang::EOpSubgroupBallotFindLSB:
6982 case glslang::EOpSubgroupBallotFindMSB:
6983 builder.addCapability(spv::CapabilityGroupNonUniform);
6984 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6985 break;
6986 case glslang::EOpSubgroupShuffle:
6987 case glslang::EOpSubgroupShuffleXor:
6988 builder.addCapability(spv::CapabilityGroupNonUniform);
6989 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6990 break;
6991 case glslang::EOpSubgroupShuffleUp:
6992 case glslang::EOpSubgroupShuffleDown:
6993 builder.addCapability(spv::CapabilityGroupNonUniform);
6994 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6995 break;
6996 case glslang::EOpSubgroupAdd:
6997 case glslang::EOpSubgroupMul:
6998 case glslang::EOpSubgroupMin:
6999 case glslang::EOpSubgroupMax:
7000 case glslang::EOpSubgroupAnd:
7001 case glslang::EOpSubgroupOr:
7002 case glslang::EOpSubgroupXor:
7003 case glslang::EOpSubgroupInclusiveAdd:
7004 case glslang::EOpSubgroupInclusiveMul:
7005 case glslang::EOpSubgroupInclusiveMin:
7006 case glslang::EOpSubgroupInclusiveMax:
7007 case glslang::EOpSubgroupInclusiveAnd:
7008 case glslang::EOpSubgroupInclusiveOr:
7009 case glslang::EOpSubgroupInclusiveXor:
7010 case glslang::EOpSubgroupExclusiveAdd:
7011 case glslang::EOpSubgroupExclusiveMul:
7012 case glslang::EOpSubgroupExclusiveMin:
7013 case glslang::EOpSubgroupExclusiveMax:
7014 case glslang::EOpSubgroupExclusiveAnd:
7015 case glslang::EOpSubgroupExclusiveOr:
7016 case glslang::EOpSubgroupExclusiveXor:
7017 builder.addCapability(spv::CapabilityGroupNonUniform);
7018 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
7019 break;
7020 case glslang::EOpSubgroupClusteredAdd:
7021 case glslang::EOpSubgroupClusteredMul:
7022 case glslang::EOpSubgroupClusteredMin:
7023 case glslang::EOpSubgroupClusteredMax:
7024 case glslang::EOpSubgroupClusteredAnd:
7025 case glslang::EOpSubgroupClusteredOr:
7026 case glslang::EOpSubgroupClusteredXor:
7027 builder.addCapability(spv::CapabilityGroupNonUniform);
7028 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7029 break;
7030 case glslang::EOpSubgroupQuadBroadcast:
7031 case glslang::EOpSubgroupQuadSwapHorizontal:
7032 case glslang::EOpSubgroupQuadSwapVertical:
7033 case glslang::EOpSubgroupQuadSwapDiagonal:
7034 builder.addCapability(spv::CapabilityGroupNonUniform);
7035 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7036 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007037 case glslang::EOpSubgroupPartitionedAdd:
7038 case glslang::EOpSubgroupPartitionedMul:
7039 case glslang::EOpSubgroupPartitionedMin:
7040 case glslang::EOpSubgroupPartitionedMax:
7041 case glslang::EOpSubgroupPartitionedAnd:
7042 case glslang::EOpSubgroupPartitionedOr:
7043 case glslang::EOpSubgroupPartitionedXor:
7044 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7045 case glslang::EOpSubgroupPartitionedInclusiveMul:
7046 case glslang::EOpSubgroupPartitionedInclusiveMin:
7047 case glslang::EOpSubgroupPartitionedInclusiveMax:
7048 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7049 case glslang::EOpSubgroupPartitionedInclusiveOr:
7050 case glslang::EOpSubgroupPartitionedInclusiveXor:
7051 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7052 case glslang::EOpSubgroupPartitionedExclusiveMul:
7053 case glslang::EOpSubgroupPartitionedExclusiveMin:
7054 case glslang::EOpSubgroupPartitionedExclusiveMax:
7055 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7056 case glslang::EOpSubgroupPartitionedExclusiveOr:
7057 case glslang::EOpSubgroupPartitionedExclusiveXor:
7058 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7059 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7060 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007061 default: assert(0 && "Unhandled subgroup operation!");
7062 }
7063
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007064
7065 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7066 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007067 const bool isBool = typeProxy == glslang::EbtBool;
7068
7069 spv::Op opCode = spv::OpNop;
7070
7071 // Figure out which opcode to use.
7072 switch (op) {
7073 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7074 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7075 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7076 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7077 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7078 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7079 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7080 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7081 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7082 case glslang::EOpSubgroupBallotBitCount:
7083 case glslang::EOpSubgroupBallotInclusiveBitCount:
7084 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7085 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7086 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7087 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7088 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7089 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7090 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7091 case glslang::EOpSubgroupAdd:
7092 case glslang::EOpSubgroupInclusiveAdd:
7093 case glslang::EOpSubgroupExclusiveAdd:
7094 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007095 case glslang::EOpSubgroupPartitionedAdd:
7096 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7097 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007098 if (isFloat) {
7099 opCode = spv::OpGroupNonUniformFAdd;
7100 } else {
7101 opCode = spv::OpGroupNonUniformIAdd;
7102 }
7103 break;
7104 case glslang::EOpSubgroupMul:
7105 case glslang::EOpSubgroupInclusiveMul:
7106 case glslang::EOpSubgroupExclusiveMul:
7107 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007108 case glslang::EOpSubgroupPartitionedMul:
7109 case glslang::EOpSubgroupPartitionedInclusiveMul:
7110 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007111 if (isFloat) {
7112 opCode = spv::OpGroupNonUniformFMul;
7113 } else {
7114 opCode = spv::OpGroupNonUniformIMul;
7115 }
7116 break;
7117 case glslang::EOpSubgroupMin:
7118 case glslang::EOpSubgroupInclusiveMin:
7119 case glslang::EOpSubgroupExclusiveMin:
7120 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007121 case glslang::EOpSubgroupPartitionedMin:
7122 case glslang::EOpSubgroupPartitionedInclusiveMin:
7123 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007124 if (isFloat) {
7125 opCode = spv::OpGroupNonUniformFMin;
7126 } else if (isUnsigned) {
7127 opCode = spv::OpGroupNonUniformUMin;
7128 } else {
7129 opCode = spv::OpGroupNonUniformSMin;
7130 }
7131 break;
7132 case glslang::EOpSubgroupMax:
7133 case glslang::EOpSubgroupInclusiveMax:
7134 case glslang::EOpSubgroupExclusiveMax:
7135 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007136 case glslang::EOpSubgroupPartitionedMax:
7137 case glslang::EOpSubgroupPartitionedInclusiveMax:
7138 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007139 if (isFloat) {
7140 opCode = spv::OpGroupNonUniformFMax;
7141 } else if (isUnsigned) {
7142 opCode = spv::OpGroupNonUniformUMax;
7143 } else {
7144 opCode = spv::OpGroupNonUniformSMax;
7145 }
7146 break;
7147 case glslang::EOpSubgroupAnd:
7148 case glslang::EOpSubgroupInclusiveAnd:
7149 case glslang::EOpSubgroupExclusiveAnd:
7150 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007151 case glslang::EOpSubgroupPartitionedAnd:
7152 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7153 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007154 if (isBool) {
7155 opCode = spv::OpGroupNonUniformLogicalAnd;
7156 } else {
7157 opCode = spv::OpGroupNonUniformBitwiseAnd;
7158 }
7159 break;
7160 case glslang::EOpSubgroupOr:
7161 case glslang::EOpSubgroupInclusiveOr:
7162 case glslang::EOpSubgroupExclusiveOr:
7163 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007164 case glslang::EOpSubgroupPartitionedOr:
7165 case glslang::EOpSubgroupPartitionedInclusiveOr:
7166 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007167 if (isBool) {
7168 opCode = spv::OpGroupNonUniformLogicalOr;
7169 } else {
7170 opCode = spv::OpGroupNonUniformBitwiseOr;
7171 }
7172 break;
7173 case glslang::EOpSubgroupXor:
7174 case glslang::EOpSubgroupInclusiveXor:
7175 case glslang::EOpSubgroupExclusiveXor:
7176 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007177 case glslang::EOpSubgroupPartitionedXor:
7178 case glslang::EOpSubgroupPartitionedInclusiveXor:
7179 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007180 if (isBool) {
7181 opCode = spv::OpGroupNonUniformLogicalXor;
7182 } else {
7183 opCode = spv::OpGroupNonUniformBitwiseXor;
7184 }
7185 break;
7186 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7187 case glslang::EOpSubgroupQuadSwapHorizontal:
7188 case glslang::EOpSubgroupQuadSwapVertical:
7189 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7190 default: assert(0 && "Unhandled subgroup operation!");
7191 }
7192
John Kessenich149afc32018-08-14 13:31:43 -06007193 // get the right Group Operation
7194 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007195 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007196 default:
7197 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007198 case glslang::EOpSubgroupBallotBitCount:
7199 case glslang::EOpSubgroupAdd:
7200 case glslang::EOpSubgroupMul:
7201 case glslang::EOpSubgroupMin:
7202 case glslang::EOpSubgroupMax:
7203 case glslang::EOpSubgroupAnd:
7204 case glslang::EOpSubgroupOr:
7205 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007206 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007207 break;
7208 case glslang::EOpSubgroupBallotInclusiveBitCount:
7209 case glslang::EOpSubgroupInclusiveAdd:
7210 case glslang::EOpSubgroupInclusiveMul:
7211 case glslang::EOpSubgroupInclusiveMin:
7212 case glslang::EOpSubgroupInclusiveMax:
7213 case glslang::EOpSubgroupInclusiveAnd:
7214 case glslang::EOpSubgroupInclusiveOr:
7215 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007216 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007217 break;
7218 case glslang::EOpSubgroupBallotExclusiveBitCount:
7219 case glslang::EOpSubgroupExclusiveAdd:
7220 case glslang::EOpSubgroupExclusiveMul:
7221 case glslang::EOpSubgroupExclusiveMin:
7222 case glslang::EOpSubgroupExclusiveMax:
7223 case glslang::EOpSubgroupExclusiveAnd:
7224 case glslang::EOpSubgroupExclusiveOr:
7225 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007226 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007227 break;
7228 case glslang::EOpSubgroupClusteredAdd:
7229 case glslang::EOpSubgroupClusteredMul:
7230 case glslang::EOpSubgroupClusteredMin:
7231 case glslang::EOpSubgroupClusteredMax:
7232 case glslang::EOpSubgroupClusteredAnd:
7233 case glslang::EOpSubgroupClusteredOr:
7234 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007235 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007236 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007237 case glslang::EOpSubgroupPartitionedAdd:
7238 case glslang::EOpSubgroupPartitionedMul:
7239 case glslang::EOpSubgroupPartitionedMin:
7240 case glslang::EOpSubgroupPartitionedMax:
7241 case glslang::EOpSubgroupPartitionedAnd:
7242 case glslang::EOpSubgroupPartitionedOr:
7243 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007244 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007245 break;
7246 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7247 case glslang::EOpSubgroupPartitionedInclusiveMul:
7248 case glslang::EOpSubgroupPartitionedInclusiveMin:
7249 case glslang::EOpSubgroupPartitionedInclusiveMax:
7250 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7251 case glslang::EOpSubgroupPartitionedInclusiveOr:
7252 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007253 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007254 break;
7255 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7256 case glslang::EOpSubgroupPartitionedExclusiveMul:
7257 case glslang::EOpSubgroupPartitionedExclusiveMin:
7258 case glslang::EOpSubgroupPartitionedExclusiveMax:
7259 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7260 case glslang::EOpSubgroupPartitionedExclusiveOr:
7261 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007262 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007263 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007264 }
7265
John Kessenich149afc32018-08-14 13:31:43 -06007266 // build the instruction
7267 std::vector<spv::IdImmediate> spvGroupOperands;
7268
7269 // Every operation begins with the Execution Scope operand.
7270 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7271 spvGroupOperands.push_back(executionScope);
7272
7273 // Next, for all operations that use a Group Operation, push that as an operand.
7274 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007275 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007276 spvGroupOperands.push_back(groupOperand);
7277 }
7278
John Kessenich66011cb2018-03-06 16:12:04 -07007279 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007280 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7281 spv::IdImmediate operand = { true, *opIt };
7282 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007283 }
7284
7285 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007286 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007287 switch (op) {
7288 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007289 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7290 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7291 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7292 }
7293 if (directionId != spv::NoResult) {
7294 spv::IdImmediate direction = { true, directionId };
7295 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007296 }
7297
7298 return builder.createOp(opCode, typeId, spvGroupOperands);
7299}
7300
John Kessenich8985fc92020-03-03 10:25:07 -07007301spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7302 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007303{
John Kessenich66011cb2018-03-06 16:12:04 -07007304 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7305 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007306
John Kessenich140f3df2015-06-26 16:58:36 -06007307 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007308 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007309 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007310 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007311 spv::Id typeId0 = 0;
7312 if (consumedOperands > 0)
7313 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007314 spv::Id typeId1 = 0;
7315 if (consumedOperands > 1)
7316 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007317 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007318
7319 switch (op) {
7320 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007321 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007322 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007323 else if (isUnsigned)
7324 libCall = spv::GLSLstd450UMin;
7325 else
7326 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007327 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007328 break;
7329 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007330 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007331 break;
7332 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007333 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007334 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007335 else if (isUnsigned)
7336 libCall = spv::GLSLstd450UMax;
7337 else
7338 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007339 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007340 break;
7341 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007342 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007343 break;
7344 case glslang::EOpDot:
7345 opCode = spv::OpDot;
7346 break;
7347 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007348 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007349 break;
7350
7351 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007352 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007353 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007354 else if (isUnsigned)
7355 libCall = spv::GLSLstd450UClamp;
7356 else
7357 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007358 builder.promoteScalar(precision, operands.front(), operands[1]);
7359 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007360 break;
7361 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007362 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7363 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007364 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007365 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007366 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007367 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007368 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007369 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007370 break;
7371 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007372 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007373 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007374 break;
7375 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007376 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007377 builder.promoteScalar(precision, operands[0], operands[2]);
7378 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007379 break;
7380
7381 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007382 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007383 break;
7384 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007385 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007386 break;
7387 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007388 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007389 break;
7390 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007391 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007392 break;
7393 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007394 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007395 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007396 case glslang::EOpBarrier:
7397 {
7398 // This is for the extended controlBarrier function, with four operands.
7399 // The unextended barrier() goes through createNoArgOperation.
7400 assert(operands.size() == 4);
7401 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7402 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7403 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007404 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7405 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007406 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7407 spv::MemorySemanticsMakeVisibleKHRMask |
7408 spv::MemorySemanticsOutputMemoryKHRMask |
7409 spv::MemorySemanticsVolatileMask)) {
7410 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7411 }
John Kessenich8985fc92020-03-03 10:25:07 -07007412 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7413 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007414 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7415 }
7416 return 0;
7417 }
7418 break;
7419 case glslang::EOpMemoryBarrier:
7420 {
7421 // This is for the extended memoryBarrier function, with three operands.
7422 // The unextended memoryBarrier() goes through createNoArgOperation.
7423 assert(operands.size() == 3);
7424 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7425 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7426 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7427 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7428 spv::MemorySemanticsMakeVisibleKHRMask |
7429 spv::MemorySemanticsOutputMemoryKHRMask |
7430 spv::MemorySemanticsVolatileMask)) {
7431 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7432 }
7433 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7434 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7435 }
7436 return 0;
7437 }
7438 break;
7439
John Kessenicha28f7a72019-08-06 07:00:58 -06007440#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007441 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007442 if (typeProxy == glslang::EbtFloat16)
7443 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007444 libCall = spv::GLSLstd450InterpolateAtSample;
7445 break;
7446 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007447 if (typeProxy == glslang::EbtFloat16)
7448 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007449 libCall = spv::GLSLstd450InterpolateAtOffset;
7450 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007451 case glslang::EOpAddCarry:
7452 opCode = spv::OpIAddCarry;
7453 typeId = builder.makeStructResultType(typeId0, typeId0);
7454 consumedOperands = 2;
7455 break;
7456 case glslang::EOpSubBorrow:
7457 opCode = spv::OpISubBorrow;
7458 typeId = builder.makeStructResultType(typeId0, typeId0);
7459 consumedOperands = 2;
7460 break;
7461 case glslang::EOpUMulExtended:
7462 opCode = spv::OpUMulExtended;
7463 typeId = builder.makeStructResultType(typeId0, typeId0);
7464 consumedOperands = 2;
7465 break;
7466 case glslang::EOpIMulExtended:
7467 opCode = spv::OpSMulExtended;
7468 typeId = builder.makeStructResultType(typeId0, typeId0);
7469 consumedOperands = 2;
7470 break;
7471 case glslang::EOpBitfieldExtract:
7472 if (isUnsigned)
7473 opCode = spv::OpBitFieldUExtract;
7474 else
7475 opCode = spv::OpBitFieldSExtract;
7476 break;
7477 case glslang::EOpBitfieldInsert:
7478 opCode = spv::OpBitFieldInsert;
7479 break;
7480
7481 case glslang::EOpFma:
7482 libCall = spv::GLSLstd450Fma;
7483 break;
7484 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007485 {
7486 libCall = spv::GLSLstd450FrexpStruct;
7487 assert(builder.isPointerType(typeId1));
7488 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007489 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007490 if (width == 16)
7491 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7492 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007493 if (builder.getNumComponents(operands[0]) == 1)
7494 frexpIntType = builder.makeIntegerType(width, true);
7495 else
John Kessenich8985fc92020-03-03 10:25:07 -07007496 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7497 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007498 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7499 consumedOperands = 1;
7500 }
John Kessenich55e7d112015-11-15 21:33:39 -07007501 break;
7502 case glslang::EOpLdexp:
7503 libCall = spv::GLSLstd450Ldexp;
7504 break;
7505
Rex Xu574ab042016-04-14 16:53:07 +08007506 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007507 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007508
John Kessenich66011cb2018-03-06 16:12:04 -07007509 case glslang::EOpSubgroupBroadcast:
7510 case glslang::EOpSubgroupBallotBitExtract:
7511 case glslang::EOpSubgroupShuffle:
7512 case glslang::EOpSubgroupShuffleXor:
7513 case glslang::EOpSubgroupShuffleUp:
7514 case glslang::EOpSubgroupShuffleDown:
7515 case glslang::EOpSubgroupClusteredAdd:
7516 case glslang::EOpSubgroupClusteredMul:
7517 case glslang::EOpSubgroupClusteredMin:
7518 case glslang::EOpSubgroupClusteredMax:
7519 case glslang::EOpSubgroupClusteredAnd:
7520 case glslang::EOpSubgroupClusteredOr:
7521 case glslang::EOpSubgroupClusteredXor:
7522 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007523 case glslang::EOpSubgroupPartitionedAdd:
7524 case glslang::EOpSubgroupPartitionedMul:
7525 case glslang::EOpSubgroupPartitionedMin:
7526 case glslang::EOpSubgroupPartitionedMax:
7527 case glslang::EOpSubgroupPartitionedAnd:
7528 case glslang::EOpSubgroupPartitionedOr:
7529 case glslang::EOpSubgroupPartitionedXor:
7530 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7531 case glslang::EOpSubgroupPartitionedInclusiveMul:
7532 case glslang::EOpSubgroupPartitionedInclusiveMin:
7533 case glslang::EOpSubgroupPartitionedInclusiveMax:
7534 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7535 case glslang::EOpSubgroupPartitionedInclusiveOr:
7536 case glslang::EOpSubgroupPartitionedInclusiveXor:
7537 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7538 case glslang::EOpSubgroupPartitionedExclusiveMul:
7539 case glslang::EOpSubgroupPartitionedExclusiveMin:
7540 case glslang::EOpSubgroupPartitionedExclusiveMax:
7541 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7542 case glslang::EOpSubgroupPartitionedExclusiveOr:
7543 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007544 return createSubgroupOperation(op, typeId, operands, typeProxy);
7545
Rex Xu9d93a232016-05-05 12:30:44 +08007546 case glslang::EOpSwizzleInvocations:
7547 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7548 libCall = spv::SwizzleInvocationsAMD;
7549 break;
7550 case glslang::EOpSwizzleInvocationsMasked:
7551 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7552 libCall = spv::SwizzleInvocationsMaskedAMD;
7553 break;
7554 case glslang::EOpWriteInvocation:
7555 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7556 libCall = spv::WriteInvocationAMD;
7557 break;
7558
7559 case glslang::EOpMin3:
7560 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7561 if (isFloat)
7562 libCall = spv::FMin3AMD;
7563 else {
7564 if (isUnsigned)
7565 libCall = spv::UMin3AMD;
7566 else
7567 libCall = spv::SMin3AMD;
7568 }
7569 break;
7570 case glslang::EOpMax3:
7571 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7572 if (isFloat)
7573 libCall = spv::FMax3AMD;
7574 else {
7575 if (isUnsigned)
7576 libCall = spv::UMax3AMD;
7577 else
7578 libCall = spv::SMax3AMD;
7579 }
7580 break;
7581 case glslang::EOpMid3:
7582 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7583 if (isFloat)
7584 libCall = spv::FMid3AMD;
7585 else {
7586 if (isUnsigned)
7587 libCall = spv::UMid3AMD;
7588 else
7589 libCall = spv::SMid3AMD;
7590 }
7591 break;
7592
7593 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007594 if (typeProxy == glslang::EbtFloat16)
7595 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007596 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7597 libCall = spv::InterpolateAtVertexAMD;
7598 break;
Chao Chen3c366992018-09-19 11:41:59 -07007599
Daniel Kochdb32b242020-03-17 20:42:47 -04007600 case glslang::EOpReportIntersection:
Chao Chenb50c02e2018-09-19 11:42:24 -07007601 {
7602 typeId = builder.makeBoolType();
Daniel Kochdb32b242020-03-17 20:42:47 -04007603 opCode = spv::OpReportIntersectionKHR;
Chao Chenb50c02e2018-09-19 11:42:24 -07007604 }
7605 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04007606 case glslang::EOpTrace:
Chao Chenb50c02e2018-09-19 11:42:24 -07007607 {
Daniel Kochdb32b242020-03-17 20:42:47 -04007608 builder.createNoResultOp(spv::OpTraceRayKHR, operands);
Ashwin Leleff1783d2018-10-22 16:41:44 -07007609 return 0;
7610 }
7611 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04007612 case glslang::EOpExecuteCallable:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007613 {
Daniel Kochdb32b242020-03-17 20:42:47 -04007614 builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007615 return 0;
7616 }
7617 break;
Chao Chen3c366992018-09-19 11:41:59 -07007618 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7619 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7620 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007621 case glslang::EOpCooperativeMatrixMulAdd:
7622 opCode = spv::OpCooperativeMatrixMulAddNV;
7623 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007624#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007625 default:
7626 return 0;
7627 }
7628
7629 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007630 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007631 // Use an extended instruction from the standard library.
7632 // Construct the call arguments, without modifying the original operands vector.
7633 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7634 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007635 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007636 } else if (opCode == spv::OpDot && !isFloat) {
7637 // int dot(int, int)
7638 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7639 const int componentCount = builder.getNumComponents(operands[0]);
7640 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7641 builder.setPrecision(mulOp, precision);
7642 id = builder.createCompositeExtract(mulOp, typeId, 0);
7643 for (int i = 1; i < componentCount; ++i) {
7644 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07007645 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01007646 }
John Kessenich2359bd02015-12-06 19:29:11 -07007647 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007648 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007649 case 0:
7650 // should all be handled by visitAggregate and createNoArgOperation
7651 assert(0);
7652 return 0;
7653 case 1:
7654 // should all be handled by createUnaryOperation
7655 assert(0);
7656 return 0;
7657 case 2:
7658 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7659 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007660 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007661 // anything 3 or over doesn't have l-value operands, so all should be consumed
7662 assert(consumedOperands == operands.size());
7663 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007664 break;
7665 }
7666 }
7667
John Kessenichb9197c82019-08-11 07:41:45 -06007668#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007669 // Decode the return types that were structures
7670 switch (op) {
7671 case glslang::EOpAddCarry:
7672 case glslang::EOpSubBorrow:
7673 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7674 id = builder.createCompositeExtract(id, typeId0, 0);
7675 break;
7676 case glslang::EOpUMulExtended:
7677 case glslang::EOpIMulExtended:
7678 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7679 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7680 break;
7681 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007682 {
7683 assert(operands.size() == 2);
7684 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7685 // "exp" is floating-point type (from HLSL intrinsic)
7686 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7687 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7688 builder.createStore(member1, operands[1]);
7689 } else
7690 // "exp" is integer type (from GLSL built-in function)
7691 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7692 id = builder.createCompositeExtract(id, typeId0, 0);
7693 }
John Kessenich55e7d112015-11-15 21:33:39 -07007694 break;
7695 default:
7696 break;
7697 }
John Kessenichb9197c82019-08-11 07:41:45 -06007698#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007699
John Kessenich32cfd492016-02-02 12:37:46 -07007700 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007701}
7702
Rex Xu9d93a232016-05-05 12:30:44 +08007703// Intrinsics with no arguments (or no return value, and no precision).
7704spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007705{
Jeff Bolz36831c92018-09-05 10:11:41 -05007706 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07007707 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
7708 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007709
7710 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007711 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007712 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007713 if (glslangIntermediate->usingVulkanMemoryModel()) {
7714 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7715 spv::MemorySemanticsOutputMemoryKHRMask |
7716 spv::MemorySemanticsAcquireReleaseMask);
7717 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7718 } else {
7719 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7720 }
John Kessenich82979362017-12-11 04:02:24 -07007721 } else {
7722 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7723 spv::MemorySemanticsWorkgroupMemoryMask |
7724 spv::MemorySemanticsAcquireReleaseMask);
7725 }
John Kessenich140f3df2015-06-26 16:58:36 -06007726 return 0;
7727 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007728 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7729 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007730 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007731 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007732 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7733 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007734 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007735 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007736 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7737 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007738 return 0;
7739 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007740 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7741 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007742 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007743#ifndef GLSLANG_WEB
7744 case glslang::EOpMemoryBarrierAtomicCounter:
7745 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7746 spv::MemorySemanticsAcquireReleaseMask);
7747 return 0;
7748 case glslang::EOpMemoryBarrierImage:
7749 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7750 spv::MemorySemanticsAcquireReleaseMask);
7751 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007752 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007753 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007754 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007755 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007756 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007757 case glslang::EOpDeviceMemoryBarrier:
7758 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7759 spv::MemorySemanticsImageMemoryMask |
7760 spv::MemorySemanticsAcquireReleaseMask);
7761 return 0;
7762 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7763 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7764 spv::MemorySemanticsImageMemoryMask |
7765 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007766 return 0;
7767 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007768 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7769 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007770 return 0;
7771 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007772 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7773 spv::MemorySemanticsWorkgroupMemoryMask |
7774 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007775 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007776 case glslang::EOpSubgroupBarrier:
7777 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7778 spv::MemorySemanticsAcquireReleaseMask);
7779 return spv::NoResult;
7780 case glslang::EOpSubgroupMemoryBarrier:
7781 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7782 spv::MemorySemanticsAcquireReleaseMask);
7783 return spv::NoResult;
7784 case glslang::EOpSubgroupMemoryBarrierBuffer:
7785 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7786 spv::MemorySemanticsAcquireReleaseMask);
7787 return spv::NoResult;
7788 case glslang::EOpSubgroupMemoryBarrierImage:
7789 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7790 spv::MemorySemanticsAcquireReleaseMask);
7791 return spv::NoResult;
7792 case glslang::EOpSubgroupMemoryBarrierShared:
7793 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7794 spv::MemorySemanticsAcquireReleaseMask);
7795 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06007796
7797 case glslang::EOpEmitVertex:
7798 builder.createNoResultOp(spv::OpEmitVertex);
7799 return 0;
7800 case glslang::EOpEndPrimitive:
7801 builder.createNoResultOp(spv::OpEndPrimitive);
7802 return 0;
7803
John Kessenich66011cb2018-03-06 16:12:04 -07007804 case glslang::EOpSubgroupElect: {
7805 std::vector<spv::Id> operands;
7806 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7807 }
Rex Xu9d93a232016-05-05 12:30:44 +08007808 case glslang::EOpTime:
7809 {
7810 std::vector<spv::Id> args; // Dummy arguments
7811 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7812 return builder.setPrecision(id, precision);
7813 }
Daniel Kochdb32b242020-03-17 20:42:47 -04007814 case glslang::EOpIgnoreIntersection:
7815 builder.createNoResultOp(spv::OpIgnoreIntersectionKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07007816 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04007817 case glslang::EOpTerminateRay:
7818 builder.createNoResultOp(spv::OpTerminateRayKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07007819 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007820
7821 case glslang::EOpBeginInvocationInterlock:
7822 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7823 return 0;
7824 case glslang::EOpEndInvocationInterlock:
7825 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7826 return 0;
7827
Jeff Bolzba6170b2019-07-01 09:23:23 -05007828 case glslang::EOpIsHelperInvocation:
7829 {
7830 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08007831 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
7832 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
7833 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05007834 }
7835
amhagan91fb0092019-07-10 21:14:38 -04007836 case glslang::EOpReadClockSubgroupKHR: {
7837 std::vector<spv::Id> args;
7838 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
7839 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7840 builder.addCapability(spv::CapabilityShaderClockKHR);
7841 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7842 }
7843
7844 case glslang::EOpReadClockDeviceKHR: {
7845 std::vector<spv::Id> args;
7846 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
7847 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7848 builder.addCapability(spv::CapabilityShaderClockKHR);
7849 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7850 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06007851#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007852 default:
John Kessenich155d3512019-08-08 23:29:20 -06007853 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007854 }
John Kessenich155d3512019-08-08 23:29:20 -06007855
7856 logger->missingFunctionality("unknown operation with no arguments");
7857
7858 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007859}
7860
7861spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7862{
John Kessenich2f273362015-07-18 22:34:27 -06007863 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007864 spv::Id id;
7865 if (symbolValues.end() != iter) {
7866 id = iter->second;
7867 return id;
7868 }
7869
7870 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06007871 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
Daniel Kochdb32b242020-03-17 20:42:47 -04007872 auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06007873 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06007874 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06007875 if (forcedType.second != spv::NoType)
7876 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06007877
Rex Xuc884b4a2016-06-29 15:03:44 +08007878 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007879 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7880 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7881 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06007882#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007883 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06007884 if (symbol->getQualifier().hasComponent())
7885 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
7886 if (symbol->getQualifier().hasIndex())
7887 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07007888#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007889 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007890 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06007891 // atomic counters use this:
7892 if (symbol->getQualifier().hasOffset())
7893 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007894 }
7895
scygan2c864272016-05-18 18:09:17 +02007896 if (symbol->getQualifier().hasLocation())
7897 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007898 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007899 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007900 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007901 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007902 }
John Kessenich140f3df2015-06-26 16:58:36 -06007903 if (symbol->getQualifier().hasSet())
7904 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007905 else if (IsDescriptorResource(symbol->getType())) {
7906 // default to 0
7907 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7908 }
John Kessenich140f3df2015-06-26 16:58:36 -06007909 if (symbol->getQualifier().hasBinding())
7910 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007911 else if (IsDescriptorResource(symbol->getType())) {
7912 // default to 0
7913 builder.addDecoration(id, spv::DecorationBinding, 0);
7914 }
John Kessenich6c292d32016-02-15 20:58:50 -07007915 if (symbol->getQualifier().hasAttachment())
7916 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007917 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007918 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007919 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007920 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007921 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7922 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7923 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7924 }
7925 if (symbol->getQualifier().hasXfbOffset())
7926 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007927 }
7928
John Kessenichb9197c82019-08-11 07:41:45 -06007929 // add built-in variable decoration
7930 if (builtIn != spv::BuiltInMax) {
7931 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
7932 }
7933
7934#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08007935 if (symbol->getType().isImage()) {
7936 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07007937 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
7938 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007939 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007940 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007941 }
7942
John Kessenich5611c6d2018-04-05 11:25:02 -06007943 // nonuniform
7944 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7945
chaoc0ad6a4e2016-12-19 16:29:34 -08007946 if (builtIn == spv::BuiltInSampleMask) {
7947 spv::Decoration decoration;
7948 // GL_NV_sample_mask_override_coverage extension
7949 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007950 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007951 else
7952 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007953 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007954 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07007955 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08007956 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7957 }
7958 }
chaoc771d89f2017-01-13 01:10:53 -08007959 else if (builtIn == spv::BuiltInLayer) {
7960 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007961 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007962 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007963 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7964 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7965 }
John Kessenichb41bff62017-08-11 13:07:17 -06007966 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007967 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7968 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007969 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7970 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7971 }
7972 }
7973
chaoc6e5acae2016-12-20 13:28:52 -08007974 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007975 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007976 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007977 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7978 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007979 if (symbol->getQualifier().pervertexNV) {
7980 builder.addDecoration(id, spv::DecorationPerVertexNV);
7981 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7982 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7983 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007984
John Kessenich5d610ee2018-03-07 18:05:55 -07007985 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7986 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7987 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7988 symbol->getType().getQualifier().semanticName);
7989 }
7990
John Kessenich7015bd62019-08-01 03:28:08 -06007991 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07007992 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
7993 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007994 }
John Kessenichb9197c82019-08-11 07:41:45 -06007995#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007996
John Kessenich140f3df2015-06-26 16:58:36 -06007997 return id;
7998}
7999
John Kessenicha28f7a72019-08-06 07:00:58 -06008000#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008001// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
8002void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
8003{
8004 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07008005 if (qualifier.perPrimitiveNV) {
8006 // Need to add capability/extension for fragment shader.
8007 // Mesh shader already adds this by default.
8008 if (glslangIntermediate->getStage() == EShLangFragment) {
8009 builder.addCapability(spv::CapabilityMeshShadingNV);
8010 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8011 }
Chao Chen3c366992018-09-19 11:41:59 -07008012 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008013 }
Chao Chen3c366992018-09-19 11:41:59 -07008014 if (qualifier.perViewNV)
8015 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
8016 if (qualifier.perTaskNV)
8017 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
8018 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07008019 if (qualifier.perPrimitiveNV) {
8020 // Need to add capability/extension for fragment shader.
8021 // Mesh shader already adds this by default.
8022 if (glslangIntermediate->getStage() == EShLangFragment) {
8023 builder.addCapability(spv::CapabilityMeshShadingNV);
8024 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8025 }
Chao Chen3c366992018-09-19 11:41:59 -07008026 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008027 }
Chao Chen3c366992018-09-19 11:41:59 -07008028 if (qualifier.perViewNV)
8029 builder.addDecoration(id, spv::DecorationPerViewNV);
8030 if (qualifier.perTaskNV)
8031 builder.addDecoration(id, spv::DecorationPerTaskNV);
8032 }
8033}
8034#endif
8035
John Kessenich55e7d112015-11-15 21:33:39 -07008036// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008037// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008038//
8039// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8040//
8041// Recursively walk the nodes. The nodes form a tree whose leaves are
8042// regular constants, which themselves are trees that createSpvConstant()
8043// recursively walks. So, this function walks the "top" of the tree:
8044// - emit specialization constant-building instructions for specConstant
8045// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008046spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008047{
John Kessenich7cc0e282016-03-20 00:46:02 -06008048 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008049
qining4f4bb812016-04-03 23:55:17 -04008050 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008051 if (! node.getQualifier().specConstant) {
8052 // hand off to the non-spec-constant path
8053 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8054 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008055 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8056 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8057 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008058 }
8059
8060 // We now know we have a specialization constant to build
8061
John Kessenichd94c0032016-05-30 19:29:40 -06008062 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008063 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8064 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8065 std::vector<spv::Id> dimConstId;
8066 for (int dim = 0; dim < 3; ++dim) {
8067 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8068 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008069 if (specConst) {
8070 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8071 glslangIntermediate->getLocalSizeSpecId(dim));
8072 }
qining4f4bb812016-04-03 23:55:17 -04008073 }
8074 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8075 }
8076
8077 // An AST node labelled as specialization constant should be a symbol node.
8078 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8079 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008080 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008081 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008082 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8083 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8084 // will set the builder into spec constant op instruction generating mode.
8085 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008086 result = accessChainLoad(sub_tree->getType());
8087 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008088 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008089 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008090 } else {
8091 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008092 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008093 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008094 builder.addName(result, sn->getName().c_str());
8095 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008096 }
qining4f4bb812016-04-03 23:55:17 -04008097
8098 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8099 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008100 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008101 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008102}
8103
John Kessenich140f3df2015-06-26 16:58:36 -06008104// Use 'consts' as the flattened glslang source of scalar constants to recursively
8105// build the aggregate SPIR-V constant.
8106//
8107// If there are not enough elements present in 'consts', 0 will be substituted;
8108// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8109//
John Kessenich8985fc92020-03-03 10:25:07 -07008110spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8111 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008112{
8113 // vector of constants for SPIR-V
8114 std::vector<spv::Id> spvConsts;
8115
8116 // Type is used for struct and array constants
8117 spv::Id typeId = convertGlslangToSpvType(glslangType);
8118
8119 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008120 glslang::TType elementType(glslangType, 0);
8121 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008122 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008123 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008124 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008125 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008126 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008127 } else if (glslangType.isCoopMat()) {
8128 glslang::TType componentType(glslangType.getBasicType());
8129 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008130 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008131 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8132 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008133 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008134 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008135 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8136 bool zero = nextConst >= consts.size();
8137 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008138 case glslang::EbtInt:
8139 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8140 break;
8141 case glslang::EbtUint:
8142 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8143 break;
8144 case glslang::EbtFloat:
8145 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8146 break;
8147 case glslang::EbtBool:
8148 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8149 break;
8150#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008151 case glslang::EbtInt8:
8152 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8153 break;
8154 case glslang::EbtUint8:
8155 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8156 break;
8157 case glslang::EbtInt16:
8158 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8159 break;
8160 case glslang::EbtUint16:
8161 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8162 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008163 case glslang::EbtInt64:
8164 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8165 break;
8166 case glslang::EbtUint64:
8167 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8168 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008169 case glslang::EbtDouble:
8170 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8171 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008172 case glslang::EbtFloat16:
8173 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8174 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008175#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008176 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008177 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008178 break;
8179 }
8180 ++nextConst;
8181 }
8182 } else {
8183 // we have a non-aggregate (scalar) constant
8184 bool zero = nextConst >= consts.size();
8185 spv::Id scalar = 0;
8186 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008187 case glslang::EbtInt:
8188 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8189 break;
8190 case glslang::EbtUint:
8191 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8192 break;
8193 case glslang::EbtFloat:
8194 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8195 break;
8196 case glslang::EbtBool:
8197 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8198 break;
8199#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008200 case glslang::EbtInt8:
8201 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8202 break;
8203 case glslang::EbtUint8:
8204 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8205 break;
8206 case glslang::EbtInt16:
8207 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8208 break;
8209 case glslang::EbtUint16:
8210 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8211 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008212 case glslang::EbtInt64:
8213 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8214 break;
8215 case glslang::EbtUint64:
8216 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8217 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008218 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008219 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008220 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008221 case glslang::EbtFloat16:
8222 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8223 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008224 case glslang::EbtReference:
8225 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8226 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8227 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008228#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008229 case glslang::EbtString:
8230 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8231 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008232 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008233 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008234 break;
8235 }
8236 ++nextConst;
8237 return scalar;
8238 }
8239
8240 return builder.makeCompositeConstant(typeId, spvConsts);
8241}
8242
John Kessenich7c1aa102015-10-15 13:29:11 -06008243// Return true if the node is a constant or symbol whose reading has no
8244// non-trivial observable cost or effect.
8245bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8246{
8247 // don't know what this is
8248 if (node == nullptr)
8249 return false;
8250
8251 // a constant is safe
8252 if (node->getAsConstantUnion() != nullptr)
8253 return true;
8254
8255 // not a symbol means non-trivial
8256 if (node->getAsSymbolNode() == nullptr)
8257 return false;
8258
8259 // a symbol, depends on what's being read
8260 switch (node->getType().getQualifier().storage) {
8261 case glslang::EvqTemporary:
8262 case glslang::EvqGlobal:
8263 case glslang::EvqIn:
8264 case glslang::EvqInOut:
8265 case glslang::EvqConst:
8266 case glslang::EvqConstReadOnly:
8267 case glslang::EvqUniform:
8268 return true;
8269 default:
8270 return false;
8271 }
qining25262b32016-05-06 17:25:16 -04008272}
John Kessenich7c1aa102015-10-15 13:29:11 -06008273
8274// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008275// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008276// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008277// Return true if trivial.
8278bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8279{
8280 if (node == nullptr)
8281 return false;
8282
John Kessenich84cc15f2017-05-24 16:44:47 -06008283 // count non scalars as trivial, as well as anything coming from HLSL
8284 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008285 return true;
8286
John Kessenich7c1aa102015-10-15 13:29:11 -06008287 // symbols and constants are trivial
8288 if (isTrivialLeaf(node))
8289 return true;
8290
8291 // otherwise, it needs to be a simple operation or one or two leaf nodes
8292
8293 // not a simple operation
8294 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8295 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8296 if (binaryNode == nullptr && unaryNode == nullptr)
8297 return false;
8298
8299 // not on leaf nodes
8300 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8301 return false;
8302
8303 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8304 return false;
8305 }
8306
8307 switch (node->getAsOperator()->getOp()) {
8308 case glslang::EOpLogicalNot:
8309 case glslang::EOpConvIntToBool:
8310 case glslang::EOpConvUintToBool:
8311 case glslang::EOpConvFloatToBool:
8312 case glslang::EOpConvDoubleToBool:
8313 case glslang::EOpEqual:
8314 case glslang::EOpNotEqual:
8315 case glslang::EOpLessThan:
8316 case glslang::EOpGreaterThan:
8317 case glslang::EOpLessThanEqual:
8318 case glslang::EOpGreaterThanEqual:
8319 case glslang::EOpIndexDirect:
8320 case glslang::EOpIndexDirectStruct:
8321 case glslang::EOpLogicalXor:
8322 case glslang::EOpAny:
8323 case glslang::EOpAll:
8324 return true;
8325 default:
8326 return false;
8327 }
8328}
8329
8330// Emit short-circuiting code, where 'right' is never evaluated unless
8331// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008332spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8333 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008334{
8335 spv::Id boolTypeId = builder.makeBoolType();
8336
8337 // emit left operand
8338 builder.clearAccessChain();
8339 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008340 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008341
8342 // Operands to accumulate OpPhi operands
8343 std::vector<spv::Id> phiOperands;
8344 // accumulate left operand's phi information
8345 phiOperands.push_back(leftId);
8346 phiOperands.push_back(builder.getBuildPoint()->getId());
8347
8348 // Make the two kinds of operation symmetric with a "!"
8349 // || => emit "if (! left) result = right"
8350 // && => emit "if ( left) result = right"
8351 //
8352 // TODO: this runtime "not" for || could be avoided by adding functionality
8353 // to 'builder' to have an "else" without an "then"
8354 if (op == glslang::EOpLogicalOr)
8355 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8356
8357 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008358 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008359
8360 // emit right operand as the "then" part of the "if"
8361 builder.clearAccessChain();
8362 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008363 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008364
8365 // accumulate left operand's phi information
8366 phiOperands.push_back(rightId);
8367 phiOperands.push_back(builder.getBuildPoint()->getId());
8368
8369 // finish the "if"
8370 ifBuilder.makeEndIf();
8371
8372 // phi together the two results
8373 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8374}
8375
John Kessenicha28f7a72019-08-06 07:00:58 -06008376#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008377// Return type Id of the imported set of extended instructions corresponds to the name.
8378// Import this set if it has not been imported yet.
8379spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8380{
8381 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8382 return extBuiltinMap[name];
8383 else {
Rex Xu51596642016-09-21 18:56:12 +08008384 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008385 spv::Id extBuiltins = builder.import(name);
8386 extBuiltinMap[name] = extBuiltins;
8387 return extBuiltins;
8388 }
8389}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008390#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008391
John Kessenich140f3df2015-06-26 16:58:36 -06008392}; // end anonymous namespace
8393
8394namespace glslang {
8395
John Kessenich68d78fd2015-07-12 19:28:10 -06008396void GetSpirvVersion(std::string& version)
8397{
John Kessenich9e55f632015-07-15 10:03:39 -06008398 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008399 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008400 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008401 version = buf;
8402}
8403
John Kessenicha372a3e2017-11-02 22:32:14 -06008404// For low-order part of the generator's magic number. Bump up
8405// when there is a change in the style (e.g., if SSA form changes,
8406// or a different instruction sequence to do something gets used).
8407int GetSpirvGeneratorVersion()
8408{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008409 // return 1; // start
8410 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008411 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008412 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008413 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008414 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8415 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008416 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
8417 return 8; // switch to new dead block eliminator; use OpUnreachable
John Kessenicha372a3e2017-11-02 22:32:14 -06008418}
8419
John Kessenich140f3df2015-06-26 16:58:36 -06008420// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008421void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008422{
8423 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008424 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008425 if (out.fail())
8426 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008427 for (int i = 0; i < (int)spirv.size(); ++i) {
8428 unsigned int word = spirv[i];
8429 out.write((const char*)&word, 4);
8430 }
8431 out.close();
8432}
8433
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008434// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008435void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008436{
John Kessenich155d3512019-08-08 23:29:20 -06008437#ifndef GLSLANG_WEB
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008438 std::ofstream out;
8439 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008440 if (out.fail())
8441 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008442 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008443 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008444 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008445 if (varName != nullptr) {
8446 out << "\t #pragma once" << std::endl;
8447 out << "const uint32_t " << varName << "[] = {" << std::endl;
8448 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008449 const int WORDS_PER_LINE = 8;
8450 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8451 out << "\t";
8452 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8453 const unsigned int word = spirv[i + j];
8454 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8455 if (i + j + 1 < (int)spirv.size()) {
8456 out << ",";
8457 }
8458 }
8459 out << std::endl;
8460 }
Flavio15017db2017-02-15 14:29:33 -08008461 if (varName != nullptr) {
8462 out << "};";
8463 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008464 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008465#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008466}
8467
John Kessenich140f3df2015-06-26 16:58:36 -06008468//
8469// Set up the glslang traversal
8470//
John Kessenich4e11b612018-08-30 16:56:59 -06008471void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008472{
Lei Zhang17535f72016-05-04 15:55:59 -04008473 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008474 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008475}
8476
John Kessenich4e11b612018-08-30 16:56:59 -06008477void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008478 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008479{
John Kessenich140f3df2015-06-26 16:58:36 -06008480 TIntermNode* root = intermediate.getTreeRoot();
8481
8482 if (root == 0)
8483 return;
8484
John Kessenich4e11b612018-08-30 16:56:59 -06008485 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008486 if (options == nullptr)
8487 options = &defaultOptions;
8488
John Kessenich4e11b612018-08-30 16:56:59 -06008489 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008490
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008491 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008492 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008493 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008494 it.dumpSpv(spirv);
8495
GregFfb03a552018-03-29 11:49:14 -06008496#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008497 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8498 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008499 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8500 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008501 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008502 prelegalization = false;
8503 }
John Kessenich717c80a2018-08-23 15:17:10 -06008504
John Kessenich4e11b612018-08-30 16:56:59 -06008505 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008506 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008507
John Kessenich717c80a2018-08-23 15:17:10 -06008508 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008509 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008510
GregFcd1f1692017-09-21 18:40:22 -06008511#endif
8512
John Kessenich4e11b612018-08-30 16:56:59 -06008513 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008514}
8515
8516}; // end namespace glslang