blob: 98e02831e972dee8cf872d812e0f1ca2ab8dcc82 [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"
John Kessenich5e4b1242015-08-06 22:53:06 -060051}
John Kessenich140f3df2015-06-26 16:58:36 -060052
53// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020054#include "../glslang/MachineIndependent/localintermediate.h"
55#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060056#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050057#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060058
John Kessenich140f3df2015-06-26 16:58:36 -060059#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050060#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040061#include <list>
62#include <map>
63#include <stack>
64#include <string>
65#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060066
67namespace {
68
qining4c912612016-04-01 10:35:16 -040069namespace {
70class SpecConstantOpModeGuard {
71public:
72 SpecConstantOpModeGuard(spv::Builder* builder)
73 : builder_(builder) {
74 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040075 }
76 ~SpecConstantOpModeGuard() {
77 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
78 : builder_->setToNormalCodeGenMode();
79 }
qining40887662016-04-03 22:20:42 -040080 void turnOnSpecConstantOpMode() {
81 builder_->setToSpecConstCodeGenMode();
82 }
qining4c912612016-04-01 10:35:16 -040083
84private:
85 spv::Builder* builder_;
86 bool previous_flag_;
87};
John Kessenichead86222018-03-28 18:01:20 -060088
89struct OpDecorations {
John Kessenichb9197c82019-08-11 07:41:45 -060090 public:
91 OpDecorations(spv::Decoration precision, spv::Decoration noContraction, spv::Decoration nonUniform) :
92 precision(precision)
93#ifndef GLSLANG_WEB
94 ,
95 noContraction(noContraction),
96 nonUniform(nonUniform)
97#endif
98 { }
99
John Kessenichead86222018-03-28 18:01:20 -0600100 spv::Decoration precision;
John Kessenichb9197c82019-08-11 07:41:45 -0600101
102#ifdef GLSLANG_WEB
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400103 void addNoContraction(spv::Builder&, spv::Id) const { }
104 void addNonUniform(spv::Builder&, spv::Id) const { }
John Kessenichb9197c82019-08-11 07:41:45 -0600105#else
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400106 void addNoContraction(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, noContraction); }
107 void addNonUniform(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, nonUniform); }
John Kessenichb9197c82019-08-11 07:41:45 -0600108 protected:
109 spv::Decoration noContraction;
110 spv::Decoration nonUniform;
111#endif
112
John Kessenichead86222018-03-28 18:01:20 -0600113};
114
115} // namespace
qining4c912612016-04-01 10:35:16 -0400116
John Kessenich140f3df2015-06-26 16:58:36 -0600117//
118// The main holder of information for translating glslang to SPIR-V.
119//
120// Derives from the AST walking base class.
121//
122class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
123public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700124 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
125 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700126 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600127
128 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
129 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
130 void visitConstantUnion(glslang::TIntermConstantUnion*);
131 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
132 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
133 void visitSymbol(glslang::TIntermSymbol* symbol);
134 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
135 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
136 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
137
John Kessenichfca82622016-11-26 13:23:20 -0700138 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700139 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600140
141protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700142 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
143 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
144
Rex Xu17ff3432016-10-14 17:41:45 +0800145 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800146 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600147 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500148 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
149 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
150 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
151 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100152 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700153 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700154 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
155 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700156 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600157 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600158 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich9c14f772019-06-17 08:38:35 -0600159 spv::Id createSpvVariable(const glslang::TIntermSymbol*, spv::Id forcedType);
John Kessenich140f3df2015-06-26 16:58:36 -0600160 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600161 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
162 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
163 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600164 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600165 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600166 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600167 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600168 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
169 glslang::TLayoutPacking, const glslang::TQualifier&);
170 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
171 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700172 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700173 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800174 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600175 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700176 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700177 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
178 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700179 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
180 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100181 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600182
John Kessenich6fccb3c2016-09-19 16:01:41 -0600183 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600184 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600185 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600186 void makeFunctions(const glslang::TIntermSequence&);
187 void makeGlobalInitializers(const glslang::TIntermSequence&);
188 void visitFunctions(const glslang::TIntermSequence&);
189 void handleFunctionEntry(const glslang::TIntermAggregate* node);
John Kessenich8985fc92020-03-03 10:25:07 -0700190 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
191 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -0600192 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
193 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600194 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
195
John Kessenichead86222018-03-28 18:01:20 -0600196 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
197 glslang::TBasicType typeProxy, bool reduceComparison = true);
198 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
199 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
John Kessenich8985fc92020-03-03 10:25:07 -0700200 glslang::TBasicType typeProxy,
201 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -0600202 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
203 glslang::TBasicType typeProxy);
204 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
205 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600206 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600207 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
John Kessenich8985fc92020-03-03 10:25:07 -0700208 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId,
209 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
210 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
211 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands,
212 glslang::TBasicType typeProxy);
213 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
214 spv::Id typeId, std::vector<spv::Id>& operands);
215 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands,
216 glslang::TBasicType typeProxy);
217 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId,
218 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800219 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600220 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700221 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
qining08408382016-03-21 09:51:37 -0400222 spv::Id createSpvConstant(const glslang::TIntermTyped&);
John Kessenich8985fc92020-03-03 10:25:07 -0700223 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&,
224 int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600225 bool isTrivialLeaf(const glslang::TIntermTyped* node);
226 bool isTrivial(const glslang::TIntermTyped* node);
227 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800228 spv::Id getExtBuiltins(const char* name);
John Kessenich9c14f772019-06-17 08:38:35 -0600229 std::pair<spv::Id, spv::Id> getForcedType(spv::BuiltIn, const glslang::TType&);
230 spv::Id translateForcedType(spv::Id object);
Jeff Bolz53134492019-06-25 13:31:10 -0500231 spv::Id createCompositeConstruct(spv::Id typeId, std::vector<spv::Id> constituents);
John Kessenich140f3df2015-06-26 16:58:36 -0600232
John Kessenich121853f2017-05-31 17:11:16 -0600233 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600234 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600235 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700236 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600237 int sequenceDepth;
238
Lei Zhang17535f72016-05-04 15:55:59 -0400239 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400240
John Kessenich140f3df2015-06-26 16:58:36 -0600241 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
242 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700243 bool inEntryPoint;
244 bool entryPointTerminated;
John Kessenich8985fc92020-03-03 10:25:07 -0700245 bool linkageOnly; // true when visiting the set of objects in the AST present only for
246 // establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700247 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600248 const glslang::TIntermediate* glslangIntermediate;
John Kessenich605afc72019-06-17 23:33:09 -0600249 bool nanMinMaxClamp; // true if use NMin/NMax/NClamp instead of FMin/FMax/FClamp
John Kessenich140f3df2015-06-26 16:58:36 -0600250 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800251 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600252
John Kessenich2f273362015-07-18 22:34:27 -0600253 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich8985fc92020-03-03 10:25:07 -0700254 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues,
255 // rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600256 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700257 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700258 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
Roy05a5b532020-01-03 16:21:34 +0800259 std::unordered_map<int, std::vector<int>> memberRemapper;
260 // for mapping glslang symbol struct to symbol Id
261 std::unordered_map<const glslang::TTypeList*, int> glslangTypeToIdMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600262 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700263 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600264 // Map pointee types for EbtReference to their forward pointers
265 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich9c14f772019-06-17 08:38:35 -0600266 // Type forcing, for when SPIR-V wants a different type than the AST,
267 // requiring local translation to and from SPIR-V type on every access.
268 // Maps <builtin-variable-id -> AST-required-type-id>
269 std::unordered_map<spv::Id, spv::Id> forceType;
John Kessenich140f3df2015-06-26 16:58:36 -0600270};
271
272//
273// Helper functions for translating glslang representations to SPIR-V enumerants.
274//
275
276// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700277spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600278{
John Kessenich155d3512019-08-08 23:29:20 -0600279#ifdef GLSLANG_WEB
280 return spv::SourceLanguageESSL;
281#endif
282
John Kessenich66e2faf2016-03-12 18:34:36 -0700283 switch (source) {
284 case glslang::EShSourceGlsl:
285 switch (profile) {
286 case ENoProfile:
287 case ECoreProfile:
288 case ECompatibilityProfile:
289 return spv::SourceLanguageGLSL;
290 case EEsProfile:
291 return spv::SourceLanguageESSL;
292 default:
293 return spv::SourceLanguageUnknown;
294 }
295 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600296 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600297 default:
298 return spv::SourceLanguageUnknown;
299 }
300}
301
302// Translate glslang language (stage) to SPIR-V execution model.
303spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
304{
305 switch (stage) {
306 case EShLangVertex: return spv::ExecutionModelVertex;
John Kessenicha28f7a72019-08-06 07:00:58 -0600307 case EShLangFragment: return spv::ExecutionModelFragment;
John Kessenicha28f7a72019-08-06 07:00:58 -0600308 case EShLangCompute: return spv::ExecutionModelGLCompute;
John Kessenich51ed01c2019-10-10 11:40:11 -0600309#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -0600310 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
311 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
312 case EShLangGeometry: return spv::ExecutionModelGeometry;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700313 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
314 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
315 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
316 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
317 case EShLangMissNV: return spv::ExecutionModelMissNV;
318 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700319 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
320 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
321#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600322 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700323 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600324 return spv::ExecutionModelFragment;
325 }
326}
327
John Kessenich140f3df2015-06-26 16:58:36 -0600328// Translate glslang sampler type to SPIR-V dimensionality.
329spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
330{
331 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700332 case glslang::Esd1D: return spv::Dim1D;
333 case glslang::Esd2D: return spv::Dim2D;
334 case glslang::Esd3D: return spv::Dim3D;
335 case glslang::EsdCube: return spv::DimCube;
336 case glslang::EsdRect: return spv::DimRect;
337 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700338 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600339 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700340 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600341 return spv::Dim2D;
342 }
343}
344
John Kessenichf6640762016-08-01 19:44:00 -0600345// Translate glslang precision to SPIR-V precision decorations.
346spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600347{
John Kessenichf6640762016-08-01 19:44:00 -0600348 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700349 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600350 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600351 default:
352 return spv::NoPrecision;
353 }
354}
355
John Kessenichf6640762016-08-01 19:44:00 -0600356// Translate glslang type to SPIR-V precision decorations.
357spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
358{
359 return TranslatePrecisionDecoration(type.getQualifier().precision);
360}
361
John Kessenich140f3df2015-06-26 16:58:36 -0600362// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600363spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600364{
365 if (type.getBasicType() == glslang::EbtBlock) {
366 switch (type.getQualifier().storage) {
367 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600368 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600369 case glslang::EvqVaryingIn: return spv::DecorationBlock;
370 case glslang::EvqVaryingOut: return spv::DecorationBlock;
John Kessenicha28f7a72019-08-06 07:00:58 -0600371#ifndef GLSLANG_WEB
Chao Chenb50c02e2018-09-19 11:42:24 -0700372 case glslang::EvqPayloadNV: return spv::DecorationBlock;
373 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
374 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700375 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
376 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700377#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600378 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700379 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600380 break;
381 }
382 }
383
John Kessenich4016e382016-07-15 11:53:56 -0600384 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600385}
386
Rex Xu1da878f2016-02-21 20:59:01 +0800387// Translate glslang type to SPIR-V memory decorations.
John Kessenich8985fc92020-03-03 10:25:07 -0700388void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory,
389 bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800390{
Jeff Bolz36831c92018-09-05 10:11:41 -0500391 if (!useVulkanMemoryModel) {
John Kessenichf8d1d742019-10-21 06:55:11 -0600392 if (qualifier.isCoherent())
Jeff Bolz36831c92018-09-05 10:11:41 -0500393 memory.push_back(spv::DecorationCoherent);
John Kessenichf8d1d742019-10-21 06:55:11 -0600394 if (qualifier.isVolatile()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500395 memory.push_back(spv::DecorationVolatile);
396 memory.push_back(spv::DecorationCoherent);
397 }
John Kessenich14b85d32018-06-04 15:36:03 -0600398 }
John Kessenichf8d1d742019-10-21 06:55:11 -0600399 if (qualifier.isRestrict())
Rex Xu1da878f2016-02-21 20:59:01 +0800400 memory.push_back(spv::DecorationRestrict);
John Kessenichdeec1932019-08-13 08:00:30 -0600401 if (qualifier.isReadOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800402 memory.push_back(spv::DecorationNonWritable);
John Kessenichdeec1932019-08-13 08:00:30 -0600403 if (qualifier.isWriteOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800404 memory.push_back(spv::DecorationNonReadable);
405}
406
John Kessenich140f3df2015-06-26 16:58:36 -0600407// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700408spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600409{
410 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700411 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600412 case glslang::ElmRowMajor:
413 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700414 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600415 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700416 default:
417 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600418 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600419 }
420 } else {
421 switch (type.getBasicType()) {
422 default:
John Kessenich4016e382016-07-15 11:53:56 -0600423 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600424 break;
425 case glslang::EbtBlock:
426 switch (type.getQualifier().storage) {
427 case glslang::EvqUniform:
428 case glslang::EvqBuffer:
429 switch (type.getQualifier().layoutPacking) {
430 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600431 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
432 default:
John Kessenich4016e382016-07-15 11:53:56 -0600433 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600434 }
435 case glslang::EvqVaryingIn:
436 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700437 if (type.getQualifier().isTaskMemory()) {
438 switch (type.getQualifier().layoutPacking) {
439 case glslang::ElpShared: return spv::DecorationGLSLShared;
440 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
441 default: break;
442 }
443 } else {
444 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
445 }
John Kessenich4016e382016-07-15 11:53:56 -0600446 return spv::DecorationMax;
John Kessenicha28f7a72019-08-06 07:00:58 -0600447#ifndef GLSLANG_WEB
Chao Chenb50c02e2018-09-19 11:42:24 -0700448 case glslang::EvqPayloadNV:
449 case glslang::EvqPayloadInNV:
450 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700451 case glslang::EvqCallableDataNV:
452 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700453 return spv::DecorationMax;
454#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600455 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700456 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600457 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600458 }
459 }
460 }
461}
462
463// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600464// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700465// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800466spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600467{
Rex Xubbceed72016-05-21 09:40:44 +0800468 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700469 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600470 return spv::DecorationMax;
John Kessenich7015bd62019-08-01 03:28:08 -0600471 else if (qualifier.isNonPerspective())
John Kessenich55e7d112015-11-15 21:33:39 -0700472 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700473 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600474 return spv::DecorationFlat;
John Kessenicha28f7a72019-08-06 07:00:58 -0600475 else if (qualifier.isExplicitInterpolation()) {
Rex Xu17ff3432016-10-14 17:41:45 +0800476 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800477 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800478 }
Rex Xubbceed72016-05-21 09:40:44 +0800479 else
John Kessenich4016e382016-07-15 11:53:56 -0600480 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800481}
482
483// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600484// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800485// should be applied.
486spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
487{
John Kessenichb9197c82019-08-11 07:41:45 -0600488 if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600489 return spv::DecorationCentroid;
John Kessenichb9197c82019-08-11 07:41:45 -0600490#ifndef GLSLANG_WEB
491 else if (qualifier.patch)
492 return spv::DecorationPatch;
John Kessenich5e801132016-02-15 11:09:46 -0700493 else if (qualifier.sample) {
494 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600495 return spv::DecorationSample;
John Kessenichb9197c82019-08-11 07:41:45 -0600496 }
497#endif
498
499 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600500}
501
John Kessenich92187592016-02-01 13:45:25 -0700502// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700503spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600504{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700505 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600506 return spv::DecorationInvariant;
507 else
John Kessenich4016e382016-07-15 11:53:56 -0600508 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600509}
510
qining9220dbb2016-05-04 17:34:38 -0400511// If glslang type is noContraction, return SPIR-V NoContraction decoration.
512spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
513{
John Kessenichb9197c82019-08-11 07:41:45 -0600514#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -0600515 if (qualifier.isNoContraction())
qining9220dbb2016-05-04 17:34:38 -0400516 return spv::DecorationNoContraction;
517 else
John Kessenichb9197c82019-08-11 07:41:45 -0600518#endif
John Kessenich4016e382016-07-15 11:53:56 -0600519 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400520}
521
John Kessenich5611c6d2018-04-05 11:25:02 -0600522// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
523spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
524{
John Kessenichb9197c82019-08-11 07:41:45 -0600525#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -0600526 if (qualifier.isNonUniform()) {
John Kessenich8317e6c2019-08-18 23:58:08 -0600527 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -0600528 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
529 return spv::DecorationNonUniformEXT;
530 } else
John Kessenichb9197c82019-08-11 07:41:45 -0600531#endif
John Kessenich5611c6d2018-04-05 11:25:02 -0600532 return spv::DecorationMax;
533}
534
John Kessenichb9197c82019-08-11 07:41:45 -0600535spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(
536 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500537{
Jeff Bolz36831c92018-09-05 10:11:41 -0500538 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600539
540#ifndef GLSLANG_WEB
541 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage)
542 return mask;
543
Jeff Bolz36831c92018-09-05 10:11:41 -0500544 if (coherentFlags.volatil ||
545 coherentFlags.coherent ||
546 coherentFlags.devicecoherent ||
547 coherentFlags.queuefamilycoherent ||
548 coherentFlags.workgroupcoherent ||
549 coherentFlags.subgroupcoherent) {
550 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
551 spv::MemoryAccessMakePointerVisibleKHRMask;
552 }
553 if (coherentFlags.nonprivate) {
554 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
555 }
556 if (coherentFlags.volatil) {
557 mask = mask | spv::MemoryAccessVolatileMask;
558 }
559 if (mask != spv::MemoryAccessMaskNone) {
560 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
561 }
John Kessenichb9197c82019-08-11 07:41:45 -0600562#endif
563
Jeff Bolz36831c92018-09-05 10:11:41 -0500564 return mask;
565}
566
John Kessenichb9197c82019-08-11 07:41:45 -0600567spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(
568 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500569{
Jeff Bolz36831c92018-09-05 10:11:41 -0500570 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600571
572#ifndef GLSLANG_WEB
573 if (!glslangIntermediate->usingVulkanMemoryModel())
574 return mask;
575
Jeff Bolz36831c92018-09-05 10:11:41 -0500576 if (coherentFlags.volatil ||
577 coherentFlags.coherent ||
578 coherentFlags.devicecoherent ||
579 coherentFlags.queuefamilycoherent ||
580 coherentFlags.workgroupcoherent ||
581 coherentFlags.subgroupcoherent) {
582 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
583 spv::ImageOperandsMakeTexelVisibleKHRMask;
584 }
585 if (coherentFlags.nonprivate) {
586 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
587 }
588 if (coherentFlags.volatil) {
589 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
590 }
591 if (mask != spv::ImageOperandsMaskNone) {
592 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
593 }
John Kessenichb9197c82019-08-11 07:41:45 -0600594#endif
595
Jeff Bolz36831c92018-09-05 10:11:41 -0500596 return mask;
597}
598
599spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
600{
John Kessenichb9197c82019-08-11 07:41:45 -0600601 spv::Builder::AccessChain::CoherentFlags flags = {};
602#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -0500603 flags.coherent = type.getQualifier().coherent;
604 flags.devicecoherent = type.getQualifier().devicecoherent;
605 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
606 // shared variables are implicitly workgroupcoherent in GLSL.
607 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
608 type.getQualifier().storage == glslang::EvqShared;
609 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600610 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500611 // *coherent variables are implicitly nonprivate in GLSL
612 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500613 flags.subgroupcoherent ||
614 flags.workgroupcoherent ||
615 flags.queuefamilycoherent ||
616 flags.devicecoherent ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600617 flags.coherent ||
618 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500619 flags.isImage = type.getBasicType() == glslang::EbtSampler;
John Kessenichb9197c82019-08-11 07:41:45 -0600620#endif
Jeff Bolz36831c92018-09-05 10:11:41 -0500621 return flags;
622}
623
John Kessenichb9197c82019-08-11 07:41:45 -0600624spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(
625 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500626{
John Kessenichb9197c82019-08-11 07:41:45 -0600627 spv::Scope scope = spv::ScopeMax;
628
629#ifndef GLSLANG_WEB
Jeff Bolz38cbad12019-03-05 14:40:07 -0600630 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500631 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
632 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
633 } else if (coherentFlags.devicecoherent) {
634 scope = spv::ScopeDevice;
635 } else if (coherentFlags.queuefamilycoherent) {
636 scope = spv::ScopeQueueFamilyKHR;
637 } else if (coherentFlags.workgroupcoherent) {
638 scope = spv::ScopeWorkgroup;
639 } else if (coherentFlags.subgroupcoherent) {
640 scope = spv::ScopeSubgroup;
Jeff Bolz36831c92018-09-05 10:11:41 -0500641 }
642 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
643 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
644 }
John Kessenichb9197c82019-08-11 07:41:45 -0600645#endif
646
Jeff Bolz36831c92018-09-05 10:11:41 -0500647 return scope;
648}
649
David Netoa901ffe2016-06-08 14:11:40 +0100650// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
651// associated capabilities when required. For some built-in variables, a capability
652// is generated only when using the variable in an executable instruction, but not when
653// just declaring a struct member variable with it. This is true for PointSize,
654// ClipDistance, and CullDistance.
John Kessenich8985fc92020-03-03 10:25:07 -0700655spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn,
656 bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600657{
658 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700659 case glslang::EbvPointSize:
John Kessenich155d3512019-08-08 23:29:20 -0600660#ifndef GLSLANG_WEB
John Kessenich78a45572016-07-08 14:05:15 -0600661 // Defer adding the capability until the built-in is actually used.
662 if (! memberDeclaration) {
663 switch (glslangIntermediate->getStage()) {
664 case EShLangGeometry:
665 builder.addCapability(spv::CapabilityGeometryPointSize);
666 break;
667 case EShLangTessControl:
668 case EShLangTessEvaluation:
669 builder.addCapability(spv::CapabilityTessellationPointSize);
670 break;
671 default:
672 break;
673 }
John Kessenich92187592016-02-01 13:45:25 -0700674 }
John Kessenich155d3512019-08-08 23:29:20 -0600675#endif
John Kessenich92187592016-02-01 13:45:25 -0700676 return spv::BuiltInPointSize;
677
John Kessenicha28f7a72019-08-06 07:00:58 -0600678 case glslang::EbvPosition: return spv::BuiltInPosition;
679 case glslang::EbvVertexId: return spv::BuiltInVertexId;
680 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
681 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
682 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
683
684 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
685 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
686 case glslang::EbvFace: return spv::BuiltInFrontFacing;
687 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
688
John Kessenich3dd1ce52019-10-17 07:08:40 -0600689 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
690 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
691 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
692 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
693 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
694 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
695
John Kessenicha28f7a72019-08-06 07:00:58 -0600696#ifndef GLSLANG_WEB
John Kessenichebb50532016-05-16 19:22:05 -0600697 // These *Distance capabilities logically belong here, but if the member is declared and
698 // then never used, consumers of SPIR-V prefer the capability not be declared.
699 // They are now generated when used, rather than here when declared.
700 // Potentially, the specification should be more clear what the minimum
701 // use needed is to trigger the capability.
702 //
John Kessenich92187592016-02-01 13:45:25 -0700703 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100704 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800705 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700706 return spv::BuiltInClipDistance;
707
708 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100709 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800710 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700711 return spv::BuiltInCullDistance;
712
713 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600714 builder.addCapability(spv::CapabilityMultiViewport);
715 if (glslangIntermediate->getStage() == EShLangVertex ||
716 glslangIntermediate->getStage() == EShLangTessControl ||
717 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800718
John Kessenich8317e6c2019-08-18 23:58:08 -0600719 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600720 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800721 }
John Kessenich92187592016-02-01 13:45:25 -0700722 return spv::BuiltInViewportIndex;
723
John Kessenich5e801132016-02-15 11:09:46 -0700724 case glslang::EbvSampleId:
725 builder.addCapability(spv::CapabilitySampleRateShading);
726 return spv::BuiltInSampleId;
727
728 case glslang::EbvSamplePosition:
729 builder.addCapability(spv::CapabilitySampleRateShading);
730 return spv::BuiltInSamplePosition;
731
732 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700733 return spv::BuiltInSampleMask;
734
John Kessenich78a45572016-07-08 14:05:15 -0600735 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700736 if (glslangIntermediate->getStage() == EShLangMeshNV) {
737 return spv::BuiltInLayer;
738 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600739 builder.addCapability(spv::CapabilityGeometry);
740 if (glslangIntermediate->getStage() == EShLangVertex ||
741 glslangIntermediate->getStage() == EShLangTessControl ||
742 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800743
John Kessenich8317e6c2019-08-18 23:58:08 -0600744 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600745 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800746 }
John Kessenich78a45572016-07-08 14:05:15 -0600747 return spv::BuiltInLayer;
748
John Kessenichda581a22015-10-14 14:10:30 -0600749 case glslang::EbvBaseVertex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600750 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800751 builder.addCapability(spv::CapabilityDrawParameters);
752 return spv::BuiltInBaseVertex;
753
John Kessenichda581a22015-10-14 14:10:30 -0600754 case glslang::EbvBaseInstance:
John Kessenich8317e6c2019-08-18 23:58:08 -0600755 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800756 builder.addCapability(spv::CapabilityDrawParameters);
757 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200758
John Kessenichda581a22015-10-14 14:10:30 -0600759 case glslang::EbvDrawId:
John Kessenich8317e6c2019-08-18 23:58:08 -0600760 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800761 builder.addCapability(spv::CapabilityDrawParameters);
762 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200763
764 case glslang::EbvPrimitiveId:
765 if (glslangIntermediate->getStage() == EShLangFragment)
766 builder.addCapability(spv::CapabilityGeometry);
767 return spv::BuiltInPrimitiveId;
768
Rex Xu37cdcee2017-06-29 17:46:34 +0800769 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800770 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
771 builder.addCapability(spv::CapabilityStencilExportEXT);
772 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800773
John Kessenich140f3df2015-06-26 16:58:36 -0600774 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600775 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
776 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
777 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
778 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
John Kessenich140f3df2015-06-26 16:58:36 -0600779 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
Rex Xu51596642016-09-21 18:56:12 +0800780
Rex Xu574ab042016-04-14 16:53:07 +0800781 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800782 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800783 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
784 return spv::BuiltInSubgroupSize;
785
Rex Xu574ab042016-04-14 16:53:07 +0800786 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800787 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800788 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
789 return spv::BuiltInSubgroupLocalInvocationId;
790
Rex Xu574ab042016-04-14 16:53:07 +0800791 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800792 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
793 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600794 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800795
Rex Xu574ab042016-04-14 16:53:07 +0800796 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800797 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
798 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600799 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800800
Rex Xu574ab042016-04-14 16:53:07 +0800801 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800802 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
803 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600804 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800805
Rex Xu574ab042016-04-14 16:53:07 +0800806 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800807 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
808 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600809 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800810
Rex Xu574ab042016-04-14 16:53:07 +0800811 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800812 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
813 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600814 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800815
John Kessenich66011cb2018-03-06 16:12:04 -0700816 case glslang::EbvNumSubgroups:
817 builder.addCapability(spv::CapabilityGroupNonUniform);
818 return spv::BuiltInNumSubgroups;
819
820 case glslang::EbvSubgroupID:
821 builder.addCapability(spv::CapabilityGroupNonUniform);
822 return spv::BuiltInSubgroupId;
823
824 case glslang::EbvSubgroupSize2:
825 builder.addCapability(spv::CapabilityGroupNonUniform);
826 return spv::BuiltInSubgroupSize;
827
828 case glslang::EbvSubgroupInvocation2:
829 builder.addCapability(spv::CapabilityGroupNonUniform);
830 return spv::BuiltInSubgroupLocalInvocationId;
831
832 case glslang::EbvSubgroupEqMask2:
833 builder.addCapability(spv::CapabilityGroupNonUniform);
834 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
835 return spv::BuiltInSubgroupEqMask;
836
837 case glslang::EbvSubgroupGeMask2:
838 builder.addCapability(spv::CapabilityGroupNonUniform);
839 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
840 return spv::BuiltInSubgroupGeMask;
841
842 case glslang::EbvSubgroupGtMask2:
843 builder.addCapability(spv::CapabilityGroupNonUniform);
844 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
845 return spv::BuiltInSubgroupGtMask;
846
847 case glslang::EbvSubgroupLeMask2:
848 builder.addCapability(spv::CapabilityGroupNonUniform);
849 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
850 return spv::BuiltInSubgroupLeMask;
851
852 case glslang::EbvSubgroupLtMask2:
853 builder.addCapability(spv::CapabilityGroupNonUniform);
854 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
855 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600856
Rex Xu17ff3432016-10-14 17:41:45 +0800857 case glslang::EbvBaryCoordNoPersp:
858 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
859 return spv::BuiltInBaryCoordNoPerspAMD;
860
861 case glslang::EbvBaryCoordNoPerspCentroid:
862 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
863 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
864
865 case glslang::EbvBaryCoordNoPerspSample:
866 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
867 return spv::BuiltInBaryCoordNoPerspSampleAMD;
868
869 case glslang::EbvBaryCoordSmooth:
870 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
871 return spv::BuiltInBaryCoordSmoothAMD;
872
873 case glslang::EbvBaryCoordSmoothCentroid:
874 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
875 return spv::BuiltInBaryCoordSmoothCentroidAMD;
876
877 case glslang::EbvBaryCoordSmoothSample:
878 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
879 return spv::BuiltInBaryCoordSmoothSampleAMD;
880
881 case glslang::EbvBaryCoordPullModel:
882 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
883 return spv::BuiltInBaryCoordPullModelAMD;
chaoc771d89f2017-01-13 01:10:53 -0800884
John Kessenich6c8aaac2017-02-27 01:20:51 -0700885 case glslang::EbvDeviceIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600886 builder.addIncorporatedExtension(spv::E_SPV_KHR_device_group, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700887 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700888 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700889
890 case glslang::EbvViewIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600891 builder.addIncorporatedExtension(spv::E_SPV_KHR_multiview, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700892 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700893 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700894
Daniel Koch5154db52018-11-26 10:01:58 -0500895 case glslang::EbvFragSizeEXT:
896 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
897 builder.addCapability(spv::CapabilityFragmentDensityEXT);
898 return spv::BuiltInFragSizeEXT;
899
900 case glslang::EbvFragInvocationCountEXT:
901 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
902 builder.addCapability(spv::CapabilityFragmentDensityEXT);
903 return spv::BuiltInFragInvocationCountEXT;
904
chaoc771d89f2017-01-13 01:10:53 -0800905 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800906 if (!memberDeclaration) {
907 builder.addExtension(spv::E_SPV_NV_viewport_array2);
908 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
909 }
chaoc771d89f2017-01-13 01:10:53 -0800910 return spv::BuiltInViewportMaskNV;
911 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800912 if (!memberDeclaration) {
913 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
914 builder.addCapability(spv::CapabilityShaderStereoViewNV);
915 }
chaoc771d89f2017-01-13 01:10:53 -0800916 return spv::BuiltInSecondaryPositionNV;
917 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800918 if (!memberDeclaration) {
919 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
920 builder.addCapability(spv::CapabilityShaderStereoViewNV);
921 }
chaoc771d89f2017-01-13 01:10:53 -0800922 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800923 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800924 if (!memberDeclaration) {
925 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
926 builder.addCapability(spv::CapabilityPerViewAttributesNV);
927 }
chaocdf3956c2017-02-14 14:52:34 -0800928 return spv::BuiltInPositionPerViewNV;
929 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800930 if (!memberDeclaration) {
931 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
932 builder.addCapability(spv::CapabilityPerViewAttributesNV);
933 }
chaocdf3956c2017-02-14 14:52:34 -0800934 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700935 case glslang::EbvFragFullyCoveredNV:
936 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
937 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
938 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700939 case glslang::EbvFragmentSizeNV:
940 builder.addExtension(spv::E_SPV_NV_shading_rate);
941 builder.addCapability(spv::CapabilityShadingRateNV);
942 return spv::BuiltInFragmentSizeNV;
943 case glslang::EbvInvocationsPerPixelNV:
944 builder.addExtension(spv::E_SPV_NV_shading_rate);
945 builder.addCapability(spv::CapabilityShadingRateNV);
946 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700947
Daniel Koch593a4e02019-05-27 16:46:31 -0400948 // ray tracing
Chao Chenb50c02e2018-09-19 11:42:24 -0700949 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700950 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700951 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700952 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700953 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700954 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700955 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700956 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700957 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700958 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700959 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700960 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700961 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700962 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700963 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700964 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700965 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700966 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700967 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700968 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700969 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700970 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700971 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700972 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700973 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700974 return spv::BuiltInWorldToObjectNV;
975 case glslang::EbvIncomingRayFlagsNV:
976 return spv::BuiltInIncomingRayFlagsNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400977
978 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700979 case glslang::EbvBaryCoordNV:
980 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
981 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
982 return spv::BuiltInBaryCoordNV;
983 case glslang::EbvBaryCoordNoPerspNV:
984 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
985 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
986 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400987
988 // mesh shaders
989 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700990 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400991 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700992 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400993 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700994 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400995 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700996 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400997 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700998 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400999 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07001000 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001001 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001002 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001003 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -07001004 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch2cb2f192019-06-04 08:43:32 -04001005
1006 // sm builtins
1007 case glslang::EbvWarpsPerSM:
1008 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1009 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1010 return spv::BuiltInWarpsPerSMNV;
1011 case glslang::EbvSMCount:
1012 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1013 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1014 return spv::BuiltInSMCountNV;
1015 case glslang::EbvWarpID:
1016 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1017 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1018 return spv::BuiltInWarpIDNV;
1019 case glslang::EbvSMID:
1020 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1021 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1022 return spv::BuiltInSMIDNV;
John Kessenicha28f7a72019-08-06 07:00:58 -06001023#endif
1024
Rex Xu3e783f92017-02-22 16:44:48 +08001025 default:
1026 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -06001027 }
1028}
1029
Rex Xufc618912015-09-09 16:42:49 +08001030// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -07001031spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +08001032{
1033 assert(type.getBasicType() == glslang::EbtSampler);
1034
John Kessenichb9197c82019-08-11 07:41:45 -06001035#ifdef GLSLANG_WEB
1036 return spv::ImageFormatUnknown;
1037#endif
1038
John Kessenich5d0fa972016-02-15 11:57:00 -07001039 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -06001040 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -07001041 case glslang::ElfRg32f:
1042 case glslang::ElfRg16f:
1043 case glslang::ElfR11fG11fB10f:
1044 case glslang::ElfR16f:
1045 case glslang::ElfRgba16:
1046 case glslang::ElfRgb10A2:
1047 case glslang::ElfRg16:
1048 case glslang::ElfRg8:
1049 case glslang::ElfR16:
1050 case glslang::ElfR8:
1051 case glslang::ElfRgba16Snorm:
1052 case glslang::ElfRg16Snorm:
1053 case glslang::ElfRg8Snorm:
1054 case glslang::ElfR16Snorm:
1055 case glslang::ElfR8Snorm:
1056
1057 case glslang::ElfRg32i:
1058 case glslang::ElfRg16i:
1059 case glslang::ElfRg8i:
1060 case glslang::ElfR16i:
1061 case glslang::ElfR8i:
1062
1063 case glslang::ElfRgb10a2ui:
1064 case glslang::ElfRg32ui:
1065 case glslang::ElfRg16ui:
1066 case glslang::ElfRg8ui:
1067 case glslang::ElfR16ui:
1068 case glslang::ElfR8ui:
1069 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1070 break;
1071
1072 default:
1073 break;
1074 }
1075
1076 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001077 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001078 case glslang::ElfNone: return spv::ImageFormatUnknown;
1079 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1080 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1081 case glslang::ElfR32f: return spv::ImageFormatR32f;
1082 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1083 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1084 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1085 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1086 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1087 case glslang::ElfR16f: return spv::ImageFormatR16f;
1088 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1089 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1090 case glslang::ElfRg16: return spv::ImageFormatRg16;
1091 case glslang::ElfRg8: return spv::ImageFormatRg8;
1092 case glslang::ElfR16: return spv::ImageFormatR16;
1093 case glslang::ElfR8: return spv::ImageFormatR8;
1094 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1095 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1096 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1097 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1098 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1099 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1100 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1101 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1102 case glslang::ElfR32i: return spv::ImageFormatR32i;
1103 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1104 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1105 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1106 case glslang::ElfR16i: return spv::ImageFormatR16i;
1107 case glslang::ElfR8i: return spv::ImageFormatR8i;
1108 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1109 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1110 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1111 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1112 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1113 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1114 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1115 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1116 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1117 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001118 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001119 }
1120}
1121
John Kessenich8985fc92020-03-03 10:25:07 -07001122spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(
1123 const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001124{
John Kesseniche18fd202018-01-30 11:01:39 -07001125 if (selectionNode.getFlatten())
1126 return spv::SelectionControlFlattenMask;
1127 if (selectionNode.getDontFlatten())
1128 return spv::SelectionControlDontFlattenMask;
1129 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001130}
1131
John Kessenich8985fc92020-03-03 10:25:07 -07001132spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode)
1133 const
steve-lunargf1709e72017-05-02 20:14:50 -06001134{
John Kesseniche18fd202018-01-30 11:01:39 -07001135 if (switchNode.getFlatten())
1136 return spv::SelectionControlFlattenMask;
1137 if (switchNode.getDontFlatten())
1138 return spv::SelectionControlDontFlattenMask;
1139 return spv::SelectionControlMaskNone;
1140}
1141
John Kessenicha2858d92018-01-31 08:11:18 -07001142// return a non-0 dependency if the dependency argument must be set
1143spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001144 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001145{
1146 spv::LoopControlMask control = spv::LoopControlMaskNone;
1147
1148 if (loopNode.getDontUnroll())
1149 control = control | spv::LoopControlDontUnrollMask;
1150 if (loopNode.getUnroll())
1151 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001152 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001153 control = control | spv::LoopControlDependencyInfiniteMask;
1154 else if (loopNode.getLoopDependency() > 0) {
1155 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001156 operands.push_back((unsigned int)loopNode.getLoopDependency());
1157 }
1158 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1159 if (loopNode.getMinIterations() > 0) {
1160 control = control | spv::LoopControlMinIterationsMask;
1161 operands.push_back(loopNode.getMinIterations());
1162 }
1163 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1164 control = control | spv::LoopControlMaxIterationsMask;
1165 operands.push_back(loopNode.getMaxIterations());
1166 }
1167 if (loopNode.getIterationMultiple() > 1) {
1168 control = control | spv::LoopControlIterationMultipleMask;
1169 operands.push_back(loopNode.getIterationMultiple());
1170 }
1171 if (loopNode.getPeelCount() > 0) {
1172 control = control | spv::LoopControlPeelCountMask;
1173 operands.push_back(loopNode.getPeelCount());
1174 }
1175 if (loopNode.getPartialCount() > 0) {
1176 control = control | spv::LoopControlPartialCountMask;
1177 operands.push_back(loopNode.getPartialCount());
1178 }
John Kessenicha2858d92018-01-31 08:11:18 -07001179 }
John Kesseniche18fd202018-01-30 11:01:39 -07001180
1181 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001182}
1183
John Kessenicha5c5fb62017-05-05 05:09:58 -06001184// Translate glslang type to SPIR-V storage class.
1185spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1186{
1187 if (type.getQualifier().isPipeInput())
1188 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001189 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001190 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001191
1192 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001193 type.getQualifier().storage == glslang::EvqUniform) {
John Kessenichdeec1932019-08-13 08:00:30 -06001194 if (type.isAtomic())
John Kessenichbed4e4f2017-09-08 02:38:07 -06001195 return spv::StorageClassAtomicCounter;
1196 if (type.containsOpaque())
1197 return spv::StorageClassUniformConstant;
1198 }
1199
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001200 if (type.getQualifier().isUniformOrBuffer() &&
John Kessenichdeec1932019-08-13 08:00:30 -06001201 type.getQualifier().isShaderRecordNV()) {
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001202 return spv::StorageClassShaderRecordBufferNV;
1203 }
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001204
John Kessenichbed4e4f2017-09-08 02:38:07 -06001205 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001206 builder.addIncorporatedExtension(spv::E_SPV_KHR_storage_buffer_storage_class, spv::Spv_1_3);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001207 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001208 }
1209
1210 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich7015bd62019-08-01 03:28:08 -06001211 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001212 return spv::StorageClassPushConstant;
1213 if (type.getBasicType() == glslang::EbtBlock)
1214 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001215 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001216 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001217
1218 switch (type.getQualifier().storage) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001219 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1220 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1221 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenichdeec1932019-08-13 08:00:30 -06001222 case glslang::EvqShared: return spv::StorageClassWorkgroup;
John Kessenich3dd1ce52019-10-17 07:08:40 -06001223#ifndef GLSLANG_WEB
Ashwin Leleff1783d2018-10-22 16:41:44 -07001224 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1225 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1226 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1227 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1228 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001229#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001230 default:
1231 assert(0);
1232 break;
1233 }
1234
1235 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001236}
1237
John Kessenich5611c6d2018-04-05 11:25:02 -06001238// Add capabilities pertaining to how an array is indexed.
1239void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1240 const glslang::TType& indexType)
1241{
John Kessenichb9197c82019-08-11 07:41:45 -06001242#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06001243 if (indexType.getQualifier().isNonUniform()) {
1244 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001245 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001246 if (baseType.getBasicType() == glslang::EbtSampler) {
1247 if (baseType.getQualifier().hasAttachment())
1248 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001249 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001250 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001251 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001252 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1253 else if (baseType.isImage())
1254 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1255 else if (baseType.isTexture())
1256 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1257 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1258 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1259 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1260 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1261 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1262 }
1263 } else {
1264 // assume a dynamically uniform index
1265 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001266 if (baseType.getQualifier().hasAttachment()) {
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::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001269 } else if (baseType.isImage() && 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::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001272 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001273 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001274 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001275 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001276 }
1277 }
John Kessenichb9197c82019-08-11 07:41:45 -06001278#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06001279}
1280
qining25262b32016-05-06 17:25:16 -04001281// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001282// descriptor set.
1283bool IsDescriptorResource(const glslang::TType& type)
1284{
John Kessenichf7497e22016-03-08 21:36:22 -07001285 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001286 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001287 return type.getQualifier().isUniformOrBuffer() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001288 ! type.getQualifier().isShaderRecordNV() &&
1289 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001290
1291 // non block...
1292 // basically samplerXXX/subpass/sampler/texture are all included
1293 // if they are the global-scope-class, not the function parameter
1294 // (or local, if they ever exist) class.
1295 if (type.getBasicType() == glslang::EbtSampler)
1296 return type.getQualifier().isUniformOrBuffer();
1297
1298 // None of the above.
1299 return false;
1300}
1301
John Kesseniche0b6cad2015-12-24 10:30:13 -07001302void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1303{
1304 if (child.layoutMatrix == glslang::ElmNone)
1305 child.layoutMatrix = parent.layoutMatrix;
1306
1307 if (parent.invariant)
1308 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001309 if (parent.flat)
1310 child.flat = true;
1311 if (parent.centroid)
1312 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001313#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001314 if (parent.nopersp)
1315 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001316 if (parent.explicitInterp)
1317 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001318 if (parent.perPrimitiveNV)
1319 child.perPrimitiveNV = true;
1320 if (parent.perViewNV)
1321 child.perViewNV = true;
1322 if (parent.perTaskNV)
1323 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001324 if (parent.patch)
1325 child.patch = true;
1326 if (parent.sample)
1327 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001328 if (parent.coherent)
1329 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001330 if (parent.devicecoherent)
1331 child.devicecoherent = true;
1332 if (parent.queuefamilycoherent)
1333 child.queuefamilycoherent = true;
1334 if (parent.workgroupcoherent)
1335 child.workgroupcoherent = true;
1336 if (parent.subgroupcoherent)
1337 child.subgroupcoherent = true;
1338 if (parent.nonprivate)
1339 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001340 if (parent.volatil)
1341 child.volatil = true;
1342 if (parent.restrict)
1343 child.restrict = true;
1344 if (parent.readonly)
1345 child.readonly = true;
1346 if (parent.writeonly)
1347 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001348#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001349}
1350
John Kessenichf2b7f332016-09-01 17:05:23 -06001351bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001352{
John Kessenich7b9fa252016-01-21 18:56:57 -07001353 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001354 // - struct members might inherit from a struct declaration
1355 // (note that non-block structs don't explicitly inherit,
1356 // only implicitly, meaning no decoration involved)
1357 // - affect decorations on the struct members
1358 // (note smooth does not, and expecting something like volatile
1359 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001360 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001361 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001362}
1363
John Kessenich140f3df2015-06-26 16:58:36 -06001364//
1365// Implement the TGlslangToSpvTraverser class.
1366//
1367
John Kessenich8985fc92020-03-03 10:25:07 -07001368TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion,
1369 const glslang::TIntermediate* glslangIntermediate,
1370 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options) :
1371 TIntermTraverser(true, false, true),
1372 options(options),
1373 shaderEntry(nullptr), currentFunction(nullptr),
1374 sequenceDepth(0), logger(buildLogger),
1375 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
1376 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
1377 glslangIntermediate(glslangIntermediate),
1378 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp())
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
Chao Chenb50c02e2018-09-19 11:42:24 -07001602 case EShLangRayGenNV:
1603 case EShLangIntersectNV:
1604 case EShLangAnyHitNV:
1605 case EShLangClosestHitNV:
1606 case EShLangMissNV:
1607 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001608 builder.addCapability(spv::CapabilityRayTracingNV);
1609 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001610 break;
Chao Chen3c366992018-09-19 11:41:59 -07001611 case EShLangTaskNV:
1612 case EShLangMeshNV:
1613 builder.addCapability(spv::CapabilityMeshShadingNV);
1614 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1615 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1616 glslangIntermediate->getLocalSize(1),
1617 glslangIntermediate->getLocalSize(2));
1618 if (glslangIntermediate->getStage() == EShLangMeshNV) {
John Kessenich8985fc92020-03-03 10:25:07 -07001619 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1620 glslangIntermediate->getVertices());
1621 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV,
1622 glslangIntermediate->getPrimitives());
Chao Chen3c366992018-09-19 11:41:59 -07001623
1624 switch (glslangIntermediate->getOutputPrimitive()) {
1625 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1626 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1627 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1628 default: mode = spv::ExecutionModeMax; break;
1629 }
1630 if (mode != spv::ExecutionModeMax)
1631 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1632 }
1633 break;
1634#endif
1635
John Kessenich140f3df2015-06-26 16:58:36 -06001636 default:
1637 break;
1638 }
John Kessenich140f3df2015-06-26 16:58:36 -06001639}
1640
John Kessenichfca82622016-11-26 13:23:20 -07001641// Finish creating SPV, after the traversal is complete.
1642void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001643{
John Kessenichf04c51b2018-08-03 15:56:12 -06001644 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001645 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001646 builder.setBuildPoint(shaderEntry->getLastBlock());
1647 builder.leaveFunction();
1648 }
1649
John Kessenich7ba63412015-12-20 17:37:07 -07001650 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001651 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1652 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001653
David Neto8c3d5b42019-10-21 14:50:31 -04001654 // Add capabilities, extensions, remove unneeded decorations, etc.,
John Kessenichf04c51b2018-08-03 15:56:12 -06001655 // based on the resulting SPIR-V.
David Neto8c3d5b42019-10-21 14:50:31 -04001656 // Note: WebGPU code generation must have the opportunity to aggressively
1657 // prune unreachable merge blocks and continue targets.
John Kessenichf04c51b2018-08-03 15:56:12 -06001658 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001659}
1660
John Kessenichfca82622016-11-26 13:23:20 -07001661// Write the SPV into 'out'.
1662void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001663{
John Kessenichfca82622016-11-26 13:23:20 -07001664 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001665}
1666
1667//
1668// Implement the traversal functions.
1669//
1670// Return true from interior nodes to have the external traversal
1671// continue on to children. Return false if children were
1672// already processed.
1673//
1674
1675//
qining25262b32016-05-06 17:25:16 -04001676// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001677// - uniform/input reads
1678// - output writes
1679// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1680// - something simple that degenerates into the last bullet
1681//
1682void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1683{
qining75d1d802016-04-06 14:42:01 -04001684 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
Roy05a5b532020-01-03 16:21:34 +08001685 if (symbol->getType().isStruct())
1686 glslangTypeToIdMap[symbol->getType().getStruct()] = symbol->getId();
1687
qining75d1d802016-04-06 14:42:01 -04001688 if (symbol->getType().getQualifier().isSpecConstant())
1689 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1690
John Kessenich140f3df2015-06-26 16:58:36 -06001691 // getSymbolId() will set up all the IO decorations on the first call.
1692 // Formal function parameters were mapped during makeFunctions().
1693 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001694
John Kessenich7ba63412015-12-20 17:37:07 -07001695 if (builder.isPointer(id)) {
John Kessenich9c14f772019-06-17 08:38:35 -06001696 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
John Kessenich7c7731e2019-01-04 16:47:06 +07001697 // Consider adding to the OpEntryPoint interface list.
1698 // Only looking at structures if they have at least one member.
1699 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1700 spv::StorageClass sc = builder.getStorageClass(id);
1701 // Before SPIR-V 1.4, we only want to include Input and Output.
1702 // Starting with SPIR-V 1.4, we want all globals.
1703 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1704 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001705 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001706 }
John Kessenich5f77d862017-09-19 11:09:59 -06001707 }
John Kessenich9c14f772019-06-17 08:38:35 -06001708
1709 // If the SPIR-V type is required to be different than the AST type,
1710 // translate now from the SPIR-V type to the AST type, for the consuming
1711 // operation.
1712 // Note this turns it from an l-value to an r-value.
1713 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1714 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1715 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001716 }
1717
1718 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001719 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001720 // Prepare to generate code for the access
1721
1722 // L-value chains will be computed left to right. We're on the symbol now,
1723 // which is the left-most part of the access chain, so now is "clear" time,
1724 // followed by setting the base.
1725 builder.clearAccessChain();
1726
1727 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001728 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001729 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001730 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001731 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001732 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001733 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001734 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001735 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1736 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001737 builder.setAccessChainRValue(id);
1738 else
1739 builder.setAccessChainLValue(id);
1740 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001741
John Kessenichb9197c82019-08-11 07:41:45 -06001742#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001743 // Process linkage-only nodes for any special additional interface work.
1744 if (linkageOnly) {
1745 if (glslangIntermediate->getHlslFunctionality1()) {
1746 // Map implicit counter buffers to their originating buffers, which should have been
1747 // seen by now, given earlier pruning of unused counters, and preservation of order
1748 // of declaration.
1749 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1750 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1751 // Save possible originating buffers for counter buffers, keyed by
1752 // making the potential counter-buffer name.
1753 std::string keyName = symbol->getName().c_str();
1754 keyName = glslangIntermediate->addCounterBufferName(keyName);
1755 counterOriginator[keyName] = symbol;
1756 } else {
1757 // Handle a counter buffer, by finding the saved originating buffer.
1758 std::string keyName = symbol->getName().c_str();
1759 auto it = counterOriginator.find(keyName);
1760 if (it != counterOriginator.end()) {
1761 id = getSymbolId(it->second);
1762 if (id != spv::NoResult) {
1763 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001764 if (counterId != spv::NoResult) {
1765 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001766 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001767 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001768 }
1769 }
1770 }
1771 }
1772 }
1773 }
John Kessenich155d3512019-08-08 23:29:20 -06001774#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001775}
1776
1777bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1778{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001779 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Roy05a5b532020-01-03 16:21:34 +08001780 if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
1781 glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
1782 }
1783 if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
1784 glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
1785 }
John Kesseniche485c7a2017-05-31 18:50:53 -06001786
qining40887662016-04-03 22:20:42 -04001787 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1788 if (node->getType().getQualifier().isSpecConstant())
1789 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1790
John Kessenich140f3df2015-06-26 16:58:36 -06001791 // First, handle special cases
1792 switch (node->getOp()) {
1793 case glslang::EOpAssign:
1794 case glslang::EOpAddAssign:
1795 case glslang::EOpSubAssign:
1796 case glslang::EOpMulAssign:
1797 case glslang::EOpVectorTimesMatrixAssign:
1798 case glslang::EOpVectorTimesScalarAssign:
1799 case glslang::EOpMatrixTimesScalarAssign:
1800 case glslang::EOpMatrixTimesMatrixAssign:
1801 case glslang::EOpDivAssign:
1802 case glslang::EOpModAssign:
1803 case glslang::EOpAndAssign:
1804 case glslang::EOpInclusiveOrAssign:
1805 case glslang::EOpExclusiveOrAssign:
1806 case glslang::EOpLeftShiftAssign:
1807 case glslang::EOpRightShiftAssign:
1808 // A bin-op assign "a += b" means the same thing as "a = a + b"
1809 // where a is evaluated before b. For a simple assignment, GLSL
1810 // says to evaluate the left before the right. So, always, left
1811 // node then right node.
1812 {
1813 // get the left l-value, save it away
1814 builder.clearAccessChain();
1815 node->getLeft()->traverse(this);
1816 spv::Builder::AccessChain lValue = builder.getAccessChain();
1817
1818 // evaluate the right
1819 builder.clearAccessChain();
1820 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001821 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001822
1823 if (node->getOp() != glslang::EOpAssign) {
1824 // the left is also an r-value
1825 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001826 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001827
1828 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001829 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001830 TranslateNoContractionDecoration(node->getType().getQualifier()),
1831 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001832 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001833 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1834 node->getType().getBasicType());
1835
1836 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001837 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001838 }
1839
1840 // store the result
1841 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001842 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001843
1844 // assignments are expressions having an rValue after they are evaluated...
1845 builder.clearAccessChain();
1846 builder.setAccessChainRValue(rValue);
1847 }
1848 return false;
1849 case glslang::EOpIndexDirect:
1850 case glslang::EOpIndexDirectStruct:
1851 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001852 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001853 // Get the left part of the access chain.
1854 node->getLeft()->traverse(this);
1855
1856 // Add the next element in the chain
1857
David Netoa901ffe2016-06-08 14:11:40 +01001858 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001859 if (! node->getLeft()->getType().isArray() &&
1860 node->getLeft()->getType().isVector() &&
1861 node->getOp() == glslang::EOpIndexDirect) {
1862 // This is essentially a hard-coded vector swizzle of size 1,
1863 // so short circuit the access-chain stuff with a swizzle.
1864 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001865 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001866 int dummySize;
1867 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1868 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001869 glslangIntermediate->getBaseAlignmentScalar(
1870 node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001871 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001872
1873 // Load through a block reference is performed with a dot operator that
1874 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1875 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001876 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001877 !node->getLeft()->getType().isArray() &&
1878 node->getOp() == glslang::EOpIndexDirectStruct)
1879 {
1880 spv::Id left = accessChainLoad(node->getLeft()->getType());
1881 builder.clearAccessChain();
1882 builder.setAccessChainLValue(left);
1883 }
1884
David Netoa901ffe2016-06-08 14:11:40 +01001885 int spvIndex = glslangIndex;
1886 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1887 node->getOp() == glslang::EOpIndexDirectStruct)
1888 {
1889 // This may be, e.g., an anonymous block-member selection, which generally need
1890 // index remapping due to hidden members in anonymous blocks.
Roy05a5b532020-01-03 16:21:34 +08001891 int glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
1892 if (memberRemapper.find(glslangId) != memberRemapper.end()) {
1893 std::vector<int>& remapper = memberRemapper[glslangId];
1894 assert(remapper.size() > 0);
1895 spvIndex = remapper[glslangIndex];
1896 }
David Netoa901ffe2016-06-08 14:11:40 +01001897 }
John Kessenichebb50532016-05-16 19:22:05 -06001898
David Netoa901ffe2016-06-08 14:11:40 +01001899 // normal case for indexing array or structure or block
John Kessenich8985fc92020-03-03 10:25:07 -07001900 builder.accessChainPush(builder.makeIntConstant(spvIndex),
1901 TranslateCoherent(node->getLeft()->getType()),
1902 node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001903
1904 // Add capabilities here for accessing PointSize and clip/cull distance.
1905 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001906 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001907 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001908 }
1909 }
1910 return false;
1911 case glslang::EOpIndexIndirect:
1912 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001913 // Array, matrix, or vector indirection with variable index.
1914 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001915 // matrices are arrays of vectors, so will also work for a matrix.
1916 // Will use the access chain's 'component' for variable index into a vector.
1917
1918 // This adapter is building access chains left to right.
1919 // Set up the access chain to the left.
1920 node->getLeft()->traverse(this);
1921
1922 // save it so that computing the right side doesn't trash it
1923 spv::Builder::AccessChain partial = builder.getAccessChain();
1924
1925 // compute the next index in the chain
1926 builder.clearAccessChain();
1927 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001928 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001929
John Kessenich5611c6d2018-04-05 11:25:02 -06001930 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1931
John Kessenich140f3df2015-06-26 16:58:36 -06001932 // restore the saved access chain
1933 builder.setAccessChain(partial);
1934
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001935 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1936 int dummySize;
1937 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1938 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001939 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1940 dummySize));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001941 } else
John Kessenich8985fc92020-03-03 10:25:07 -07001942 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()),
1943 node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001944 }
1945 return false;
1946 case glslang::EOpVectorSwizzle:
1947 {
1948 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001949 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001950 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001951 int dummySize;
1952 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1953 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001954 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1955 dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001956 }
1957 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001958 case glslang::EOpMatrixSwizzle:
1959 logger->missingFunctionality("matrix swizzle");
1960 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001961 case glslang::EOpLogicalOr:
1962 case glslang::EOpLogicalAnd:
1963 {
1964
1965 // These may require short circuiting, but can sometimes be done as straight
1966 // binary operations. The right operand must be short circuited if it has
1967 // side effects, and should probably be if it is complex.
1968 if (isTrivial(node->getRight()->getAsTyped()))
1969 break; // handle below as a normal binary operation
1970 // otherwise, we need to do dynamic short circuiting on the right operand
John Kessenich8985fc92020-03-03 10:25:07 -07001971 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(),
1972 *node->getRight()->getAsTyped());
John Kessenich7c1aa102015-10-15 13:29:11 -06001973 builder.clearAccessChain();
1974 builder.setAccessChainRValue(result);
1975 }
1976 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001977 default:
1978 break;
1979 }
1980
1981 // Assume generic binary op...
1982
John Kessenich32cfd492016-02-02 12:37:46 -07001983 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001984 builder.clearAccessChain();
1985 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001986 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001987
John Kessenich32cfd492016-02-02 12:37:46 -07001988 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001989 builder.clearAccessChain();
1990 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001991 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001992
John Kessenich32cfd492016-02-02 12:37:46 -07001993 // get result
John Kessenichead86222018-03-28 18:01:20 -06001994 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001995 TranslateNoContractionDecoration(node->getType().getQualifier()),
1996 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001997 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001998 convertGlslangToSpvType(node->getType()), left, right,
1999 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002000
John Kessenich50e57562015-12-21 21:21:11 -07002001 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06002002 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002003 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07002004 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06002005 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06002006 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06002007 return false;
2008 }
John Kessenich140f3df2015-06-26 16:58:36 -06002009}
2010
John Kessenich9c14f772019-06-17 08:38:35 -06002011// Figure out what, if any, type changes are needed when accessing a specific built-in.
2012// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
2013// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
2014std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(spv::BuiltIn builtIn,
2015 const glslang::TType& glslangType)
2016{
2017 switch(builtIn)
2018 {
2019 case spv::BuiltInSubgroupEqMask:
2020 case spv::BuiltInSubgroupGeMask:
2021 case spv::BuiltInSubgroupGtMask:
2022 case spv::BuiltInSubgroupLeMask:
2023 case spv::BuiltInSubgroupLtMask: {
2024 // these require changing a 64-bit scaler -> a vector of 32-bit components
2025 if (glslangType.isVector())
2026 break;
2027 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
2028 builder.makeUintType(64));
2029 return ret;
2030 }
2031 default:
2032 break;
2033 }
2034
2035 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2036 return ret;
2037}
2038
2039// For an object previously identified (see getForcedType() and forceType)
2040// as needing type translations, do the translation needed for a load, turning
2041// an L-value into in R-value.
2042spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2043{
2044 const auto forceIt = forceType.find(object);
2045 if (forceIt == forceType.end())
2046 return object;
2047
2048 spv::Id desiredTypeId = forceIt->second;
2049 spv::Id objectTypeId = builder.getTypeId(object);
2050 assert(builder.isPointerType(objectTypeId));
2051 objectTypeId = builder.getContainedTypeId(objectTypeId);
2052 if (builder.isVectorType(objectTypeId) &&
2053 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2054 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2055 // handle 32-bit v.xy* -> 64-bit
2056 builder.clearAccessChain();
2057 builder.setAccessChainLValue(object);
2058 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2059 std::vector<spv::Id> components;
2060 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2061 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2062
2063 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2064 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2065 builder.createCompositeConstruct(vecType, components));
2066 } else {
2067 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2068 }
2069 } else {
2070 logger->missingFunctionality("forcing non 32-bit vector type");
2071 }
2072
2073 return object;
2074}
2075
John Kessenich140f3df2015-06-26 16:58:36 -06002076bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2077{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002078 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002079
qining40887662016-04-03 22:20:42 -04002080 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2081 if (node->getType().getQualifier().isSpecConstant())
2082 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2083
John Kessenichfc51d282015-08-19 13:34:18 -06002084 spv::Id result = spv::NoResult;
2085
2086 // try texturing first
2087 result = createImageTextureFunctionCall(node);
2088 if (result != spv::NoResult) {
2089 builder.clearAccessChain();
2090 builder.setAccessChainRValue(result);
2091
2092 return false; // done with this node
2093 }
2094
2095 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002096
2097 if (node->getOp() == glslang::EOpArrayLength) {
2098 // Quite special; won't want to evaluate the operand.
2099
John Kessenich5611c6d2018-04-05 11:25:02 -06002100 // Currently, the front-end does not allow .length() on an array until it is sized,
2101 // except for the last block membeor of an SSBO.
2102 // TODO: If this changes, link-time sized arrays might show up here, and need their
2103 // size extracted.
2104
John Kessenichc9a80832015-09-12 12:17:44 -06002105 // Normal .length() would have been constant folded by the front-end.
2106 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002107 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002108
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002109 spv::Id length;
2110 if (node->getOperand()->getType().isCoopMat()) {
2111 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2112
2113 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2114 assert(builder.isCooperativeMatrixType(typeId));
2115
2116 length = builder.createCooperativeMatrixLength(typeId);
2117 } else {
2118 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2119 block->traverse(this);
John Kessenich8985fc92020-03-03 10:25:07 -07002120 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()
2121 ->getConstArray()[0].getUConst();
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002122 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2123 }
John Kessenichc9a80832015-09-12 12:17:44 -06002124
John Kessenich8c869672018-11-28 07:01:37 -07002125 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2126 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2127 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002128 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2129 if (builder.isInSpecConstCodeGenMode()) {
2130 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2131 } else {
2132 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2133 }
2134 }
John Kessenich8c869672018-11-28 07:01:37 -07002135
John Kessenichc9a80832015-09-12 12:17:44 -06002136 builder.clearAccessChain();
2137 builder.setAccessChainRValue(length);
2138
2139 return false;
2140 }
2141
John Kessenichfc51d282015-08-19 13:34:18 -06002142 // Start by evaluating the operand
2143
John Kessenich8c8505c2016-07-26 12:50:38 -06002144 // Does it need a swizzle inversion? If so, evaluation is inverted;
2145 // operate first on the swizzle base, then apply the swizzle.
2146 spv::Id invertedType = spv::NoType;
John Kessenich8985fc92020-03-03 10:25:07 -07002147 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2148 invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenich8c8505c2016-07-26 12:50:38 -06002149 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2150 invertedType = getInvertedSwizzleType(*node->getOperand());
2151
John Kessenich140f3df2015-06-26 16:58:36 -06002152 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002153 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002154 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002155 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002156 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002157 operandNode = node->getOperand();
2158
2159 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002160
Rex Xufc618912015-09-09 16:42:49 +08002161 spv::Id operand = spv::NoResult;
2162
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002163 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2164
John Kessenichfb4f2332019-08-09 03:49:15 -06002165#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002166 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2167 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002168 node->getOp() == glslang::EOpAtomicCounter ||
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002169 node->getOp() == glslang::EOpInterpolateAtCentroid) {
Rex Xufc618912015-09-09 16:42:49 +08002170 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002171 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2172 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2173 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002174#endif
2175 {
John Kessenich32cfd492016-02-02 12:37:46 -07002176 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002177 }
John Kessenich140f3df2015-06-26 16:58:36 -06002178
John Kessenichead86222018-03-28 18:01:20 -06002179 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002180 TranslateNoContractionDecoration(node->getType().getQualifier()),
2181 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002182
2183 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002184 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002185 result = createConversion(node->getOp(), decorations, resultType(), operand,
2186 node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002187
2188 // if not, then possibly an operation
2189 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002190 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand,
2191 node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002192
2193 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002194 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002195 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002196 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002197 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002198
John Kessenich140f3df2015-06-26 16:58:36 -06002199 builder.clearAccessChain();
2200 builder.setAccessChainRValue(result);
2201
2202 return false; // done with this node
2203 }
2204
2205 // it must be a special case, check...
2206 switch (node->getOp()) {
2207 case glslang::EOpPostIncrement:
2208 case glslang::EOpPostDecrement:
2209 case glslang::EOpPreIncrement:
2210 case glslang::EOpPreDecrement:
2211 {
2212 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002213 spv::Id one = 0;
2214 if (node->getBasicType() == glslang::EbtFloat)
2215 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002216#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002217 else if (node->getBasicType() == glslang::EbtDouble)
2218 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002219 else if (node->getBasicType() == glslang::EbtFloat16)
2220 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002221 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2222 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002223 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2224 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002225 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2226 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002227#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002228 else
2229 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002230 glslang::TOperator op;
2231 if (node->getOp() == glslang::EOpPreIncrement ||
2232 node->getOp() == glslang::EOpPostIncrement)
2233 op = glslang::EOpAdd;
2234 else
2235 op = glslang::EOpSub;
2236
John Kessenichead86222018-03-28 18:01:20 -06002237 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002238 convertGlslangToSpvType(node->getType()), operand, one,
2239 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002240 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002241
2242 // The result of operation is always stored, but conditionally the
2243 // consumed result. The consumed result is always an r-value.
2244 builder.accessChainStore(result);
2245 builder.clearAccessChain();
2246 if (node->getOp() == glslang::EOpPreIncrement ||
2247 node->getOp() == glslang::EOpPreDecrement)
2248 builder.setAccessChainRValue(result);
2249 else
2250 builder.setAccessChainRValue(operand);
2251 }
2252
2253 return false;
2254
John Kessenich155d3512019-08-08 23:29:20 -06002255#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002256 case glslang::EOpEmitStreamVertex:
2257 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2258 return false;
2259 case glslang::EOpEndStreamPrimitive:
2260 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2261 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002262#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002263
2264 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002265 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002266 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002267 }
John Kessenich140f3df2015-06-26 16:58:36 -06002268}
2269
Jeff Bolz53134492019-06-25 13:31:10 -05002270// Construct a composite object, recursively copying members if their types don't match
2271spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2272{
2273 for (int c = 0; c < (int)constituents.size(); ++c) {
2274 spv::Id& constituent = constituents[c];
2275 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2276 spv::Id rType = builder.getTypeId(constituent);
2277 if (lType != rType) {
2278 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2279 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2280 } else if (builder.isStructType(rType)) {
2281 std::vector<spv::Id> rTypeConstituents;
2282 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2283 for (int i = 0; i < numrTypeConstituents; ++i) {
John Kessenich8985fc92020-03-03 10:25:07 -07002284 rTypeConstituents.push_back(builder.createCompositeExtract(constituent,
2285 builder.getContainedTypeId(rType, i), i));
Jeff Bolz53134492019-06-25 13:31:10 -05002286 }
2287 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2288 } else {
2289 assert(builder.isArrayType(rType));
2290 std::vector<spv::Id> rTypeConstituents;
2291 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2292
2293 spv::Id elementRType = builder.getContainedTypeId(rType);
2294 for (int i = 0; i < numrTypeConstituents; ++i) {
2295 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2296 }
2297 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2298 }
2299 }
2300 }
2301 return builder.createCompositeConstruct(resultTypeId, constituents);
2302}
2303
John Kessenich140f3df2015-06-26 16:58:36 -06002304bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2305{
qining27e04a02016-04-14 16:40:20 -04002306 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2307 if (node->getType().getQualifier().isSpecConstant())
2308 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2309
John Kessenichfc51d282015-08-19 13:34:18 -06002310 spv::Id result = spv::NoResult;
John Kessenichbbbd9a22020-03-03 07:21:37 -07002311 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
John Kessenich8985fc92020-03-03 10:25:07 -07002312 spv::Builder::AccessChain complexLvalue; // for holding swizzling l-values too complex for SPIR-V,
2313 // for at out parameter
John Kessenichbbbd9a22020-03-03 07:21:37 -07002314 spv::Id temporaryLvalue = spv::NoResult; // temporary to pass, as proxy for complexLValue
2315
John Kessenich8985fc92020-03-03 10:25:07 -07002316 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2317 invertedType :
2318 convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002319
2320 // try texturing
2321 result = createImageTextureFunctionCall(node);
2322 if (result != spv::NoResult) {
2323 builder.clearAccessChain();
2324 builder.setAccessChainRValue(result);
2325
2326 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002327 }
2328#ifndef GLSLANG_WEB
2329 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002330 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002331 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002332 // "imageStore" is a special case, which has no result
2333 return false;
2334 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002335#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002336
John Kessenich140f3df2015-06-26 16:58:36 -06002337 glslang::TOperator binOp = glslang::EOpNull;
2338 bool reduceComparison = true;
2339 bool isMatrix = false;
2340 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002341 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002342
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002343 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2344
John Kessenich140f3df2015-06-26 16:58:36 -06002345 assert(node->getOp());
2346
John Kessenichf6640762016-08-01 19:44:00 -06002347 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002348
2349 switch (node->getOp()) {
2350 case glslang::EOpSequence:
2351 {
2352 if (preVisit)
2353 ++sequenceDepth;
2354 else
2355 --sequenceDepth;
2356
2357 if (sequenceDepth == 1) {
2358 // If this is the parent node of all the functions, we want to see them
2359 // early, so all call points have actual SPIR-V functions to reference.
2360 // In all cases, still let the traverser visit the children for us.
2361 makeFunctions(node->getAsAggregate()->getSequence());
2362
John Kessenich6fccb3c2016-09-19 16:01:41 -06002363 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002364 // anything else gets there, so visit out of order, doing them all now.
2365 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2366
John Kessenich6a60c2f2016-12-08 21:01:59 -07002367 // 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 -06002368 // so do them manually.
2369 visitFunctions(node->getAsAggregate()->getSequence());
2370
2371 return false;
2372 }
2373
2374 return true;
2375 }
2376 case glslang::EOpLinkerObjects:
2377 {
2378 if (visit == glslang::EvPreVisit)
2379 linkageOnly = true;
2380 else
2381 linkageOnly = false;
2382
2383 return true;
2384 }
2385 case glslang::EOpComma:
2386 {
2387 // processing from left to right naturally leaves the right-most
2388 // lying around in the access chain
2389 glslang::TIntermSequence& glslangOperands = node->getSequence();
2390 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2391 glslangOperands[i]->traverse(this);
2392
2393 return false;
2394 }
2395 case glslang::EOpFunction:
2396 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002397 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002398 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002399 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002400 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002401 } else {
2402 handleFunctionEntry(node);
2403 }
2404 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002405 if (inEntryPoint)
2406 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002407 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002408 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002409 }
2410
2411 return true;
2412 case glslang::EOpParameters:
2413 // Parameters will have been consumed by EOpFunction processing, but not
2414 // the body, so we still visited the function node's children, making this
2415 // child redundant.
2416 return false;
2417 case glslang::EOpFunctionCall:
2418 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002419 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002420 if (node->isUserDefined())
2421 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07002422 if (result) {
2423 builder.clearAccessChain();
2424 builder.setAccessChainRValue(result);
2425 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002426 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002427
2428 return false;
2429 }
2430 case glslang::EOpConstructMat2x2:
2431 case glslang::EOpConstructMat2x3:
2432 case glslang::EOpConstructMat2x4:
2433 case glslang::EOpConstructMat3x2:
2434 case glslang::EOpConstructMat3x3:
2435 case glslang::EOpConstructMat3x4:
2436 case glslang::EOpConstructMat4x2:
2437 case glslang::EOpConstructMat4x3:
2438 case glslang::EOpConstructMat4x4:
2439 case glslang::EOpConstructDMat2x2:
2440 case glslang::EOpConstructDMat2x3:
2441 case glslang::EOpConstructDMat2x4:
2442 case glslang::EOpConstructDMat3x2:
2443 case glslang::EOpConstructDMat3x3:
2444 case glslang::EOpConstructDMat3x4:
2445 case glslang::EOpConstructDMat4x2:
2446 case glslang::EOpConstructDMat4x3:
2447 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002448 case glslang::EOpConstructIMat2x2:
2449 case glslang::EOpConstructIMat2x3:
2450 case glslang::EOpConstructIMat2x4:
2451 case glslang::EOpConstructIMat3x2:
2452 case glslang::EOpConstructIMat3x3:
2453 case glslang::EOpConstructIMat3x4:
2454 case glslang::EOpConstructIMat4x2:
2455 case glslang::EOpConstructIMat4x3:
2456 case glslang::EOpConstructIMat4x4:
2457 case glslang::EOpConstructUMat2x2:
2458 case glslang::EOpConstructUMat2x3:
2459 case glslang::EOpConstructUMat2x4:
2460 case glslang::EOpConstructUMat3x2:
2461 case glslang::EOpConstructUMat3x3:
2462 case glslang::EOpConstructUMat3x4:
2463 case glslang::EOpConstructUMat4x2:
2464 case glslang::EOpConstructUMat4x3:
2465 case glslang::EOpConstructUMat4x4:
2466 case glslang::EOpConstructBMat2x2:
2467 case glslang::EOpConstructBMat2x3:
2468 case glslang::EOpConstructBMat2x4:
2469 case glslang::EOpConstructBMat3x2:
2470 case glslang::EOpConstructBMat3x3:
2471 case glslang::EOpConstructBMat3x4:
2472 case glslang::EOpConstructBMat4x2:
2473 case glslang::EOpConstructBMat4x3:
2474 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002475 case glslang::EOpConstructF16Mat2x2:
2476 case glslang::EOpConstructF16Mat2x3:
2477 case glslang::EOpConstructF16Mat2x4:
2478 case glslang::EOpConstructF16Mat3x2:
2479 case glslang::EOpConstructF16Mat3x3:
2480 case glslang::EOpConstructF16Mat3x4:
2481 case glslang::EOpConstructF16Mat4x2:
2482 case glslang::EOpConstructF16Mat4x3:
2483 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002484 isMatrix = true;
2485 // fall through
2486 case glslang::EOpConstructFloat:
2487 case glslang::EOpConstructVec2:
2488 case glslang::EOpConstructVec3:
2489 case glslang::EOpConstructVec4:
2490 case glslang::EOpConstructDouble:
2491 case glslang::EOpConstructDVec2:
2492 case glslang::EOpConstructDVec3:
2493 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002494 case glslang::EOpConstructFloat16:
2495 case glslang::EOpConstructF16Vec2:
2496 case glslang::EOpConstructF16Vec3:
2497 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002498 case glslang::EOpConstructBool:
2499 case glslang::EOpConstructBVec2:
2500 case glslang::EOpConstructBVec3:
2501 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002502 case glslang::EOpConstructInt8:
2503 case glslang::EOpConstructI8Vec2:
2504 case glslang::EOpConstructI8Vec3:
2505 case glslang::EOpConstructI8Vec4:
2506 case glslang::EOpConstructUint8:
2507 case glslang::EOpConstructU8Vec2:
2508 case glslang::EOpConstructU8Vec3:
2509 case glslang::EOpConstructU8Vec4:
2510 case glslang::EOpConstructInt16:
2511 case glslang::EOpConstructI16Vec2:
2512 case glslang::EOpConstructI16Vec3:
2513 case glslang::EOpConstructI16Vec4:
2514 case glslang::EOpConstructUint16:
2515 case glslang::EOpConstructU16Vec2:
2516 case glslang::EOpConstructU16Vec3:
2517 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002518 case glslang::EOpConstructInt:
2519 case glslang::EOpConstructIVec2:
2520 case glslang::EOpConstructIVec3:
2521 case glslang::EOpConstructIVec4:
2522 case glslang::EOpConstructUint:
2523 case glslang::EOpConstructUVec2:
2524 case glslang::EOpConstructUVec3:
2525 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002526 case glslang::EOpConstructInt64:
2527 case glslang::EOpConstructI64Vec2:
2528 case glslang::EOpConstructI64Vec3:
2529 case glslang::EOpConstructI64Vec4:
2530 case glslang::EOpConstructUint64:
2531 case glslang::EOpConstructU64Vec2:
2532 case glslang::EOpConstructU64Vec3:
2533 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002534 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002535 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002536 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002537 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002538 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002539 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002540 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002541 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002542 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002543 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002544 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002545 else if (node->getOp() == glslang::EOpConstructStruct ||
2546 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2547 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002548 std::vector<spv::Id> constituents;
2549 for (int c = 0; c < (int)arguments.size(); ++c)
2550 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002551 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002552 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002553 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002554 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002555 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002556
2557 builder.clearAccessChain();
2558 builder.setAccessChainRValue(constructed);
2559
2560 return false;
2561 }
2562
2563 // These six are component-wise compares with component-wise results.
2564 // Forward on to createBinaryOperation(), requesting a vector result.
2565 case glslang::EOpLessThan:
2566 case glslang::EOpGreaterThan:
2567 case glslang::EOpLessThanEqual:
2568 case glslang::EOpGreaterThanEqual:
2569 case glslang::EOpVectorEqual:
2570 case glslang::EOpVectorNotEqual:
2571 {
2572 // Map the operation to a binary
2573 binOp = node->getOp();
2574 reduceComparison = false;
2575 switch (node->getOp()) {
2576 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2577 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2578 default: binOp = node->getOp(); break;
2579 }
2580
2581 break;
2582 }
2583 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002584 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002585 binOp = glslang::EOpMul;
2586 break;
2587 case glslang::EOpOuterProduct:
2588 // two vectors multiplied to make a matrix
2589 binOp = glslang::EOpOuterProduct;
2590 break;
2591 case glslang::EOpDot:
2592 {
qining25262b32016-05-06 17:25:16 -04002593 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002594 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002595 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002596 binOp = glslang::EOpMul;
2597 break;
2598 }
2599 case glslang::EOpMod:
2600 // when an aggregate, this is the floating-point mod built-in function,
2601 // which can be emitted by the one in createBinaryOperation()
2602 binOp = glslang::EOpMod;
2603 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002604
John Kessenich140f3df2015-06-26 16:58:36 -06002605 case glslang::EOpEmitVertex:
2606 case glslang::EOpEndPrimitive:
2607 case glslang::EOpBarrier:
2608 case glslang::EOpMemoryBarrier:
2609 case glslang::EOpMemoryBarrierAtomicCounter:
2610 case glslang::EOpMemoryBarrierBuffer:
2611 case glslang::EOpMemoryBarrierImage:
2612 case glslang::EOpMemoryBarrierShared:
2613 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002614 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002615 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002616 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002617 case glslang::EOpWorkgroupMemoryBarrier:
2618 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002619 case glslang::EOpSubgroupBarrier:
2620 case glslang::EOpSubgroupMemoryBarrier:
2621 case glslang::EOpSubgroupMemoryBarrierBuffer:
2622 case glslang::EOpSubgroupMemoryBarrierImage:
2623 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002624 noReturnValue = true;
2625 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2626 break;
2627
John Kessenich426394d2015-07-23 10:22:48 -06002628 case glslang::EOpAtomicAdd:
2629 case glslang::EOpAtomicMin:
2630 case glslang::EOpAtomicMax:
2631 case glslang::EOpAtomicAnd:
2632 case glslang::EOpAtomicOr:
2633 case glslang::EOpAtomicXor:
2634 case glslang::EOpAtomicExchange:
2635 case glslang::EOpAtomicCompSwap:
2636 atomic = true;
2637 break;
2638
John Kesseniche5eee8f2019-10-18 01:03:11 -06002639#ifndef GLSLANG_WEB
2640 case glslang::EOpAtomicStore:
2641 noReturnValue = true;
2642 // fallthrough
2643 case glslang::EOpAtomicLoad:
2644 atomic = true;
2645 break;
2646
John Kessenich0d0c6d32017-07-23 16:08:26 -06002647 case glslang::EOpAtomicCounterAdd:
2648 case glslang::EOpAtomicCounterSubtract:
2649 case glslang::EOpAtomicCounterMin:
2650 case glslang::EOpAtomicCounterMax:
2651 case glslang::EOpAtomicCounterAnd:
2652 case glslang::EOpAtomicCounterOr:
2653 case glslang::EOpAtomicCounterXor:
2654 case glslang::EOpAtomicCounterExchange:
2655 case glslang::EOpAtomicCounterCompSwap:
2656 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2657 builder.addCapability(spv::CapabilityAtomicStorageOps);
2658 atomic = true;
2659 break;
2660
Ian Romanickb3bd4022019-01-21 08:57:25 -08002661 case glslang::EOpAbsDifference:
2662 case glslang::EOpAddSaturate:
2663 case glslang::EOpSubSaturate:
2664 case glslang::EOpAverage:
2665 case glslang::EOpAverageRounded:
2666 case glslang::EOpMul32x16:
2667 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2668 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2669 binOp = node->getOp();
2670 break;
2671
Chao Chenb50c02e2018-09-19 11:42:24 -07002672 case glslang::EOpIgnoreIntersectionNV:
2673 case glslang::EOpTerminateRayNV:
2674 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002675 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002676 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2677 noReturnValue = true;
2678 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002679 case glslang::EOpCooperativeMatrixLoad:
2680 case glslang::EOpCooperativeMatrixStore:
2681 noReturnValue = true;
2682 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002683 case glslang::EOpBeginInvocationInterlock:
2684 case glslang::EOpEndInvocationInterlock:
2685 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2686 noReturnValue = true;
2687 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002688#endif
Chao Chen3c366992018-09-19 11:41:59 -07002689
John Kessenich140f3df2015-06-26 16:58:36 -06002690 default:
2691 break;
2692 }
2693
2694 //
2695 // See if it maps to a regular operation.
2696 //
John Kessenich140f3df2015-06-26 16:58:36 -06002697 if (binOp != glslang::EOpNull) {
2698 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2699 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2700 assert(left && right);
2701
2702 builder.clearAccessChain();
2703 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002704 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002705
2706 builder.clearAccessChain();
2707 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002708 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002709
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002710 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002711 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002712 TranslateNoContractionDecoration(node->getType().getQualifier()),
2713 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002714 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002715 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002716 left->getType().getBasicType(), reduceComparison);
2717
2718 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002719 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002720 builder.clearAccessChain();
2721 builder.setAccessChainRValue(result);
2722
2723 return false;
2724 }
2725
John Kessenich426394d2015-07-23 10:22:48 -06002726 //
2727 // Create the list of operands.
2728 //
John Kessenich140f3df2015-06-26 16:58:36 -06002729 glslang::TIntermSequence& glslangOperands = node->getSequence();
2730 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002731 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002732 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002733 // special case l-value operands; there are just a few
2734 bool lvalue = false;
2735 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002736 case glslang::EOpModf:
2737 if (arg == 1)
2738 lvalue = true;
2739 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002740
2741 case glslang::EOpAtomicAdd:
2742 case glslang::EOpAtomicMin:
2743 case glslang::EOpAtomicMax:
2744 case glslang::EOpAtomicAnd:
2745 case glslang::EOpAtomicOr:
2746 case glslang::EOpAtomicXor:
2747 case glslang::EOpAtomicExchange:
2748 case glslang::EOpAtomicCompSwap:
2749 if (arg == 0)
2750 lvalue = true;
2751 break;
2752
John Kessenicha28f7a72019-08-06 07:00:58 -06002753#ifndef GLSLANG_WEB
2754 case glslang::EOpFrexp:
2755 if (arg == 1)
2756 lvalue = true;
2757 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002758 case glslang::EOpInterpolateAtSample:
2759 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002760 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002761 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002762 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002763
2764 // Does it need a swizzle inversion? If so, evaluation is inverted;
2765 // operate first on the swizzle base, then apply the swizzle.
John Kessenichbbbd9a22020-03-03 07:21:37 -07002766 // That is, we transform
2767 //
2768 // interpolate(v.zy) -> interpolate(v).zy
2769 //
John Kessenichecba76f2017-01-06 00:34:48 -07002770 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002771 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
John Kessenich8985fc92020-03-03 10:25:07 -07002772 invertedType = convertGlslangToSpvType(
2773 glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
John Kessenich8c8505c2016-07-26 12:50:38 -06002774 }
Rex Xu7a26c172015-12-08 17:12:09 +08002775 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002776 case glslang::EOpAtomicLoad:
2777 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002778 case glslang::EOpAtomicCounterAdd:
2779 case glslang::EOpAtomicCounterSubtract:
2780 case glslang::EOpAtomicCounterMin:
2781 case glslang::EOpAtomicCounterMax:
2782 case glslang::EOpAtomicCounterAnd:
2783 case glslang::EOpAtomicCounterOr:
2784 case glslang::EOpAtomicCounterXor:
2785 case glslang::EOpAtomicCounterExchange:
2786 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002787 if (arg == 0)
2788 lvalue = true;
2789 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002790 case glslang::EOpAddCarry:
2791 case glslang::EOpSubBorrow:
2792 if (arg == 2)
2793 lvalue = true;
2794 break;
2795 case glslang::EOpUMulExtended:
2796 case glslang::EOpIMulExtended:
2797 if (arg >= 2)
2798 lvalue = true;
2799 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002800 case glslang::EOpCooperativeMatrixLoad:
2801 if (arg == 0 || arg == 1)
2802 lvalue = true;
2803 break;
2804 case glslang::EOpCooperativeMatrixStore:
2805 if (arg == 1)
2806 lvalue = true;
2807 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002808#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002809 default:
2810 break;
2811 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002812 builder.clearAccessChain();
2813 if (invertedType != spv::NoType && arg == 0)
2814 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2815 else
2816 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002817
John Kessenichb9197c82019-08-11 07:41:45 -06002818#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002819 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2820 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2821
2822 if (arg == 1) {
2823 // fold "element" parameter into the access chain
2824 spv::Builder::AccessChain save = builder.getAccessChain();
2825 builder.clearAccessChain();
2826 glslangOperands[2]->traverse(this);
2827
2828 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2829
2830 builder.setAccessChain(save);
2831
2832 // Point to the first element of the array.
John Kessenich8985fc92020-03-03 10:25:07 -07002833 builder.accessChainPush(elementId,
2834 TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
2835 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002836
2837 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2838 unsigned int alignment = builder.getAccessChain().alignment;
2839
2840 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2841 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2842 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2843 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2844 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
John Kessenich8985fc92020-03-03 10:25:07 -07002845 if (builder.getStorageClass(builder.getAccessChain().base) ==
2846 spv::StorageClassPhysicalStorageBufferEXT) {
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002847 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2848 }
2849
2850 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2851
2852 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2853 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2854 }
2855
John Kessenich8985fc92020-03-03 10:25:07 -07002856 if (memoryAccess &
2857 (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2858 memoryAccessOperands.push_back(spv::IdImmediate(true,
2859 builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002860 }
2861 } else if (arg == 2) {
2862 continue;
2863 }
2864 }
John Kessenichb9197c82019-08-11 07:41:45 -06002865#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002866
John Kessenichbbbd9a22020-03-03 07:21:37 -07002867 // for l-values, pass the address, for r-values, pass the value
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002868 if (lvalue) {
John Kessenichbbbd9a22020-03-03 07:21:37 -07002869 if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
2870 // SPIR-V cannot represent an l-value containing a swizzle that doesn't
2871 // reduce to a simple access chain. So, we need a temporary vector to
2872 // receive the result, and must later swizzle that into the original
2873 // l-value.
2874 complexLvalue = builder.getAccessChain();
John Kessenich8985fc92020-03-03 10:25:07 -07002875 temporaryLvalue = builder.createVariable(spv::StorageClassFunction,
2876 builder.accessChainGetInferredType(), "swizzleTemp");
John Kessenichbbbd9a22020-03-03 07:21:37 -07002877 operands.push_back(temporaryLvalue);
2878 } else {
2879 operands.push_back(builder.accessChainGetLValue());
2880 }
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002881 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2882 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2883 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002884 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002885 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002886 }
John Kessenich140f3df2015-06-26 16:58:36 -06002887 }
John Kessenich426394d2015-07-23 10:22:48 -06002888
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002889 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06002890#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002891 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2892 std::vector<spv::IdImmediate> idImmOps;
2893
2894 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2895 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2896 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2897 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2898 // get the pointee type
2899 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2900 assert(builder.isCooperativeMatrixType(typeId));
2901 // do the op
2902 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2903 // store the result to the pointer (out param 'm')
2904 builder.createStore(result, operands[0]);
2905 result = 0;
2906 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2907 std::vector<spv::IdImmediate> idImmOps;
2908
2909 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2910 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2911 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2912 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2913 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2914
2915 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2916 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06002917 } else
2918#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06002919 if (atomic) {
2920 // Handle all atomics
John Kessenich8985fc92020-03-03 10:25:07 -07002921 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
2922 lvalueCoherentFlags);
John Kesseniche5eee8f2019-10-18 01:03:11 -06002923 } else {
John Kessenich426394d2015-07-23 10:22:48 -06002924 // Pass through to generic operations.
2925 switch (glslangOperands.size()) {
2926 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002927 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002928 break;
2929 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002930 {
2931 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002932 TranslateNoContractionDecoration(node->getType().getQualifier()),
2933 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002934 result = createUnaryOperation(
2935 node->getOp(), decorations,
2936 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002937 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06002938 }
John Kessenich426394d2015-07-23 10:22:48 -06002939 break;
2940 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002941 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002942 break;
2943 }
John Kessenichbbbd9a22020-03-03 07:21:37 -07002944 if (invertedType != spv::NoResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06002945 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenichbbbd9a22020-03-03 07:21:37 -07002946 else if (temporaryLvalue != spv::NoResult) {
2947 builder.setAccessChain(complexLvalue);
2948 builder.accessChainStore(builder.createLoad(temporaryLvalue));
2949 }
John Kessenich140f3df2015-06-26 16:58:36 -06002950 }
2951
2952 if (noReturnValue)
2953 return false;
2954
2955 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002956 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002957 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002958 } else {
2959 builder.clearAccessChain();
2960 builder.setAccessChainRValue(result);
2961 return false;
2962 }
2963}
2964
John Kessenich433e9ff2017-01-26 20:31:11 -07002965// This path handles both if-then-else and ?:
2966// The if-then-else has a node type of void, while
2967// ?: has either a void or a non-void node type
2968//
2969// Leaving the result, when not void:
2970// GLSL only has r-values as the result of a :?, but
2971// if we have an l-value, that can be more efficient if it will
2972// become the base of a complex r-value expression, because the
2973// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002974bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2975{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002976 // see if OpSelect can handle it
2977 const auto isOpSelectable = [&]() {
2978 if (node->getBasicType() == glslang::EbtVoid)
2979 return false;
2980 // OpSelect can do all other types starting with SPV 1.4
2981 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2982 // pre-1.4, only scalars and vectors can be handled
2983 if ((!node->getType().isScalar() && !node->getType().isVector()))
2984 return false;
2985 }
2986 return true;
2987 };
2988
John Kessenich4bee5312018-02-20 21:29:05 -07002989 // See if it simple and safe, or required, to execute both sides.
2990 // Crucially, side effects must be either semantically required or avoided,
2991 // and there are performance trade-offs.
2992 // Return true if required or a good idea (and safe) to execute both sides,
2993 // false otherwise.
2994 const auto bothSidesPolicy = [&]() -> bool {
2995 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002996 if (node->getTrueBlock() == nullptr ||
2997 node->getFalseBlock() == nullptr)
2998 return false;
2999
John Kessenich4bee5312018-02-20 21:29:05 -07003000 // required? (unless we write additional code to look for side effects
3001 // and make performance trade-offs if none are present)
3002 if (!node->getShortCircuit())
3003 return true;
3004
3005 // if not required to execute both, decide based on performance/practicality...
3006
John Kessenich0c1e71a2019-01-10 18:23:06 +07003007 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07003008 return false;
3009
John Kessenich433e9ff2017-01-26 20:31:11 -07003010 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
3011 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
3012
3013 // return true if a single operand to ? : is okay for OpSelect
3014 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003015 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07003016 };
3017
3018 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
3019 operandOkay(node->getFalseBlock()->getAsTyped());
3020 };
3021
John Kessenich4bee5312018-02-20 21:29:05 -07003022 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
3023 // emit the condition before doing anything with selection
3024 node->getCondition()->traverse(this);
3025 spv::Id condition = accessChainLoad(node->getCondition()->getType());
3026
3027 // Find a way of executing both sides and selecting the right result.
3028 const auto executeBothSides = [&]() -> void {
3029 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07003030 node->getTrueBlock()->traverse(this);
3031 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3032 node->getFalseBlock()->traverse(this);
3033 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3034
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003035 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003036
John Kessenich4bee5312018-02-20 21:29:05 -07003037 // done if void
3038 if (node->getBasicType() == glslang::EbtVoid)
3039 return;
John Kesseniche434ad92017-03-30 10:09:28 -06003040
John Kessenich4bee5312018-02-20 21:29:05 -07003041 // emit code to select between trueValue and falseValue
3042
3043 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07003044 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07003045 // Emit OpSelect for this selection.
3046
3047 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07003048 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
3049 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07003050 condition = builder.smearScalar(spv::NoPrecision, condition,
3051 builder.makeVectorType(builder.makeBoolType(),
3052 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07003053 }
John Kessenich4bee5312018-02-20 21:29:05 -07003054
3055 // OpSelect
3056 result = builder.createTriOp(spv::OpSelect,
3057 convertGlslangToSpvType(node->getType()), condition,
3058 trueValue, falseValue);
3059
3060 builder.clearAccessChain();
3061 builder.setAccessChainRValue(result);
3062 } else {
3063 // We need control flow to select the result.
3064 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
3065 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
3066
3067 // Selection control:
3068 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3069
3070 // make an "if" based on the value created by the condition
3071 spv::Builder::If ifBuilder(condition, control, builder);
3072
3073 // emit the "then" statement
3074 builder.createStore(trueValue, result);
3075 ifBuilder.makeBeginElse();
3076 // emit the "else" statement
3077 builder.createStore(falseValue, result);
3078
3079 // finish off the control flow
3080 ifBuilder.makeEndIf();
3081
3082 builder.clearAccessChain();
3083 builder.setAccessChainLValue(result);
3084 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003085 };
3086
John Kessenich4bee5312018-02-20 21:29:05 -07003087 // Execute the one side needed, as per the condition
3088 const auto executeOneSide = [&]() {
3089 // Always emit control flow.
3090 if (node->getBasicType() != glslang::EbtVoid)
3091 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07003092
John Kessenich4bee5312018-02-20 21:29:05 -07003093 // Selection control:
3094 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3095
3096 // make an "if" based on the value created by the condition
3097 spv::Builder::If ifBuilder(condition, control, builder);
3098
3099 // emit the "then" statement
3100 if (node->getTrueBlock() != nullptr) {
3101 node->getTrueBlock()->traverse(this);
3102 if (result != spv::NoResult)
3103 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3104 }
3105
3106 if (node->getFalseBlock() != nullptr) {
3107 ifBuilder.makeBeginElse();
3108 // emit the "else" statement
3109 node->getFalseBlock()->traverse(this);
3110 if (result != spv::NoResult)
3111 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3112 }
3113
3114 // finish off the control flow
3115 ifBuilder.makeEndIf();
3116
3117 if (result != spv::NoResult) {
3118 builder.clearAccessChain();
3119 builder.setAccessChainLValue(result);
3120 }
3121 };
3122
3123 // Try for OpSelect (or a requirement to execute both sides)
3124 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003125 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3126 if (node->getType().getQualifier().isSpecConstant())
3127 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003128 executeBothSides();
3129 } else
3130 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003131
3132 return false;
3133}
3134
3135bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3136{
3137 // emit and get the condition before doing anything with switch
3138 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003139 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003140
Rex Xu57e65922017-07-04 23:23:40 +08003141 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003142 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003143
John Kessenich140f3df2015-06-26 16:58:36 -06003144 // browse the children to sort out code segments
3145 int defaultSegment = -1;
3146 std::vector<TIntermNode*> codeSegments;
3147 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3148 std::vector<int> caseValues;
3149 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3150 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3151 TIntermNode* child = *c;
3152 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003153 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003154 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003155 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich8985fc92020-03-03 10:25:07 -07003156 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()
3157 ->getConstArray()[0].getIConst());
John Kessenich140f3df2015-06-26 16:58:36 -06003158 } else
3159 codeSegments.push_back(child);
3160 }
3161
qining25262b32016-05-06 17:25:16 -04003162 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003163 // statements between the last case and the end of the switch statement
3164 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3165 (int)codeSegments.size() == defaultSegment)
3166 codeSegments.push_back(nullptr);
3167
3168 // make the switch statement
3169 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
John Kessenich8985fc92020-03-03 10:25:07 -07003170 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment,
3171 segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003172
3173 // emit all the code in the segments
3174 breakForLoop.push(false);
3175 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3176 builder.nextSwitchSegment(segmentBlocks, s);
3177 if (codeSegments[s])
3178 codeSegments[s]->traverse(this);
3179 else
3180 builder.addSwitchBreak();
3181 }
3182 breakForLoop.pop();
3183
3184 builder.endSwitch(segmentBlocks);
3185
3186 return false;
3187}
3188
3189void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3190{
3191 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003192 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003193
3194 builder.clearAccessChain();
3195 builder.setAccessChainRValue(constant);
3196}
3197
3198bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3199{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003200 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003201 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003202
3203 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003204 std::vector<unsigned int> operands;
3205 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003206
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003207 // Spec requires back edges to target header blocks, and every header block
3208 // must dominate its merge block. Make a header block first to ensure these
3209 // conditions are met. By definition, it will contain OpLoopMerge, followed
3210 // by a block-ending branch. But we don't want to put any other body/test
3211 // instructions in it, since the body/test may have arbitrary instructions,
3212 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003213 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003214 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003215 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003216 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003217 spv::Block& test = builder.makeNewBlock();
3218 builder.createBranch(&test);
3219
3220 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003221 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003222 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003223 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3224
3225 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003226 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003227 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003228 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003229 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003230 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003231
3232 builder.setBuildPoint(&blocks.continue_target);
3233 if (node->getTerminal())
3234 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003235 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003236 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003237 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003238 builder.createBranch(&blocks.body);
3239
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003240 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003241 builder.setBuildPoint(&blocks.body);
3242 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003243 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003244 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003245 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003246
3247 builder.setBuildPoint(&blocks.continue_target);
3248 if (node->getTerminal())
3249 node->getTerminal()->traverse(this);
3250 if (node->getTest()) {
3251 node->getTest()->traverse(this);
3252 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003253 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003254 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003255 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003256 // TODO: unless there was a break/return/discard instruction
3257 // somewhere in the body, this is an infinite loop, so we should
3258 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003259 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003260 }
John Kessenich140f3df2015-06-26 16:58:36 -06003261 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003262 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003263 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003264 return false;
3265}
3266
3267bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3268{
3269 if (node->getExpression())
3270 node->getExpression()->traverse(this);
3271
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003272 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003273
John Kessenich140f3df2015-06-26 16:58:36 -06003274 switch (node->getFlowOp()) {
3275 case glslang::EOpKill:
3276 builder.makeDiscard();
3277 break;
3278 case glslang::EOpBreak:
3279 if (breakForLoop.top())
3280 builder.createLoopExit();
3281 else
3282 builder.addSwitchBreak();
3283 break;
3284 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003285 builder.createLoopContinue();
3286 break;
3287 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003288 if (node->getExpression()) {
3289 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3290 spv::Id returnId = accessChainLoad(glslangReturnType);
3291 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3292 builder.clearAccessChain();
3293 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3294 builder.setAccessChainLValue(copyId);
3295 multiTypeStore(glslangReturnType, returnId);
3296 returnId = builder.createLoad(copyId);
3297 }
3298 builder.makeReturn(false, returnId);
3299 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003300 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003301
3302 builder.clearAccessChain();
3303 break;
3304
John Kessenichb9197c82019-08-11 07:41:45 -06003305#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003306 case glslang::EOpDemote:
3307 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3308 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3309 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3310 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003311#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003312
John Kessenich140f3df2015-06-26 16:58:36 -06003313 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003314 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003315 break;
3316 }
3317
3318 return false;
3319}
3320
John Kessenich9c14f772019-06-17 08:38:35 -06003321spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003322{
qining25262b32016-05-06 17:25:16 -04003323 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003324 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003325 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003326 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003327 spv::Id result = createSpvConstant(*node);
3328 if (result != spv::NoResult)
3329 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003330 }
3331
3332 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003333 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003334 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3335 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003336
John Kessenichb9197c82019-08-11 07:41:45 -06003337 const bool contains16BitType = node->getType().contains16BitFloat() ||
3338 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003339 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003340 switch (storageClass) {
3341 case spv::StorageClassInput:
3342 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003343 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003344 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003345 break;
John Kessenich18310872018-05-14 22:08:53 -06003346 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003347 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003348 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3349 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003350 else
3351 builder.addCapability(spv::CapabilityStorageUniform16);
3352 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003353#ifndef GLSLANG_WEB
3354 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003355 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003356 builder.addCapability(spv::CapabilityStoragePushConstant16);
3357 break;
John Kessenich18310872018-05-14 22:08:53 -06003358 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003359 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003360 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003361 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3362 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003363#endif
John Kessenich18310872018-05-14 22:08:53 -06003364 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003365 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003366 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003367 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003368 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003369 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003370 }
3371 }
Rex Xuf89ad982017-04-07 23:22:33 +08003372
John Kessenichb9197c82019-08-11 07:41:45 -06003373 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003374 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003375 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003376 builder.addCapability(spv::CapabilityStoragePushConstant8);
3377 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003378 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003379 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003380 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003381 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003382 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003383 } else {
3384 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003385 }
3386 }
3387
John Kessenich140f3df2015-06-26 16:58:36 -06003388 const char* name = node->getName().c_str();
3389 if (glslang::IsAnonymous(name))
3390 name = "";
3391
3392 return builder.createVariable(storageClass, spvType, name);
3393}
3394
3395// Return type Id of the sampled type.
3396spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3397{
3398 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003399 case glslang::EbtInt: return builder.makeIntType(32);
3400 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003401 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003402#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003403 case glslang::EbtFloat16:
3404 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3405 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3406 return builder.makeFloatType(16);
3407#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003408 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003409 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003410 return builder.makeFloatType(32);
3411 }
3412}
3413
John Kessenich8c8505c2016-07-26 12:50:38 -06003414// If node is a swizzle operation, return the type that should be used if
3415// the swizzle base is first consumed by another operation, before the swizzle
3416// is applied.
3417spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3418{
John Kessenichecba76f2017-01-06 00:34:48 -07003419 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003420 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3421 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3422 else
3423 return spv::NoType;
3424}
3425
3426// When inverting a swizzle with a parent op, this function
3427// will apply the swizzle operation to a completed parent operation.
John Kessenich8985fc92020-03-03 10:25:07 -07003428spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
3429 spv::Id parentResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003430{
3431 std::vector<unsigned> swizzle;
3432 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3433 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3434}
3435
John Kessenich8c8505c2016-07-26 12:50:38 -06003436// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3437void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3438{
3439 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3440 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3441 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3442}
3443
John Kessenich3ac051e2015-12-20 11:29:16 -07003444// Convert from a glslang type to an SPV type, by calling into a
3445// recursive version of this function. This establishes the inherited
3446// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003447spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003448{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003449 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003450}
3451
3452// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003453// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003454// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003455spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003456 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3457 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003458{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003459 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003460
3461 switch (type.getBasicType()) {
3462 case glslang::EbtVoid:
3463 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003464 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003465 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003466 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003467 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3468 // a 32-bit int where non-0 means true.
3469 if (explicitLayout != glslang::ElpNone)
3470 spvType = builder.makeUintType(32);
3471 else
3472 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003473 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003474 case glslang::EbtInt:
3475 spvType = builder.makeIntType(32);
3476 break;
3477 case glslang::EbtUint:
3478 spvType = builder.makeUintType(32);
3479 break;
3480 case glslang::EbtFloat:
3481 spvType = builder.makeFloatType(32);
3482 break;
3483#ifndef GLSLANG_WEB
3484 case glslang::EbtDouble:
3485 spvType = builder.makeFloatType(64);
3486 break;
3487 case glslang::EbtFloat16:
3488 spvType = builder.makeFloatType(16);
3489 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003490 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003491 spvType = builder.makeIntType(8);
3492 break;
3493 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003494 spvType = builder.makeUintType(8);
3495 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003496 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003497 spvType = builder.makeIntType(16);
3498 break;
3499 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003500 spvType = builder.makeUintType(16);
3501 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003502 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003503 spvType = builder.makeIntType(64);
3504 break;
3505 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003506 spvType = builder.makeUintType(64);
3507 break;
John Kessenich426394d2015-07-23 10:22:48 -06003508 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003509 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003510 spvType = builder.makeUintType(32);
3511 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003512 case glslang::EbtAccStructNV:
3513 spvType = builder.makeAccelerationStructureNVType();
3514 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003515 case glslang::EbtReference:
3516 {
3517 // Make the forward pointer, then recurse to convert the structure type, then
3518 // patch up the forward pointer with a real pointer type.
3519 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3520 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3521 forwardPointers[type.getReferentType()] = forwardId;
3522 }
3523 spvType = forwardPointers[type.getReferentType()];
3524 if (!forwardReferenceOnly) {
3525 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3526 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3527 forwardPointers[type.getReferentType()],
3528 referentType);
3529 }
3530 }
3531 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003532#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003533 case glslang::EbtSampler:
3534 {
3535 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003536 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003537 spvType = builder.makeSamplerType();
3538 } else {
3539 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003540 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3541 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3542 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3543 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003544 // already has both image and sampler, make the combined type
3545 spvType = builder.makeSampledImageType(spvType);
3546 }
John Kessenich55e7d112015-11-15 21:33:39 -07003547 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003548 }
John Kessenich140f3df2015-06-26 16:58:36 -06003549 break;
3550 case glslang::EbtStruct:
3551 case glslang::EbtBlock:
3552 {
3553 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003554 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003555
3556 // Try to share structs for different layouts, but not yet for other
3557 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003558 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003559 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003560 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003561 break;
3562
3563 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003564 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003565 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003566 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003567 }
3568 break;
3569 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003570 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003571 break;
3572 }
3573
3574 if (type.isMatrix())
3575 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3576 else {
3577 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3578 if (type.getVectorSize() > 1)
3579 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3580 }
3581
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003582 if (type.isCoopMat()) {
3583 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3584 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3585 if (type.getBasicType() == glslang::EbtFloat16)
3586 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003587 if (type.getBasicType() == glslang::EbtUint8 ||
3588 type.getBasicType() == glslang::EbtInt8) {
3589 builder.addCapability(spv::CapabilityInt8);
3590 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003591
3592 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3593 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3594 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3595
3596 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3597 }
3598
John Kessenich140f3df2015-06-26 16:58:36 -06003599 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003600 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3601
John Kessenichc9a80832015-09-12 12:17:44 -06003602 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003603 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003604 // We need to decorate array strides for types needing explicit layout, except blocks.
3605 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003606 // Use a dummy glslang type for querying internal strides of
3607 // arrays of arrays, but using just a one-dimensional array.
3608 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003609 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3610 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003611
3612 // Will compute the higher-order strides here, rather than making a whole
3613 // pile of types and doing repetitive recursion on their contents.
3614 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3615 }
John Kessenichf8842e52016-01-04 19:22:56 -07003616
3617 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003618 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003619 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003620 if (stride > 0)
3621 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003622 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003623 }
3624 } else {
3625 // single-dimensional array, and don't yet have stride
3626
John Kessenichf8842e52016-01-04 19:22:56 -07003627 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003628 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3629 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003630 }
John Kessenich31ed4832015-09-09 17:51:38 -06003631
John Kessenichead86222018-03-28 18:01:20 -06003632 // Do the outer dimension, which might not be known for a runtime-sized array.
3633 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3634 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003635 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003636 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003637#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003638 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003639 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003640 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3641 }
John Kessenichb9197c82019-08-11 07:41:45 -06003642#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003643 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003644 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003645 if (stride > 0)
3646 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003647 }
3648
3649 return spvType;
3650}
3651
John Kessenich0e737842017-03-24 18:38:16 -06003652// TODO: this functionality should exist at a higher level, in creating the AST
3653//
3654// Identify interface members that don't have their required extension turned on.
3655//
3656bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3657{
John Kessenicha28f7a72019-08-06 07:00:58 -06003658#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003659 auto& extensions = glslangIntermediate->getRequestedExtensions();
3660
Rex Xubcf291a2017-03-29 23:01:36 +08003661 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3662 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3663 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003664 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3665 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3666 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003667
3668 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3669 if (member.getFieldName() == "gl_ViewportMask" &&
3670 extensions.find("GL_NV_viewport_array2") == extensions.end())
3671 return true;
3672 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3673 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3674 return true;
3675 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3676 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3677 return true;
3678 }
3679#endif
John Kessenich0e737842017-03-24 18:38:16 -06003680
3681 return false;
3682};
3683
John Kessenich6090df02016-06-30 21:18:02 -06003684// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3685// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3686// Mutually recursive with convertGlslangToSpvType().
3687spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3688 const glslang::TTypeList* glslangMembers,
3689 glslang::TLayoutPacking explicitLayout,
3690 const glslang::TQualifier& qualifier)
3691{
3692 // Create a vector of struct types for SPIR-V to consume
3693 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07003694 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
3695 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003696 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003697 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3698 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3699 if (glslangMember.hiddenMember()) {
3700 ++memberDelta;
3701 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003702 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06003703 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003704 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003705 if (filterMember(glslangMember)) {
3706 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08003707 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003708 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003709 }
Roy05a5b532020-01-03 16:21:34 +08003710 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003711 }
John Kessenich6090df02016-06-30 21:18:02 -06003712 // modify just this child's view of the qualifier
3713 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3714 InheritQualifiers(memberQualifier, qualifier);
3715
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003716 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003717 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003718 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003719
3720 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003721 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3722 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003723
3724 // Make forward pointers for any pointer members, and create a list of members to
3725 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003726 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003727 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3728 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3729 }
3730 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003731 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3732 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003733 } else {
3734 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003735 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3736 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003737 }
John Kessenich6090df02016-06-30 21:18:02 -06003738 }
3739 }
3740
3741 // Make the SPIR-V type
3742 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003743 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003744 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3745
3746 // Decorate it
3747 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3748
John Kessenichd72f4882019-01-16 14:55:37 +07003749 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003750 auto it = deferredForwardPointers[i];
3751 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3752 }
3753
John Kessenich6090df02016-06-30 21:18:02 -06003754 return spvType;
3755}
3756
3757void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3758 const glslang::TTypeList* glslangMembers,
3759 glslang::TLayoutPacking explicitLayout,
3760 const glslang::TQualifier& qualifier,
3761 spv::Id spvType)
3762{
3763 // Name and decorate the non-hidden members
3764 int offset = -1;
3765 int locationOffset = 0; // for use within the members of this struct
3766 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3767 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3768 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003769 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08003770 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06003771 if (filterMember(glslangMember))
3772 continue;
3773 }
John Kessenich6090df02016-06-30 21:18:02 -06003774
3775 // modify just this child's view of the qualifier
3776 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3777 InheritQualifiers(memberQualifier, qualifier);
3778
3779 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003780 if (member < 0)
3781 continue;
3782
3783 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3784 builder.addMemberDecoration(spvType, member,
3785 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3786 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3787 // Add interpolation and auxiliary storage decorations only to
3788 // top-level members of Input and Output storage classes
3789 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3790 type.getQualifier().storage == glslang::EvqVaryingOut) {
3791 if (type.getBasicType() == glslang::EbtBlock ||
3792 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3793 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3794 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003795#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003796 addMeshNVDecoration(spvType, member, memberQualifier);
3797#endif
John Kessenich6090df02016-06-30 21:18:02 -06003798 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003799 }
3800 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003801
John Kessenichb9197c82019-08-11 07:41:45 -06003802#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003803 if (type.getBasicType() == glslang::EbtBlock &&
3804 qualifier.storage == glslang::EvqBuffer) {
3805 // Add memory decorations only to top-level members of shader storage block
3806 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003807 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003808 for (unsigned int i = 0; i < memory.size(); ++i)
3809 builder.addMemberDecoration(spvType, member, memory[i]);
3810 }
John Kessenichf8d1d742019-10-21 06:55:11 -06003811
John Kessenichb9197c82019-08-11 07:41:45 -06003812#endif
John Kessenich6090df02016-06-30 21:18:02 -06003813
John Kessenich5d610ee2018-03-07 18:05:55 -07003814 // Location assignment was already completed correctly by the front end,
3815 // just track whether a member needs to be decorated.
3816 // Ignore member locations if the container is an array, as that's
3817 // ill-specified and decisions have been made to not allow this.
3818 if (! type.isArray() && memberQualifier.hasLocation())
3819 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003820
John Kessenich5d610ee2018-03-07 18:05:55 -07003821 if (qualifier.hasLocation()) // track for upcoming inheritance
3822 locationOffset += glslangIntermediate->computeTypeLocationSize(
3823 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003824
John Kessenich5d610ee2018-03-07 18:05:55 -07003825 // component, XFB, others
3826 if (glslangMember.getQualifier().hasComponent())
3827 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3828 glslangMember.getQualifier().layoutComponent);
3829 if (glslangMember.getQualifier().hasXfbOffset())
3830 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3831 glslangMember.getQualifier().layoutXfbOffset);
3832 else if (explicitLayout != glslang::ElpNone) {
3833 // figure out what to do with offset, which is accumulating
3834 int nextOffset;
3835 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3836 if (offset >= 0)
3837 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3838 offset = nextOffset;
3839 }
John Kessenich6090df02016-06-30 21:18:02 -06003840
John Kessenich5d610ee2018-03-07 18:05:55 -07003841 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3842 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3843 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003844
John Kessenich5d610ee2018-03-07 18:05:55 -07003845 // built-in variable decorations
3846 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3847 if (builtIn != spv::BuiltInMax)
3848 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003849
John Kessenichb9197c82019-08-11 07:41:45 -06003850#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003851 // nonuniform
3852 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3853
John Kessenichead86222018-03-28 18:01:20 -06003854 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3855 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3856 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3857 memberQualifier.semanticName);
3858 }
3859
John Kessenich5d610ee2018-03-07 18:05:55 -07003860 if (builtIn == spv::BuiltInLayer) {
3861 // SPV_NV_viewport_array2 extension
3862 if (glslangMember.getQualifier().layoutViewportRelative){
3863 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3864 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3865 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003866 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003867 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3868 builder.addMemberDecoration(spvType, member,
3869 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3870 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3871 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3872 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003873 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003874 }
3875 if (glslangMember.getQualifier().layoutPassthrough) {
3876 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3877 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3878 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3879 }
chaoc771d89f2017-01-13 01:10:53 -08003880#endif
John Kessenich6090df02016-06-30 21:18:02 -06003881 }
3882
3883 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003884 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3885 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003886}
3887
John Kessenich6c292d32016-02-15 20:58:50 -07003888// Turn the expression forming the array size into an id.
3889// This is not quite trivial, because of specialization constants.
3890// Sometimes, a raw constant is turned into an Id, and sometimes
3891// a specialization constant expression is.
3892spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3893{
3894 // First, see if this is sized with a node, meaning a specialization constant:
3895 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3896 if (specNode != nullptr) {
3897 builder.clearAccessChain();
3898 specNode->traverse(this);
3899 return accessChainLoad(specNode->getAsTyped()->getType());
3900 }
qining25262b32016-05-06 17:25:16 -04003901
John Kessenich6c292d32016-02-15 20:58:50 -07003902 // Otherwise, need a compile-time (front end) size, get it:
3903 int size = arraySizes.getDimSize(dim);
3904 assert(size > 0);
3905 return builder.makeUintConstant(size);
3906}
3907
John Kessenich103bef92016-02-08 21:38:15 -07003908// Wrap the builder's accessChainLoad to:
3909// - localize handling of RelaxedPrecision
3910// - use the SPIR-V inferred type instead of another conversion of the glslang type
3911// (avoids unnecessary work and possible type punning for structures)
3912// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003913spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3914{
John Kessenich103bef92016-02-08 21:38:15 -07003915 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003916
3917 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3918 coherentFlags |= TranslateCoherent(type);
3919
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003920 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003921 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003922
John Kessenich5611c6d2018-04-05 11:25:02 -06003923 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
John Kessenich8985fc92020-03-03 10:25:07 -07003924 TranslateNonUniformDecoration(type.getQualifier()),
3925 nominalTypeId,
3926 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
3927 TranslateMemoryScope(coherentFlags),
3928 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003929
3930 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003931 if (type.getBasicType() == glslang::EbtBool) {
3932 if (builder.isScalarType(nominalTypeId)) {
3933 // Conversion for bool
3934 spv::Id boolType = builder.makeBoolType();
3935 if (nominalTypeId != boolType)
3936 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3937 } else if (builder.isVectorType(nominalTypeId)) {
3938 // Conversion for bvec
3939 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3940 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3941 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07003942 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
3943 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003944 }
3945 }
John Kessenich103bef92016-02-08 21:38:15 -07003946
3947 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003948}
3949
Rex Xu27253232016-02-23 17:51:09 +08003950// Wrap the builder's accessChainStore to:
3951// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003952//
3953// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003954void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3955{
3956 // Need to convert to abstract types when necessary
3957 if (type.getBasicType() == glslang::EbtBool) {
3958 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3959
3960 if (builder.isScalarType(nominalTypeId)) {
3961 // Conversion for bool
3962 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003963 if (nominalTypeId != boolType) {
3964 // keep these outside arguments, for determinant order-of-evaluation
3965 spv::Id one = builder.makeUintConstant(1);
3966 spv::Id zero = builder.makeUintConstant(0);
3967 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3968 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003969 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003970 } else if (builder.isVectorType(nominalTypeId)) {
3971 // Conversion for bvec
3972 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3973 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003974 if (nominalTypeId != bvecType) {
3975 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003976 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3977 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3978 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003979 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003980 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3981 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003982 }
3983 }
3984
Jeff Bolz36831c92018-09-05 10:11:41 -05003985 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3986 coherentFlags |= TranslateCoherent(type);
3987
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003988 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003989 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003990
Jeff Bolz36831c92018-09-05 10:11:41 -05003991 builder.accessChainStore(rvalue,
John Kessenich8985fc92020-03-03 10:25:07 -07003992 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
3993 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003994 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003995}
3996
John Kessenich4bf71552016-09-02 11:20:21 -06003997// For storing when types match at the glslang level, but not might match at the
3998// SPIR-V level.
3999//
4000// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004001// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004002// as in a member-decorated way.
4003//
4004// NOTE: This function can handle any store request; if it's not special it
4005// simplifies to a simple OpStore.
4006//
4007// Implicitly uses the existing builder.accessChain as the storage target.
4008void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4009{
John Kessenichb3e24e42016-09-11 12:33:43 -06004010 // we only do the complex path here if it's an aggregate
4011 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004012 accessChainStore(type, rValue);
4013 return;
4014 }
4015
John Kessenichb3e24e42016-09-11 12:33:43 -06004016 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004017 spv::Id rType = builder.getTypeId(rValue);
4018 spv::Id lValue = builder.accessChainGetLValue();
4019 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4020 if (lType == rType) {
4021 accessChainStore(type, rValue);
4022 return;
4023 }
4024
John Kessenichb3e24e42016-09-11 12:33:43 -06004025 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004026 // where the two types were the same type in GLSL. This requires member
4027 // by member copy, recursively.
4028
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004029 // SPIR-V 1.4 added an instruction to do help do this.
4030 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4031 // However, bool in uniform space is changed to int, so
4032 // OpCopyLogical does not work for that.
4033 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4034 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4035 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4036 if (lBool == rBool) {
4037 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4038 accessChainStore(type, logicalCopy);
4039 return;
4040 }
4041 }
4042
John Kessenichb3e24e42016-09-11 12:33:43 -06004043 // If an array, copy element by element.
4044 if (type.isArray()) {
4045 glslang::TType glslangElementType(type, 0);
4046 spv::Id elementRType = builder.getContainedTypeId(rType);
4047 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4048 // get the source member
4049 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004050
John Kessenichb3e24e42016-09-11 12:33:43 -06004051 // set up the target storage
4052 builder.clearAccessChain();
4053 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004054 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4055 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004056
John Kessenichb3e24e42016-09-11 12:33:43 -06004057 // store the member
4058 multiTypeStore(glslangElementType, elementRValue);
4059 }
4060 } else {
4061 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004062
John Kessenichb3e24e42016-09-11 12:33:43 -06004063 // loop over structure members
4064 const glslang::TTypeList& members = *type.getStruct();
4065 for (int m = 0; m < (int)members.size(); ++m) {
4066 const glslang::TType& glslangMemberType = *members[m].type;
4067
4068 // get the source member
4069 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4070 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4071
4072 // set up the target storage
4073 builder.clearAccessChain();
4074 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004075 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4076 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004077
4078 // store the member
4079 multiTypeStore(glslangMemberType, memberRValue);
4080 }
John Kessenich4bf71552016-09-02 11:20:21 -06004081 }
4082}
4083
John Kessenichf85e8062015-12-19 13:57:10 -07004084// Decide whether or not this type should be
4085// decorated with offsets and strides, and if so
4086// whether std140 or std430 rules should be applied.
4087glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004088{
John Kessenichf85e8062015-12-19 13:57:10 -07004089 // has to be a block
4090 if (type.getBasicType() != glslang::EbtBlock)
4091 return glslang::ElpNone;
4092
Chao Chen3c366992018-09-19 11:41:59 -07004093 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004094 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004095 type.getQualifier().storage != glslang::EvqBuffer &&
4096 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004097 return glslang::ElpNone;
4098
4099 // return the layout to use
4100 switch (type.getQualifier().layoutPacking) {
4101 case glslang::ElpStd140:
4102 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004103 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004104 return type.getQualifier().layoutPacking;
4105 default:
4106 return glslang::ElpNone;
4107 }
John Kessenich31ed4832015-09-09 17:51:38 -06004108}
4109
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004110// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004111int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4112 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004113{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004114 int size;
John Kessenich49987892015-12-29 17:11:44 -07004115 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004116 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4117 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004118
4119 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004120}
4121
John Kessenich49987892015-12-29 17:11:44 -07004122// 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 -07004123// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004124int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4125 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004126{
John Kessenich49987892015-12-29 17:11:44 -07004127 glslang::TType elementType;
4128 elementType.shallowCopy(matrixType);
4129 elementType.clearArraySizes();
4130
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004131 int size;
John Kessenich49987892015-12-29 17:11:44 -07004132 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004133 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4134 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004135
4136 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004137}
4138
John Kessenich5e4b1242015-08-06 22:53:06 -06004139// Given a member type of a struct, realign the current offset for it, and compute
4140// the next (not yet aligned) offset for the next member, which will get aligned
4141// on the next call.
4142// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4143// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4144// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004145void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4146 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004147{
4148 // this will get a positive value when deemed necessary
4149 nextOffset = -1;
4150
John Kessenich5e4b1242015-08-06 22:53:06 -06004151 // override anything in currentOffset with user-set offset
4152 if (memberType.getQualifier().hasOffset())
4153 currentOffset = memberType.getQualifier().layoutOffset;
4154
4155 // It could be that current linker usage in glslang updated all the layoutOffset,
4156 // in which case the following code does not matter. But, that's not quite right
4157 // once cross-compilation unit GLSL validation is done, as the original user
4158 // settings are needed in layoutOffset, and then the following will come into play.
4159
John Kessenichf85e8062015-12-19 13:57:10 -07004160 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004161 if (! memberType.getQualifier().hasOffset())
4162 currentOffset = -1;
4163
4164 return;
4165 }
4166
John Kessenichf85e8062015-12-19 13:57:10 -07004167 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004168 if (currentOffset < 0)
4169 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004170
John Kessenich5e4b1242015-08-06 22:53:06 -06004171 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4172 // but possibly not yet correctly aligned.
4173
4174 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004175 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004176 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4177 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004178
4179 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004180 // TODO: make this consistent in early phases of code:
4181 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4182 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4183 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004184 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004185 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004186 int dummySize;
4187 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4188 if (componentAlignment <= 4)
4189 memberAlignment = componentAlignment;
4190 }
4191
4192 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004193 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004194
4195 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004196 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4197 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004198 glslang::RoundToPow2(currentOffset, 16);
4199
John Kessenich5e4b1242015-08-06 22:53:06 -06004200 nextOffset = currentOffset + memberSize;
4201}
4202
David Netoa901ffe2016-06-08 14:11:40 +01004203void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004204{
David Netoa901ffe2016-06-08 14:11:40 +01004205 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4206 switch (glslangBuiltIn)
4207 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004208 case glslang::EbvPointSize:
4209#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004210 case glslang::EbvClipDistance:
4211 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004212 case glslang::EbvViewportMaskNV:
4213 case glslang::EbvSecondaryPositionNV:
4214 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004215 case glslang::EbvPositionPerViewNV:
4216 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004217 case glslang::EbvTaskCountNV:
4218 case glslang::EbvPrimitiveCountNV:
4219 case glslang::EbvPrimitiveIndicesNV:
4220 case glslang::EbvClipDistancePerViewNV:
4221 case glslang::EbvCullDistancePerViewNV:
4222 case glslang::EbvLayerPerViewNV:
4223 case glslang::EbvMeshViewCountNV:
4224 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004225#endif
David Netoa901ffe2016-06-08 14:11:40 +01004226 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4227 // Alternately, we could just call this for any glslang built-in, since the
4228 // capability already guards against duplicates.
4229 TranslateBuiltInDecoration(glslangBuiltIn, false);
4230 break;
4231 default:
4232 // Capabilities were already generated when the struct was declared.
4233 break;
4234 }
John Kessenichebb50532016-05-16 19:22:05 -06004235}
4236
John Kessenich6fccb3c2016-09-19 16:01:41 -06004237bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004238{
John Kessenicheee9d532016-09-19 18:09:30 -06004239 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004240}
4241
John Kessenichd41993d2017-09-10 15:21:05 -06004242// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004243// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4244// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004245bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004246{
John Kessenich6a14f782017-12-04 02:48:10 -07004247 assert(qualifier == glslang::EvqIn ||
4248 qualifier == glslang::EvqOut ||
4249 qualifier == glslang::EvqInOut ||
4250 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004251 return qualifier != glslang::EvqConstReadOnly;
4252}
4253
4254// Is parameter pass-by-original?
4255bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4256 bool implicitThisParam)
4257{
4258 if (implicitThisParam) // implicit this
4259 return true;
4260 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004261 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004262 return paramType.containsOpaque() || // sampler, etc.
4263 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4264}
4265
John Kessenich140f3df2015-06-26 16:58:36 -06004266// Make all the functions, skeletally, without actually visiting their bodies.
4267void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4268{
John Kessenich8985fc92020-03-03 10:25:07 -07004269 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4270 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004271 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4272 if (paramPrecision != spv::NoPrecision)
4273 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004274 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004275 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004276 // Original and non-writable params pass the pointer directly and
4277 // use restrict/aliased, others are stored to a pointer in Function
4278 // memory and use RestrictPointer/AliasedPointer.
4279 if (originalParam(type.getQualifier().storage, type, false) ||
4280 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004281 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4282 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004283 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004284 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4285 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004286 }
4287 }
John Kessenichfad62972017-07-18 02:35:46 -06004288 };
4289
John Kessenich140f3df2015-06-26 16:58:36 -06004290 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4291 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004292 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004293 continue;
4294
4295 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004296 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004297 //
qining25262b32016-05-06 17:25:16 -04004298 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004299 // function. What it is an address of varies:
4300 //
John Kessenich4bf71552016-09-02 11:20:21 -06004301 // - "in" parameters not marked as "const" can be written to without modifying the calling
4302 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004303 //
4304 // - "const in" parameters can just be the r-value, as no writes need occur.
4305 //
John Kessenich4bf71552016-09-02 11:20:21 -06004306 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4307 // 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 -06004308
4309 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004310 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004311 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4312
John Kessenich155d3512019-08-08 23:29:20 -06004313#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004314 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4315 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004316#else
4317 bool implicitThis = false;
4318#endif
John Kessenich37789792017-03-21 23:56:40 -06004319
John Kessenichfad62972017-07-18 02:35:46 -06004320 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004321 for (int p = 0; p < (int)parameters.size(); ++p) {
4322 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4323 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004324 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004325 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004326 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004327 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4328 else
John Kessenich4bf71552016-09-02 11:20:21 -06004329 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004330 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004331 paramTypes.push_back(typeId);
4332 }
4333
4334 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004335 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4336 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004337 glslFunction->getName().c_str(), paramTypes,
4338 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004339 if (implicitThis)
4340 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004341
4342 // Track function to emit/call later
4343 functionMap[glslFunction->getName().c_str()] = function;
4344
4345 // Set the parameter id's
4346 for (int p = 0; p < (int)parameters.size(); ++p) {
4347 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4348 // give a name too
4349 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004350
4351 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004352 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004353 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004354 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004355 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004356 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004357 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004358 }
4359 }
4360}
4361
4362// Process all the initializers, while skipping the functions and link objects
4363void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4364{
4365 builder.setBuildPoint(shaderEntry->getLastBlock());
4366 for (int i = 0; i < (int)initializers.size(); ++i) {
4367 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004368 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4369 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004370
4371 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004372 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004373 initializer->traverse(this);
4374 }
4375 }
4376}
4377
4378// Process all the functions, while skipping initializers.
4379void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4380{
4381 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4382 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004383 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004384 node->traverse(this);
4385 }
4386}
4387
4388void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4389{
qining25262b32016-05-06 17:25:16 -04004390 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004391 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004392 currentFunction = functionMap[node->getName().c_str()];
4393 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004394 builder.setBuildPoint(functionBlock);
4395}
4396
John Kessenich8985fc92020-03-03 10:25:07 -07004397void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4398 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004399{
Rex Xufc618912015-09-09 16:42:49 +08004400 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004401
4402 glslang::TSampler sampler = {};
4403 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004404#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004405 bool f16ShadowCompare = false;
4406#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004407 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004408 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4409 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004410#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004411 f16ShadowCompare = sampler.shadow &&
4412 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004413#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004414 }
4415
John Kessenich140f3df2015-06-26 16:58:36 -06004416 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4417 builder.clearAccessChain();
4418 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004419
John Kessenicha28f7a72019-08-06 07:00:58 -06004420#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004421 // Special case l-value operands
4422 bool lvalue = false;
4423 switch (node.getOp()) {
4424 case glslang::EOpImageAtomicAdd:
4425 case glslang::EOpImageAtomicMin:
4426 case glslang::EOpImageAtomicMax:
4427 case glslang::EOpImageAtomicAnd:
4428 case glslang::EOpImageAtomicOr:
4429 case glslang::EOpImageAtomicXor:
4430 case glslang::EOpImageAtomicExchange:
4431 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004432 case glslang::EOpImageAtomicLoad:
4433 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004434 if (i == 0)
4435 lvalue = true;
4436 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004437 case glslang::EOpSparseImageLoad:
4438 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4439 lvalue = true;
4440 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004441 case glslang::EOpSparseTexture:
4442 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4443 lvalue = true;
4444 break;
4445 case glslang::EOpSparseTextureClamp:
4446 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4447 lvalue = true;
4448 break;
4449 case glslang::EOpSparseTextureLod:
4450 case glslang::EOpSparseTextureOffset:
4451 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4452 lvalue = true;
4453 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004454 case glslang::EOpSparseTextureFetch:
4455 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4456 lvalue = true;
4457 break;
4458 case glslang::EOpSparseTextureFetchOffset:
4459 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4460 lvalue = true;
4461 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004462 case glslang::EOpSparseTextureLodOffset:
4463 case glslang::EOpSparseTextureGrad:
4464 case glslang::EOpSparseTextureOffsetClamp:
4465 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4466 lvalue = true;
4467 break;
4468 case glslang::EOpSparseTextureGradOffset:
4469 case glslang::EOpSparseTextureGradClamp:
4470 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4471 lvalue = true;
4472 break;
4473 case glslang::EOpSparseTextureGradOffsetClamp:
4474 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4475 lvalue = true;
4476 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004477 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004478 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4479 lvalue = true;
4480 break;
4481 case glslang::EOpSparseTextureGatherOffset:
4482 case glslang::EOpSparseTextureGatherOffsets:
4483 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4484 lvalue = true;
4485 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004486 case glslang::EOpSparseTextureGatherLod:
4487 if (i == 3)
4488 lvalue = true;
4489 break;
4490 case glslang::EOpSparseTextureGatherLodOffset:
4491 case glslang::EOpSparseTextureGatherLodOffsets:
4492 if (i == 4)
4493 lvalue = true;
4494 break;
Rex Xu129799a2017-07-05 17:23:28 +08004495 case glslang::EOpSparseImageLoadLod:
4496 if (i == 3)
4497 lvalue = true;
4498 break;
Chao Chen3a137962018-09-19 11:41:27 -07004499 case glslang::EOpImageSampleFootprintNV:
4500 if (i == 4)
4501 lvalue = true;
4502 break;
4503 case glslang::EOpImageSampleFootprintClampNV:
4504 case glslang::EOpImageSampleFootprintLodNV:
4505 if (i == 5)
4506 lvalue = true;
4507 break;
4508 case glslang::EOpImageSampleFootprintGradNV:
4509 if (i == 6)
4510 lvalue = true;
4511 break;
4512 case glslang::EOpImageSampleFootprintGradClampNV:
4513 if (i == 7)
4514 lvalue = true;
4515 break;
Rex Xufc618912015-09-09 16:42:49 +08004516 default:
4517 break;
4518 }
4519
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004520 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004521 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004522 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4523 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4524 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004525#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004526 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004527 }
4528}
4529
John Kessenichfc51d282015-08-19 13:34:18 -06004530void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004531{
John Kessenichfc51d282015-08-19 13:34:18 -06004532 builder.clearAccessChain();
4533 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004534 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004535}
John Kessenich140f3df2015-06-26 16:58:36 -06004536
John Kessenichfc51d282015-08-19 13:34:18 -06004537spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4538{
John Kesseniche485c7a2017-05-31 18:50:53 -06004539 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004540 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004541
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004542 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004543
John Kessenichfc51d282015-08-19 13:34:18 -06004544 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004545
John Kessenichf43c7392019-03-31 10:51:57 -06004546 const glslang::TType &imageType = node->getAsAggregate()
4547 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4548 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004549 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004550#ifdef GLSLANG_WEB
4551 const bool f16ShadowCompare = false;
4552#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004553 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004554 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4555 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004556#endif
4557
John Kessenichf43c7392019-03-31 10:51:57 -06004558 const auto signExtensionMask = [&]() {
4559 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4560 if (sampler.type == glslang::EbtUint)
4561 return spv::ImageOperandsZeroExtendMask;
4562 else if (sampler.type == glslang::EbtInt)
4563 return spv::ImageOperandsSignExtendMask;
4564 }
4565 return spv::ImageOperandsMaskNone;
4566 };
4567
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004568 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4569
John Kessenichfc51d282015-08-19 13:34:18 -06004570 std::vector<spv::Id> arguments;
4571 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004572 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004573 else
4574 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004575 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004576
4577 spv::Builder::TextureParameters params = { };
4578 params.sampler = arguments[0];
4579
Rex Xu04db3f52015-09-16 11:44:02 +08004580 glslang::TCrackedTextureOp cracked;
4581 node->crackTexture(sampler, cracked);
4582
amhagan05506bb2017-06-13 16:53:02 -04004583 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004584
John Kessenichfc51d282015-08-19 13:34:18 -06004585 // Check for queries
4586 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004587 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4588 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004589 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004590
John Kessenichfc51d282015-08-19 13:34:18 -06004591 switch (node->getOp()) {
4592 case glslang::EOpImageQuerySize:
4593 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004594 if (arguments.size() > 1) {
4595 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004596 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004597 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004598 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004599#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004600 case glslang::EOpImageQuerySamples:
4601 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004602 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004603 case glslang::EOpTextureQueryLod:
4604 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004605 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004606 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004607 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004608 case glslang::EOpSparseTexelsResident:
4609 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004610#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004611 default:
4612 assert(0);
4613 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004614 }
John Kessenich140f3df2015-06-26 16:58:36 -06004615 }
4616
LoopDawg4425f242018-02-18 11:40:01 -07004617 int components = node->getType().getVectorSize();
4618
4619 if (node->getOp() == glslang::EOpTextureFetch) {
4620 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4621 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4622 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4623 // here around e.g. which ones return scalars or other types.
4624 components = 4;
4625 }
4626
4627 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4628
4629 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4630
Rex Xufc618912015-09-09 16:42:49 +08004631 // Check for image functions other than queries
4632 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004633 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004634 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004635 spv::IdImmediate image = { true, *(opIt++) };
4636 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004637
4638 // Handle subpass operations
4639 // TODO: GLSL should change to have the "MS" only on the type rather than the
4640 // built-in function.
4641 if (cracked.subpass) {
4642 // add on the (0,0) coordinate
4643 spv::Id zero = builder.makeIntConstant(0);
4644 std::vector<spv::Id> comps;
4645 comps.push_back(zero);
4646 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004647 spv::IdImmediate coord = { true,
4648 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4649 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004650 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4651 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004652 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004653 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4654 }
4655 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004656 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004657 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004658 spv::IdImmediate imageOperand = { true, *(opIt++) };
4659 operands.push_back(imageOperand);
4660 }
John Kessenich6c292d32016-02-15 20:58:50 -07004661 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004662 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4663 builder.setPrecision(result, precision);
4664 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004665 }
4666
John Kessenich149afc32018-08-14 13:31:43 -06004667 spv::IdImmediate coord = { true, *(opIt++) };
4668 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004669 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004670 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004671 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004672 mask = mask | spv::ImageOperandsSampleMask;
4673 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004674 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004675 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4676 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004677 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004678 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004679 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4680 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004681 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004682 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004683 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4684 operands.push_back(imageOperands);
4685 }
4686 if (mask & spv::ImageOperandsSampleMask) {
4687 spv::IdImmediate imageOperand = { true, *opIt++ };
4688 operands.push_back(imageOperand);
4689 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004690 if (mask & spv::ImageOperandsLodMask) {
4691 spv::IdImmediate imageOperand = { true, *opIt++ };
4692 operands.push_back(imageOperand);
4693 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004694 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004695 spv::IdImmediate imageOperand = { true,
4696 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004697 operands.push_back(imageOperand);
4698 }
4699
John Kessenich149afc32018-08-14 13:31:43 -06004700 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004701 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004702
John Kessenich149afc32018-08-14 13:31:43 -06004703 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004704 builder.setPrecision(result[0], precision);
4705
4706 // If needed, add a conversion constructor to the proper size.
4707 if (components != node->getType().getVectorSize())
4708 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4709
4710 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004711 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004712
Jeff Bolz36831c92018-09-05 10:11:41 -05004713 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004714 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004715 spv::IdImmediate texel = { true, *(opIt + 1) };
4716 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004717 } else {
4718 spv::IdImmediate texel = { true, *opIt };
4719 operands.push_back(texel);
4720 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004721
4722 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004723 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004724 mask = mask | spv::ImageOperandsSampleMask;
4725 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004726 if (cracked.lod) {
4727 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4728 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4729 mask = mask | spv::ImageOperandsLodMask;
4730 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004731 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4732 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004733 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004734 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004735 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4736 operands.push_back(imageOperands);
4737 }
4738 if (mask & spv::ImageOperandsSampleMask) {
4739 spv::IdImmediate imageOperand = { true, *opIt++ };
4740 operands.push_back(imageOperand);
4741 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004742 if (mask & spv::ImageOperandsLodMask) {
4743 spv::IdImmediate imageOperand = { true, *opIt++ };
4744 operands.push_back(imageOperand);
4745 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004746 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004747 spv::IdImmediate imageOperand = { true,
4748 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004749 operands.push_back(imageOperand);
4750 }
4751
John Kessenich56bab042015-09-16 10:54:31 -06004752 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004753 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004754 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004755 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004756 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4757 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004758 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004759 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004760 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4761
Jeff Bolz36831c92018-09-05 10:11:41 -05004762 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) {
Rex Xu129799a2017-07-05 17:23:28 +08004767 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4768 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4769
Jeff Bolz36831c92018-09-05 10:11:41 -05004770 mask = mask | spv::ImageOperandsLodMask;
4771 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004772 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4773 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004774 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004775 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004776 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004777 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004778 }
4779 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004780 spv::IdImmediate imageOperand = { true, *opIt++ };
4781 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004782 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004783 if (mask & spv::ImageOperandsLodMask) {
4784 spv::IdImmediate imageOperand = { true, *opIt++ };
4785 operands.push_back(imageOperand);
4786 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004787 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07004788 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
4789 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004790 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004791 }
4792
4793 // Create the return type that was a special structure
4794 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004795 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004796 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4797 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4798
4799 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4800
4801 // Decode the return type
4802 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4803 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004804 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004805 // Process image atomic operations
4806
4807 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4808 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004809 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004810 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004811 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004812
Jeff Bolz36831c92018-09-05 10:11:41 -05004813 spv::Id resultTypeId;
4814 // imageAtomicStore has a void return type so base the pointer type on
4815 // the type of the value operand.
4816 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08004817 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05004818 } else {
4819 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4820 }
John Kessenich56bab042015-09-16 10:54:31 -06004821 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004822
4823 std::vector<spv::Id> operands;
4824 operands.push_back(pointer);
4825 for (; opIt != arguments.end(); ++opIt)
4826 operands.push_back(*opIt);
4827
John Kessenich8985fc92020-03-03 10:25:07 -07004828 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
4829 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004830 }
4831 }
4832
John Kessenicha28f7a72019-08-06 07:00:58 -06004833#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004834 // Check for fragment mask functions other than queries
4835 if (cracked.fragMask) {
4836 assert(sampler.ms);
4837
4838 auto opIt = arguments.begin();
4839 std::vector<spv::Id> operands;
4840
4841 // Extract the image if necessary
4842 if (builder.isSampledImage(params.sampler))
4843 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4844
4845 operands.push_back(params.sampler);
4846 ++opIt;
4847
4848 if (sampler.isSubpass()) {
4849 // add on the (0,0) coordinate
4850 spv::Id zero = builder.makeIntConstant(0);
4851 std::vector<spv::Id> comps;
4852 comps.push_back(zero);
4853 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07004854 operands.push_back(builder.makeCompositeConstant(
4855 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04004856 }
4857
4858 for (; opIt != arguments.end(); ++opIt)
4859 operands.push_back(*opIt);
4860
4861 spv::Op fragMaskOp = spv::OpNop;
4862 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4863 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4864 else if (node->getOp() == glslang::EOpFragmentFetch)
4865 fragMaskOp = spv::OpFragmentFetchAMD;
4866
4867 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4868 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4869 return builder.createOp(fragMaskOp, resultType(), operands);
4870 }
4871#endif
4872
Rex Xufc618912015-09-09 16:42:49 +08004873 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004874 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004875 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004876 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08004877
John Kessenichfc51d282015-08-19 13:34:18 -06004878 // check for bias argument
4879 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004880 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004881 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004882 if (cracked.gather)
4883 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004884
4885 if (f16ShadowCompare)
4886 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004887 if (cracked.offset)
4888 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004889 else if (cracked.offsets)
4890 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004891 if (cracked.grad)
4892 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004893 if (cracked.lodClamp)
4894 ++nonBiasArgCount;
4895 if (sparse)
4896 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004897 if (imageFootprint)
4898 //Following three extra arguments
4899 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4900 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06004901 if ((int)arguments.size() > nonBiasArgCount)
4902 bias = true;
4903 }
4904
John Kessenicha5c33d62016-06-02 23:45:21 -06004905 // See if the sampler param should really be just the SPV image part
4906 if (cracked.fetch) {
4907 // a fetch needs to have the image extracted first
4908 if (builder.isSampledImage(params.sampler))
4909 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4910 }
4911
John Kessenicha28f7a72019-08-06 07:00:58 -06004912#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08004913 if (cracked.gather) {
4914 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4915 if (bias || cracked.lod ||
4916 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4917 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004918 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004919 }
4920 }
4921#endif
4922
John Kessenichfc51d282015-08-19 13:34:18 -06004923 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004924
John Kessenichfc51d282015-08-19 13:34:18 -06004925 params.coords = arguments[1];
4926 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004927 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004928
4929 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004930 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004931 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004932 ++extraArgs;
4933 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004934 params.Dref = arguments[2];
4935 ++extraArgs;
4936 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004937 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004938 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004939 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004940 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004941 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004942 dRefComp = builder.getNumComponents(params.coords) - 1;
4943 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07004944 params.Dref = builder.createCompositeExtract(params.coords,
4945 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06004946 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004947
4948 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004949 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004950 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004951 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06004952 } else if (glslangIntermediate->getStage() != EShLangFragment &&
4953 !(glslangIntermediate->getStage() == EShLangCompute &&
4954 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07004955 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4956 noImplicitLod = true;
4957 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004958
4959 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004960 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004961 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004962 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004963 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004964
4965 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004966 if (cracked.grad) {
4967 params.gradX = arguments[2 + extraArgs];
4968 params.gradY = arguments[3 + extraArgs];
4969 extraArgs += 2;
4970 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004971
4972 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004973 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004974 params.offset = arguments[2 + extraArgs];
4975 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004976 } else if (cracked.offsets) {
4977 params.offsets = arguments[2 + extraArgs];
4978 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004979 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004980
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004981#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06004982 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004983 if (cracked.lodClamp) {
4984 params.lodClamp = arguments[2 + extraArgs];
4985 ++extraArgs;
4986 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004987 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004988 if (sparse) {
4989 params.texelOut = arguments[2 + extraArgs];
4990 ++extraArgs;
4991 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004992 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004993 if (cracked.gather && ! sampler.shadow) {
4994 // default component is 0, if missing, otherwise an argument
4995 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004996 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004997 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004998 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004999 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005000 }
Chao Chen3a137962018-09-19 11:41:27 -07005001 spv::Id resultStruct = spv::NoResult;
5002 if (imageFootprint) {
5003 //Following three extra arguments
5004 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5005 params.granularity = arguments[2 + extraArgs];
5006 params.coarse = arguments[3 + extraArgs];
5007 resultStruct = arguments[4 + extraArgs];
5008 extraArgs += 3;
5009 }
5010#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005011 // bias
5012 if (bias) {
5013 params.bias = arguments[2 + extraArgs];
5014 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005015 }
John Kessenichfc51d282015-08-19 13:34:18 -06005016
John Kessenicha28f7a72019-08-06 07:00:58 -06005017#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005018 if (imageFootprint) {
5019 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5020 builder.addCapability(spv::CapabilityImageFootprintNV);
5021
5022
5023 //resultStructType(OpenGL type) contains 5 elements:
5024 //struct gl_TextureFootprint2DNV {
5025 // uvec2 anchor;
5026 // uvec2 offset;
5027 // uvec2 mask;
5028 // uint lod;
5029 // uint granularity;
5030 //};
5031 //or
5032 //struct gl_TextureFootprint3DNV {
5033 // uvec3 anchor;
5034 // uvec3 offset;
5035 // uvec2 mask;
5036 // uint lod;
5037 // uint granularity;
5038 //};
5039 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5040 assert(builder.isStructType(resultStructType));
5041
5042 //resType (SPIR-V type) contains 6 elements:
5043 //Member 0 must be a Boolean type scalar(LOD),
5044 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5045 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5046 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5047 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5048 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5049 std::vector<spv::Id> members;
5050 members.push_back(resultType());
5051 for (int i = 0; i < 5; i++) {
5052 members.push_back(builder.getContainedTypeId(resultStructType, i));
5053 }
5054 spv::Id resType = builder.makeStructType(members, "ResType");
5055
5056 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005057 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5058 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005059
5060 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5061 for (int i = 0; i < 5; i++) {
5062 builder.clearAccessChain();
5063 builder.setAccessChainLValue(resultStruct);
5064
5065 //Accessing to a struct we created, no coherent flag is set
5066 spv::Builder::AccessChain::CoherentFlags flags;
5067 flags.clear();
5068
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005069 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005070 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
5071 i+1));
Chao Chen3a137962018-09-19 11:41:27 -07005072 }
5073 return builder.createCompositeExtract(res, resultType(), 0);
5074 }
5075#endif
5076
John Kessenich65336482016-06-16 14:06:26 -06005077 // projective component (might not to move)
5078 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5079 // are divided by the last component of P."
5080 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5081 // unused components will appear after all used components."
5082 if (cracked.proj) {
5083 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5084 int projTargetComp;
5085 switch (sampler.dim) {
5086 case glslang::Esd1D: projTargetComp = 1; break;
5087 case glslang::Esd2D: projTargetComp = 2; break;
5088 case glslang::EsdRect: projTargetComp = 2; break;
5089 default: projTargetComp = projSourceComp; break;
5090 }
5091 // copy the projective coordinate if we have to
5092 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005093 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005094 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005095 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005096 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005097 }
5098 }
5099
John Kessenichf8d1d742019-10-21 06:55:11 -06005100#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005101 // nonprivate
5102 if (imageType.getQualifier().nonprivate) {
5103 params.nonprivate = true;
5104 }
5105
5106 // volatile
5107 if (imageType.getQualifier().volatil) {
5108 params.volatil = true;
5109 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005110#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005111
St0fFa1184dd2018-04-09 21:08:14 +02005112 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005113 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5114 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005115 );
LoopDawg4425f242018-02-18 11:40:01 -07005116
5117 if (components != node->getType().getVectorSize())
5118 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5119
5120 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005121}
5122
5123spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5124{
5125 // Grab the function's pointer from the previously created function
5126 spv::Function* function = functionMap[node->getName().c_str()];
5127 if (! function)
5128 return 0;
5129
5130 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5131 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5132
5133 // See comments in makeFunctions() for details about the semantics for parameter passing.
5134 //
5135 // These imply we need a four step process:
5136 // 1. Evaluate the arguments
5137 // 2. Allocate and make copies of in, out, and inout arguments
5138 // 3. Make the call
5139 // 4. Copy back the results
5140
John Kessenichd3ed90b2018-05-04 11:43:03 -06005141 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005142 std::vector<spv::Builder::AccessChain> lValues;
5143 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005144 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005145 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005146 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005147 // build l-value
5148 builder.clearAccessChain();
5149 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005150 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005151 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005152 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005153 // save l-value
5154 lValues.push_back(builder.getAccessChain());
5155 } else {
5156 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005157 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005158 }
5159 }
5160
5161 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5162 // copy the original into that space.
5163 //
5164 // Also, build up the list of actual arguments to pass in for the call
5165 int lValueCount = 0;
5166 int rValueCount = 0;
5167 std::vector<spv::Id> spvArgs;
5168 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5169 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005170 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005171 builder.setAccessChain(lValues[lValueCount]);
5172 arg = builder.accessChainGetLValue();
5173 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005174 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005175 // need space to hold the copy
John Kessenich8985fc92020-03-03 10:25:07 -07005176 arg = builder.createVariable(spv::StorageClassFunction,
5177 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005178 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5179 // need to copy the input into output space
5180 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005181 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005182 builder.clearAccessChain();
5183 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005184 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005185 }
5186 ++lValueCount;
5187 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005188 // process r-value, which involves a copy for a type mismatch
5189 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5190 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5191 builder.clearAccessChain();
5192 builder.setAccessChainLValue(argCopy);
5193 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5194 arg = builder.createLoad(argCopy);
5195 } else
5196 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005197 ++rValueCount;
5198 }
5199 spvArgs.push_back(arg);
5200 }
5201
5202 // 3. Make the call.
5203 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005204 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005205
5206 // 4. Copy back out an "out" arguments.
5207 lValueCount = 0;
5208 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005209 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005210 ++lValueCount;
5211 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005212 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5213 spv::Id copy = builder.createLoad(spvArgs[a]);
5214 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005215 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005216 }
5217 ++lValueCount;
5218 }
5219 }
5220
5221 return result;
5222}
5223
5224// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005225spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005226 spv::Id typeId, spv::Id left, spv::Id right,
5227 glslang::TBasicType typeProxy, bool reduceComparison)
5228{
John Kessenich66011cb2018-03-06 16:12:04 -07005229 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5230 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005231 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005232
5233 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005234 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005235 bool comparison = false;
5236
5237 switch (op) {
5238 case glslang::EOpAdd:
5239 case glslang::EOpAddAssign:
5240 if (isFloat)
5241 binOp = spv::OpFAdd;
5242 else
5243 binOp = spv::OpIAdd;
5244 break;
5245 case glslang::EOpSub:
5246 case glslang::EOpSubAssign:
5247 if (isFloat)
5248 binOp = spv::OpFSub;
5249 else
5250 binOp = spv::OpISub;
5251 break;
5252 case glslang::EOpMul:
5253 case glslang::EOpMulAssign:
5254 if (isFloat)
5255 binOp = spv::OpFMul;
5256 else
5257 binOp = spv::OpIMul;
5258 break;
5259 case glslang::EOpVectorTimesScalar:
5260 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005261 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005262 if (builder.isVector(right))
5263 std::swap(left, right);
5264 assert(builder.isScalar(right));
5265 needMatchingVectors = false;
5266 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005267 } else if (isFloat)
5268 binOp = spv::OpFMul;
5269 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005270 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005271 break;
5272 case glslang::EOpVectorTimesMatrix:
5273 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005274 binOp = spv::OpVectorTimesMatrix;
5275 break;
5276 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005277 binOp = spv::OpMatrixTimesVector;
5278 break;
5279 case glslang::EOpMatrixTimesScalar:
5280 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005281 binOp = spv::OpMatrixTimesScalar;
5282 break;
5283 case glslang::EOpMatrixTimesMatrix:
5284 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005285 binOp = spv::OpMatrixTimesMatrix;
5286 break;
5287 case glslang::EOpOuterProduct:
5288 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005289 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005290 break;
5291
5292 case glslang::EOpDiv:
5293 case glslang::EOpDivAssign:
5294 if (isFloat)
5295 binOp = spv::OpFDiv;
5296 else if (isUnsigned)
5297 binOp = spv::OpUDiv;
5298 else
5299 binOp = spv::OpSDiv;
5300 break;
5301 case glslang::EOpMod:
5302 case glslang::EOpModAssign:
5303 if (isFloat)
5304 binOp = spv::OpFMod;
5305 else if (isUnsigned)
5306 binOp = spv::OpUMod;
5307 else
5308 binOp = spv::OpSMod;
5309 break;
5310 case glslang::EOpRightShift:
5311 case glslang::EOpRightShiftAssign:
5312 if (isUnsigned)
5313 binOp = spv::OpShiftRightLogical;
5314 else
5315 binOp = spv::OpShiftRightArithmetic;
5316 break;
5317 case glslang::EOpLeftShift:
5318 case glslang::EOpLeftShiftAssign:
5319 binOp = spv::OpShiftLeftLogical;
5320 break;
5321 case glslang::EOpAnd:
5322 case glslang::EOpAndAssign:
5323 binOp = spv::OpBitwiseAnd;
5324 break;
5325 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005326 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005327 binOp = spv::OpLogicalAnd;
5328 break;
5329 case glslang::EOpInclusiveOr:
5330 case glslang::EOpInclusiveOrAssign:
5331 binOp = spv::OpBitwiseOr;
5332 break;
5333 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005334 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005335 binOp = spv::OpLogicalOr;
5336 break;
5337 case glslang::EOpExclusiveOr:
5338 case glslang::EOpExclusiveOrAssign:
5339 binOp = spv::OpBitwiseXor;
5340 break;
5341 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005342 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005343 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005344 break;
5345
Ian Romanickb3bd4022019-01-21 08:57:25 -08005346 case glslang::EOpAbsDifference:
5347 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5348 break;
5349
5350 case glslang::EOpAddSaturate:
5351 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5352 break;
5353
5354 case glslang::EOpSubSaturate:
5355 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5356 break;
5357
5358 case glslang::EOpAverage:
5359 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5360 break;
5361
5362 case glslang::EOpAverageRounded:
5363 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5364 break;
5365
5366 case glslang::EOpMul32x16:
5367 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5368 break;
5369
John Kessenich140f3df2015-06-26 16:58:36 -06005370 case glslang::EOpLessThan:
5371 case glslang::EOpGreaterThan:
5372 case glslang::EOpLessThanEqual:
5373 case glslang::EOpGreaterThanEqual:
5374 case glslang::EOpEqual:
5375 case glslang::EOpNotEqual:
5376 case glslang::EOpVectorEqual:
5377 case glslang::EOpVectorNotEqual:
5378 comparison = true;
5379 break;
5380 default:
5381 break;
5382 }
5383
John Kessenich7c1aa102015-10-15 13:29:11 -06005384 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005385 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005386 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005387 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5388 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005389 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005390
5391 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005392 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005393 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005394
qining25262b32016-05-06 17:25:16 -04005395 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005396 decorations.addNoContraction(builder, result);
5397 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005398 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005399 }
5400
5401 if (! comparison)
5402 return 0;
5403
John Kessenich7c1aa102015-10-15 13:29:11 -06005404 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005405
John Kessenich4583b612016-08-07 19:14:22 -06005406 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005407 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5408 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005409 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005410 return result;
5411 }
John Kessenich140f3df2015-06-26 16:58:36 -06005412
5413 switch (op) {
5414 case glslang::EOpLessThan:
5415 if (isFloat)
5416 binOp = spv::OpFOrdLessThan;
5417 else if (isUnsigned)
5418 binOp = spv::OpULessThan;
5419 else
5420 binOp = spv::OpSLessThan;
5421 break;
5422 case glslang::EOpGreaterThan:
5423 if (isFloat)
5424 binOp = spv::OpFOrdGreaterThan;
5425 else if (isUnsigned)
5426 binOp = spv::OpUGreaterThan;
5427 else
5428 binOp = spv::OpSGreaterThan;
5429 break;
5430 case glslang::EOpLessThanEqual:
5431 if (isFloat)
5432 binOp = spv::OpFOrdLessThanEqual;
5433 else if (isUnsigned)
5434 binOp = spv::OpULessThanEqual;
5435 else
5436 binOp = spv::OpSLessThanEqual;
5437 break;
5438 case glslang::EOpGreaterThanEqual:
5439 if (isFloat)
5440 binOp = spv::OpFOrdGreaterThanEqual;
5441 else if (isUnsigned)
5442 binOp = spv::OpUGreaterThanEqual;
5443 else
5444 binOp = spv::OpSGreaterThanEqual;
5445 break;
5446 case glslang::EOpEqual:
5447 case glslang::EOpVectorEqual:
5448 if (isFloat)
5449 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005450 else if (isBool)
5451 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005452 else
5453 binOp = spv::OpIEqual;
5454 break;
5455 case glslang::EOpNotEqual:
5456 case glslang::EOpVectorNotEqual:
5457 if (isFloat)
5458 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005459 else if (isBool)
5460 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005461 else
5462 binOp = spv::OpINotEqual;
5463 break;
5464 default:
5465 break;
5466 }
5467
qining25262b32016-05-06 17:25:16 -04005468 if (binOp != spv::OpNop) {
5469 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005470 decorations.addNoContraction(builder, result);
5471 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005472 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005473 }
John Kessenich140f3df2015-06-26 16:58:36 -06005474
5475 return 0;
5476}
5477
John Kessenich04bb8a02015-12-12 12:28:14 -07005478//
5479// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5480// These can be any of:
5481//
5482// matrix * scalar
5483// scalar * matrix
5484// matrix * matrix linear algebraic
5485// matrix * vector
5486// vector * matrix
5487// matrix * matrix componentwise
5488// matrix op matrix op in {+, -, /}
5489// matrix op scalar op in {+, -, /}
5490// scalar op matrix op in {+, -, /}
5491//
John Kessenichead86222018-03-28 18:01:20 -06005492spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5493 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005494{
5495 bool firstClass = true;
5496
5497 // First, handle first-class matrix operations (* and matrix/scalar)
5498 switch (op) {
5499 case spv::OpFDiv:
5500 if (builder.isMatrix(left) && builder.isScalar(right)) {
5501 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005502 spv::Id resultType = builder.getTypeId(right);
5503 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005504 op = spv::OpMatrixTimesScalar;
5505 } else
5506 firstClass = false;
5507 break;
5508 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005509 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005510 std::swap(left, right);
5511 assert(builder.isScalar(right));
5512 break;
5513 case spv::OpVectorTimesMatrix:
5514 assert(builder.isVector(left));
5515 assert(builder.isMatrix(right));
5516 break;
5517 case spv::OpMatrixTimesVector:
5518 assert(builder.isMatrix(left));
5519 assert(builder.isVector(right));
5520 break;
5521 case spv::OpMatrixTimesMatrix:
5522 assert(builder.isMatrix(left));
5523 assert(builder.isMatrix(right));
5524 break;
5525 default:
5526 firstClass = false;
5527 break;
5528 }
5529
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005530 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5531 firstClass = true;
5532
qining25262b32016-05-06 17:25:16 -04005533 if (firstClass) {
5534 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005535 decorations.addNoContraction(builder, result);
5536 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005537 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005538 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005539
LoopDawg592860c2016-06-09 08:57:35 -06005540 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005541 // The result type of all of them is the same type as the (a) matrix operand.
5542 // The algorithm is to:
5543 // - break the matrix(es) into vectors
5544 // - smear any scalar to a vector
5545 // - do vector operations
5546 // - make a matrix out the vector results
5547 switch (op) {
5548 case spv::OpFAdd:
5549 case spv::OpFSub:
5550 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005551 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005552 case spv::OpFMul:
5553 {
5554 // one time set up...
5555 bool leftMat = builder.isMatrix(left);
5556 bool rightMat = builder.isMatrix(right);
5557 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5558 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5559 spv::Id scalarType = builder.getScalarTypeId(typeId);
5560 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5561 std::vector<spv::Id> results;
5562 spv::Id smearVec = spv::NoResult;
5563 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005564 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005565 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005566 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005567
5568 // do each vector op
5569 for (unsigned int c = 0; c < numCols; ++c) {
5570 std::vector<unsigned int> indexes;
5571 indexes.push_back(c);
5572 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5573 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005574 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005575 decorations.addNoContraction(builder, result);
5576 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005577 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005578 }
5579
5580 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005581 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005582 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005583 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005584 }
5585 default:
5586 assert(0);
5587 return spv::NoResult;
5588 }
5589}
5590
John Kessenichead86222018-03-28 18:01:20 -06005591spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005592 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005593{
5594 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005595 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005596 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005597 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5598 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005599
5600 switch (op) {
5601 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005602 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005603 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005604 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005605 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005606 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005607 unaryOp = spv::OpSNegate;
5608 break;
5609
5610 case glslang::EOpLogicalNot:
5611 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005612 unaryOp = spv::OpLogicalNot;
5613 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005614 case glslang::EOpBitwiseNot:
5615 unaryOp = spv::OpNot;
5616 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005617
John Kessenich140f3df2015-06-26 16:58:36 -06005618 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005619 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005620 break;
5621 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005622 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005623 break;
5624 case glslang::EOpTranspose:
5625 unaryOp = spv::OpTranspose;
5626 break;
5627
5628 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005629 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005630 break;
5631 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005632 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005633 break;
5634 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005635 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005636 break;
5637 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005638 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005639 break;
5640 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005641 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005642 break;
5643 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005644 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005645 break;
5646 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005647 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005648 break;
5649 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005650 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005651 break;
5652
5653 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005654 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005655 break;
5656 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005657 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005658 break;
5659 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005660 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005661 break;
5662 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005663 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005664 break;
5665 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005666 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005667 break;
5668 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005669 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005670 break;
5671
5672 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005673 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005674 break;
5675 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005676 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005677 break;
5678
5679 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005680 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005681 break;
5682 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005683 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005684 break;
5685 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005686 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005687 break;
5688 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005689 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005690 break;
5691 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005692 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005693 break;
5694 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005695 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005696 break;
5697
5698 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005699 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005700 break;
5701 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005702 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005703 break;
5704 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005705 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005706 break;
5707 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005708 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005709 break;
5710 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005711 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005712 break;
5713 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005714 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005715 break;
5716
5717 case glslang::EOpIsNan:
5718 unaryOp = spv::OpIsNan;
5719 break;
5720 case glslang::EOpIsInf:
5721 unaryOp = spv::OpIsInf;
5722 break;
LoopDawg592860c2016-06-09 08:57:35 -06005723 case glslang::EOpIsFinite:
5724 unaryOp = spv::OpIsFinite;
5725 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005726
Rex Xucbc426e2015-12-15 16:03:10 +08005727 case glslang::EOpFloatBitsToInt:
5728 case glslang::EOpFloatBitsToUint:
5729 case glslang::EOpIntBitsToFloat:
5730 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005731 case glslang::EOpDoubleBitsToInt64:
5732 case glslang::EOpDoubleBitsToUint64:
5733 case glslang::EOpInt64BitsToDouble:
5734 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005735 case glslang::EOpFloat16BitsToInt16:
5736 case glslang::EOpFloat16BitsToUint16:
5737 case glslang::EOpInt16BitsToFloat16:
5738 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005739 unaryOp = spv::OpBitcast;
5740 break;
5741
John Kessenich140f3df2015-06-26 16:58:36 -06005742 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005743 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005744 break;
5745 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005746 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005747 break;
5748 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005749 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005750 break;
5751 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005752 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005753 break;
5754 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005755 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005756 break;
5757 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005758 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005759 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005760#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005761 case glslang::EOpPackSnorm4x8:
5762 libCall = spv::GLSLstd450PackSnorm4x8;
5763 break;
5764 case glslang::EOpUnpackSnorm4x8:
5765 libCall = spv::GLSLstd450UnpackSnorm4x8;
5766 break;
5767 case glslang::EOpPackUnorm4x8:
5768 libCall = spv::GLSLstd450PackUnorm4x8;
5769 break;
5770 case glslang::EOpUnpackUnorm4x8:
5771 libCall = spv::GLSLstd450UnpackUnorm4x8;
5772 break;
5773 case glslang::EOpPackDouble2x32:
5774 libCall = spv::GLSLstd450PackDouble2x32;
5775 break;
5776 case glslang::EOpUnpackDouble2x32:
5777 libCall = spv::GLSLstd450UnpackDouble2x32;
5778 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005779#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005780
Rex Xu8ff43de2016-04-22 16:51:45 +08005781 case glslang::EOpPackInt2x32:
5782 case glslang::EOpUnpackInt2x32:
5783 case glslang::EOpPackUint2x32:
5784 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005785 case glslang::EOpPack16:
5786 case glslang::EOpPack32:
5787 case glslang::EOpPack64:
5788 case glslang::EOpUnpack32:
5789 case glslang::EOpUnpack16:
5790 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005791 case glslang::EOpPackInt2x16:
5792 case glslang::EOpUnpackInt2x16:
5793 case glslang::EOpPackUint2x16:
5794 case glslang::EOpUnpackUint2x16:
5795 case glslang::EOpPackInt4x16:
5796 case glslang::EOpUnpackInt4x16:
5797 case glslang::EOpPackUint4x16:
5798 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005799 case glslang::EOpPackFloat2x16:
5800 case glslang::EOpUnpackFloat2x16:
5801 unaryOp = spv::OpBitcast;
5802 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005803
John Kessenich140f3df2015-06-26 16:58:36 -06005804 case glslang::EOpDPdx:
5805 unaryOp = spv::OpDPdx;
5806 break;
5807 case glslang::EOpDPdy:
5808 unaryOp = spv::OpDPdy;
5809 break;
5810 case glslang::EOpFwidth:
5811 unaryOp = spv::OpFwidth;
5812 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005813
John Kessenich140f3df2015-06-26 16:58:36 -06005814 case glslang::EOpAny:
5815 unaryOp = spv::OpAny;
5816 break;
5817 case glslang::EOpAll:
5818 unaryOp = spv::OpAll;
5819 break;
5820
5821 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005822 if (isFloat)
5823 libCall = spv::GLSLstd450FAbs;
5824 else
5825 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005826 break;
5827 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005828 if (isFloat)
5829 libCall = spv::GLSLstd450FSign;
5830 else
5831 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005832 break;
5833
John Kessenicha28f7a72019-08-06 07:00:58 -06005834#ifndef GLSLANG_WEB
5835 case glslang::EOpDPdxFine:
5836 unaryOp = spv::OpDPdxFine;
5837 break;
5838 case glslang::EOpDPdyFine:
5839 unaryOp = spv::OpDPdyFine;
5840 break;
5841 case glslang::EOpFwidthFine:
5842 unaryOp = spv::OpFwidthFine;
5843 break;
5844 case glslang::EOpDPdxCoarse:
5845 unaryOp = spv::OpDPdxCoarse;
5846 break;
5847 case glslang::EOpDPdyCoarse:
5848 unaryOp = spv::OpDPdyCoarse;
5849 break;
5850 case glslang::EOpFwidthCoarse:
5851 unaryOp = spv::OpFwidthCoarse;
5852 break;
5853 case glslang::EOpInterpolateAtCentroid:
5854 if (typeProxy == glslang::EbtFloat16)
5855 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5856 libCall = spv::GLSLstd450InterpolateAtCentroid;
5857 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005858 case glslang::EOpAtomicCounterIncrement:
5859 case glslang::EOpAtomicCounterDecrement:
5860 case glslang::EOpAtomicCounter:
5861 {
5862 // Handle all of the atomics in one place, in createAtomicOperation()
5863 std::vector<spv::Id> operands;
5864 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005865 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005866 }
5867
John Kessenichfc51d282015-08-19 13:34:18 -06005868 case glslang::EOpBitFieldReverse:
5869 unaryOp = spv::OpBitReverse;
5870 break;
5871 case glslang::EOpBitCount:
5872 unaryOp = spv::OpBitCount;
5873 break;
5874 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005875 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005876 break;
5877 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005878 if (isUnsigned)
5879 libCall = spv::GLSLstd450FindUMsb;
5880 else
5881 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005882 break;
5883
Ian Romanickb3bd4022019-01-21 08:57:25 -08005884 case glslang::EOpCountLeadingZeros:
5885 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
5886 builder.addExtension("SPV_INTEL_shader_integer_functions2");
5887 unaryOp = spv::OpUCountLeadingZerosINTEL;
5888 break;
5889
5890 case glslang::EOpCountTrailingZeros:
5891 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
5892 builder.addExtension("SPV_INTEL_shader_integer_functions2");
5893 unaryOp = spv::OpUCountTrailingZerosINTEL;
5894 break;
5895
Rex Xu574ab042016-04-14 16:53:07 +08005896 case glslang::EOpBallot:
5897 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005898 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005899 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005900 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005901 case glslang::EOpMinInvocations:
5902 case glslang::EOpMaxInvocations:
5903 case glslang::EOpAddInvocations:
5904 case glslang::EOpMinInvocationsNonUniform:
5905 case glslang::EOpMaxInvocationsNonUniform:
5906 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005907 case glslang::EOpMinInvocationsInclusiveScan:
5908 case glslang::EOpMaxInvocationsInclusiveScan:
5909 case glslang::EOpAddInvocationsInclusiveScan:
5910 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5911 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5912 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5913 case glslang::EOpMinInvocationsExclusiveScan:
5914 case glslang::EOpMaxInvocationsExclusiveScan:
5915 case glslang::EOpAddInvocationsExclusiveScan:
5916 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5917 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5918 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08005919 {
5920 std::vector<spv::Id> operands;
5921 operands.push_back(operand);
5922 return createInvocationsOperation(op, typeId, operands, typeProxy);
5923 }
John Kessenich66011cb2018-03-06 16:12:04 -07005924 case glslang::EOpSubgroupAll:
5925 case glslang::EOpSubgroupAny:
5926 case glslang::EOpSubgroupAllEqual:
5927 case glslang::EOpSubgroupBroadcastFirst:
5928 case glslang::EOpSubgroupBallot:
5929 case glslang::EOpSubgroupInverseBallot:
5930 case glslang::EOpSubgroupBallotBitCount:
5931 case glslang::EOpSubgroupBallotInclusiveBitCount:
5932 case glslang::EOpSubgroupBallotExclusiveBitCount:
5933 case glslang::EOpSubgroupBallotFindLSB:
5934 case glslang::EOpSubgroupBallotFindMSB:
5935 case glslang::EOpSubgroupAdd:
5936 case glslang::EOpSubgroupMul:
5937 case glslang::EOpSubgroupMin:
5938 case glslang::EOpSubgroupMax:
5939 case glslang::EOpSubgroupAnd:
5940 case glslang::EOpSubgroupOr:
5941 case glslang::EOpSubgroupXor:
5942 case glslang::EOpSubgroupInclusiveAdd:
5943 case glslang::EOpSubgroupInclusiveMul:
5944 case glslang::EOpSubgroupInclusiveMin:
5945 case glslang::EOpSubgroupInclusiveMax:
5946 case glslang::EOpSubgroupInclusiveAnd:
5947 case glslang::EOpSubgroupInclusiveOr:
5948 case glslang::EOpSubgroupInclusiveXor:
5949 case glslang::EOpSubgroupExclusiveAdd:
5950 case glslang::EOpSubgroupExclusiveMul:
5951 case glslang::EOpSubgroupExclusiveMin:
5952 case glslang::EOpSubgroupExclusiveMax:
5953 case glslang::EOpSubgroupExclusiveAnd:
5954 case glslang::EOpSubgroupExclusiveOr:
5955 case glslang::EOpSubgroupExclusiveXor:
5956 case glslang::EOpSubgroupQuadSwapHorizontal:
5957 case glslang::EOpSubgroupQuadSwapVertical:
5958 case glslang::EOpSubgroupQuadSwapDiagonal: {
5959 std::vector<spv::Id> operands;
5960 operands.push_back(operand);
5961 return createSubgroupOperation(op, typeId, operands, typeProxy);
5962 }
Rex Xu9d93a232016-05-05 12:30:44 +08005963 case glslang::EOpMbcnt:
5964 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5965 libCall = spv::MbcntAMD;
5966 break;
5967
5968 case glslang::EOpCubeFaceIndex:
5969 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5970 libCall = spv::CubeFaceIndexAMD;
5971 break;
5972
5973 case glslang::EOpCubeFaceCoord:
5974 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5975 libCall = spv::CubeFaceCoordAMD;
5976 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005977 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005978 unaryOp = spv::OpGroupNonUniformPartitionNV;
5979 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005980 case glslang::EOpConstructReference:
5981 unaryOp = spv::OpBitcast;
5982 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005983#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05005984
5985 case glslang::EOpCopyObject:
5986 unaryOp = spv::OpCopyObject;
5987 break;
5988
John Kessenich140f3df2015-06-26 16:58:36 -06005989 default:
5990 return 0;
5991 }
5992
5993 spv::Id id;
5994 if (libCall >= 0) {
5995 std::vector<spv::Id> args;
5996 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005997 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005998 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005999 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006000 }
John Kessenich140f3df2015-06-26 16:58:36 -06006001
John Kessenichb9197c82019-08-11 07:41:45 -06006002 decorations.addNoContraction(builder, id);
6003 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006004 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006005}
6006
John Kessenich7a53f762016-01-20 11:19:27 -07006007// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006008spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6009 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006010{
6011 // Handle unary operations vector by vector.
6012 // The result type is the same type as the original type.
6013 // The algorithm is to:
6014 // - break the matrix into vectors
6015 // - apply the operation to each vector
6016 // - make a matrix out the vector results
6017
6018 // get the types sorted out
6019 int numCols = builder.getNumColumns(operand);
6020 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006021 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6022 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006023 std::vector<spv::Id> results;
6024
6025 // do each vector op
6026 for (int c = 0; c < numCols; ++c) {
6027 std::vector<unsigned int> indexes;
6028 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006029 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6030 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006031 decorations.addNoContraction(builder, destVec);
6032 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006033 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006034 }
6035
6036 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006037 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006038 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006039 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006040}
6041
John Kessenichad7645f2018-06-04 19:11:25 -06006042// For converting integers where both the bitwidth and the signedness could
6043// change, but only do the width change here. The caller is still responsible
6044// for the signedness conversion.
6045spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006046{
John Kessenichad7645f2018-06-04 19:11:25 -06006047 // Get the result type width, based on the type to convert to.
6048 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006049 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006050 case glslang::EOpConvInt16ToUint8:
6051 case glslang::EOpConvIntToUint8:
6052 case glslang::EOpConvInt64ToUint8:
6053 case glslang::EOpConvUint16ToInt8:
6054 case glslang::EOpConvUintToInt8:
6055 case glslang::EOpConvUint64ToInt8:
6056 width = 8;
6057 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006058 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006059 case glslang::EOpConvIntToUint16:
6060 case glslang::EOpConvInt64ToUint16:
6061 case glslang::EOpConvUint8ToInt16:
6062 case glslang::EOpConvUintToInt16:
6063 case glslang::EOpConvUint64ToInt16:
6064 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006065 break;
6066 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006067 case glslang::EOpConvInt16ToUint:
6068 case glslang::EOpConvInt64ToUint:
6069 case glslang::EOpConvUint8ToInt:
6070 case glslang::EOpConvUint16ToInt:
6071 case glslang::EOpConvUint64ToInt:
6072 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006073 break;
6074 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006075 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006076 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006077 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006078 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006079 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006080 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006081 break;
6082
6083 default:
6084 assert(false && "Default missing");
6085 break;
6086 }
6087
John Kessenichad7645f2018-06-04 19:11:25 -06006088 // Get the conversion operation and result type,
6089 // based on the target width, but the source type.
6090 spv::Id type = spv::NoType;
6091 spv::Op convOp = spv::OpNop;
6092 switch(op) {
6093 case glslang::EOpConvInt8ToUint16:
6094 case glslang::EOpConvInt8ToUint:
6095 case glslang::EOpConvInt8ToUint64:
6096 case glslang::EOpConvInt16ToUint8:
6097 case glslang::EOpConvInt16ToUint:
6098 case glslang::EOpConvInt16ToUint64:
6099 case glslang::EOpConvIntToUint8:
6100 case glslang::EOpConvIntToUint16:
6101 case glslang::EOpConvIntToUint64:
6102 case glslang::EOpConvInt64ToUint8:
6103 case glslang::EOpConvInt64ToUint16:
6104 case glslang::EOpConvInt64ToUint:
6105 convOp = spv::OpSConvert;
6106 type = builder.makeIntType(width);
6107 break;
6108 default:
6109 convOp = spv::OpUConvert;
6110 type = builder.makeUintType(width);
6111 break;
6112 }
6113
John Kessenich66011cb2018-03-06 16:12:04 -07006114 if (vectorSize > 0)
6115 type = builder.makeVectorType(type, vectorSize);
6116
John Kessenichad7645f2018-06-04 19:11:25 -06006117 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006118}
6119
John Kessenichead86222018-03-28 18:01:20 -06006120spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6121 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006122{
6123 spv::Op convOp = spv::OpNop;
6124 spv::Id zero = 0;
6125 spv::Id one = 0;
6126
6127 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6128
6129 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006130 case glslang::EOpConvIntToBool:
6131 case glslang::EOpConvUintToBool:
6132 zero = builder.makeUintConstant(0);
6133 zero = makeSmearedConstant(zero, vectorSize);
6134 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006135 case glslang::EOpConvFloatToBool:
6136 zero = builder.makeFloatConstant(0.0F);
6137 zero = makeSmearedConstant(zero, vectorSize);
6138 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006139 case glslang::EOpConvBoolToFloat:
6140 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006141 zero = builder.makeFloatConstant(0.0F);
6142 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006143 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006144
John Kessenich140f3df2015-06-26 16:58:36 -06006145 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006146 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006147#ifndef GLSLANG_WEB
6148 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006149 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006150 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006151 } else
6152#endif
6153 {
6154 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006155 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006156 }
Rex Xucabbb782017-03-24 13:41:14 +08006157
John Kessenich140f3df2015-06-26 16:58:36 -06006158 convOp = spv::OpSelect;
6159 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006160
John Kessenich140f3df2015-06-26 16:58:36 -06006161 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006162 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006163#ifndef GLSLANG_WEB
6164 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006165 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006166 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006167 } else
6168#endif
6169 {
6170 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006171 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006172 }
Rex Xucabbb782017-03-24 13:41:14 +08006173
John Kessenich140f3df2015-06-26 16:58:36 -06006174 convOp = spv::OpSelect;
6175 break;
6176
John Kessenich66011cb2018-03-06 16:12:04 -07006177 case glslang::EOpConvInt8ToFloat16:
6178 case glslang::EOpConvInt8ToFloat:
6179 case glslang::EOpConvInt8ToDouble:
6180 case glslang::EOpConvInt16ToFloat16:
6181 case glslang::EOpConvInt16ToFloat:
6182 case glslang::EOpConvInt16ToDouble:
6183 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006184 case glslang::EOpConvIntToFloat:
6185 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006186 case glslang::EOpConvInt64ToFloat:
6187 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006188 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006189 convOp = spv::OpConvertSToF;
6190 break;
6191
John Kessenich66011cb2018-03-06 16:12:04 -07006192 case glslang::EOpConvUint8ToFloat16:
6193 case glslang::EOpConvUint8ToFloat:
6194 case glslang::EOpConvUint8ToDouble:
6195 case glslang::EOpConvUint16ToFloat16:
6196 case glslang::EOpConvUint16ToFloat:
6197 case glslang::EOpConvUint16ToDouble:
6198 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006199 case glslang::EOpConvUintToFloat:
6200 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006201 case glslang::EOpConvUint64ToFloat:
6202 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006203 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006204 convOp = spv::OpConvertUToF;
6205 break;
6206
John Kessenich66011cb2018-03-06 16:12:04 -07006207 case glslang::EOpConvFloat16ToInt8:
6208 case glslang::EOpConvFloatToInt8:
6209 case glslang::EOpConvDoubleToInt8:
6210 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006211 case glslang::EOpConvFloatToInt16:
6212 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006213 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006214 case glslang::EOpConvFloatToInt:
6215 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006216 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006217 case glslang::EOpConvFloatToInt64:
6218 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006219 convOp = spv::OpConvertFToS;
6220 break;
6221
John Kessenich66011cb2018-03-06 16:12:04 -07006222 case glslang::EOpConvUint8ToInt8:
6223 case glslang::EOpConvInt8ToUint8:
6224 case glslang::EOpConvUint16ToInt16:
6225 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006226 case glslang::EOpConvUintToInt:
6227 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006228 case glslang::EOpConvUint64ToInt64:
6229 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006230 if (builder.isInSpecConstCodeGenMode()) {
6231 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006232#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006233 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6234 zero = builder.makeUint8Constant(0);
6235 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006236 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006237 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6238 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006239 } else
6240#endif
6241 {
Rex Xucabbb782017-03-24 13:41:14 +08006242 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006243 }
qining189b2032016-04-12 23:16:20 -04006244 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006245 // Use OpIAdd, instead of OpBitcast to do the conversion when
6246 // generating for OpSpecConstantOp instruction.
6247 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6248 }
6249 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006250 convOp = spv::OpBitcast;
6251 break;
6252
John Kessenich66011cb2018-03-06 16:12:04 -07006253 case glslang::EOpConvFloat16ToUint8:
6254 case glslang::EOpConvFloatToUint8:
6255 case glslang::EOpConvDoubleToUint8:
6256 case glslang::EOpConvFloat16ToUint16:
6257 case glslang::EOpConvFloatToUint16:
6258 case glslang::EOpConvDoubleToUint16:
6259 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006260 case glslang::EOpConvFloatToUint:
6261 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006262 case glslang::EOpConvFloatToUint64:
6263 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006264 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006265 convOp = spv::OpConvertFToU;
6266 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006267
John Kessenich39697cd2019-08-08 10:35:51 -06006268#ifndef GLSLANG_WEB
6269 case glslang::EOpConvInt8ToBool:
6270 case glslang::EOpConvUint8ToBool:
6271 zero = builder.makeUint8Constant(0);
6272 zero = makeSmearedConstant(zero, vectorSize);
6273 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6274 case glslang::EOpConvInt16ToBool:
6275 case glslang::EOpConvUint16ToBool:
6276 zero = builder.makeUint16Constant(0);
6277 zero = makeSmearedConstant(zero, vectorSize);
6278 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6279 case glslang::EOpConvInt64ToBool:
6280 case glslang::EOpConvUint64ToBool:
6281 zero = builder.makeUint64Constant(0);
6282 zero = makeSmearedConstant(zero, vectorSize);
6283 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6284 case glslang::EOpConvDoubleToBool:
6285 zero = builder.makeDoubleConstant(0.0);
6286 zero = makeSmearedConstant(zero, vectorSize);
6287 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6288 case glslang::EOpConvFloat16ToBool:
6289 zero = builder.makeFloat16Constant(0.0F);
6290 zero = makeSmearedConstant(zero, vectorSize);
6291 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6292 case glslang::EOpConvBoolToDouble:
6293 convOp = spv::OpSelect;
6294 zero = builder.makeDoubleConstant(0.0);
6295 one = builder.makeDoubleConstant(1.0);
6296 break;
6297 case glslang::EOpConvBoolToFloat16:
6298 convOp = spv::OpSelect;
6299 zero = builder.makeFloat16Constant(0.0F);
6300 one = builder.makeFloat16Constant(1.0F);
6301 break;
6302 case glslang::EOpConvBoolToInt8:
6303 zero = builder.makeInt8Constant(0);
6304 one = builder.makeInt8Constant(1);
6305 convOp = spv::OpSelect;
6306 break;
6307 case glslang::EOpConvBoolToUint8:
6308 zero = builder.makeUint8Constant(0);
6309 one = builder.makeUint8Constant(1);
6310 convOp = spv::OpSelect;
6311 break;
6312 case glslang::EOpConvBoolToInt16:
6313 zero = builder.makeInt16Constant(0);
6314 one = builder.makeInt16Constant(1);
6315 convOp = spv::OpSelect;
6316 break;
6317 case glslang::EOpConvBoolToUint16:
6318 zero = builder.makeUint16Constant(0);
6319 one = builder.makeUint16Constant(1);
6320 convOp = spv::OpSelect;
6321 break;
6322 case glslang::EOpConvDoubleToFloat:
6323 case glslang::EOpConvFloatToDouble:
6324 case glslang::EOpConvDoubleToFloat16:
6325 case glslang::EOpConvFloat16ToDouble:
6326 case glslang::EOpConvFloatToFloat16:
6327 case glslang::EOpConvFloat16ToFloat:
6328 convOp = spv::OpFConvert;
6329 if (builder.isMatrixType(destType))
6330 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6331 break;
6332
John Kessenich66011cb2018-03-06 16:12:04 -07006333 case glslang::EOpConvInt8ToInt16:
6334 case glslang::EOpConvInt8ToInt:
6335 case glslang::EOpConvInt8ToInt64:
6336 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006337 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006338 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006339 case glslang::EOpConvIntToInt8:
6340 case glslang::EOpConvIntToInt16:
6341 case glslang::EOpConvIntToInt64:
6342 case glslang::EOpConvInt64ToInt8:
6343 case glslang::EOpConvInt64ToInt16:
6344 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006345 convOp = spv::OpSConvert;
6346 break;
6347
John Kessenich66011cb2018-03-06 16:12:04 -07006348 case glslang::EOpConvUint8ToUint16:
6349 case glslang::EOpConvUint8ToUint:
6350 case glslang::EOpConvUint8ToUint64:
6351 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006352 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006353 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006354 case glslang::EOpConvUintToUint8:
6355 case glslang::EOpConvUintToUint16:
6356 case glslang::EOpConvUintToUint64:
6357 case glslang::EOpConvUint64ToUint8:
6358 case glslang::EOpConvUint64ToUint16:
6359 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006360 convOp = spv::OpUConvert;
6361 break;
6362
John Kessenich66011cb2018-03-06 16:12:04 -07006363 case glslang::EOpConvInt8ToUint16:
6364 case glslang::EOpConvInt8ToUint:
6365 case glslang::EOpConvInt8ToUint64:
6366 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006367 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006368 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006369 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006370 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006371 case glslang::EOpConvIntToUint64:
6372 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006373 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006374 case glslang::EOpConvInt64ToUint:
6375 case glslang::EOpConvUint8ToInt16:
6376 case glslang::EOpConvUint8ToInt:
6377 case glslang::EOpConvUint8ToInt64:
6378 case glslang::EOpConvUint16ToInt8:
6379 case glslang::EOpConvUint16ToInt:
6380 case glslang::EOpConvUint16ToInt64:
6381 case glslang::EOpConvUintToInt8:
6382 case glslang::EOpConvUintToInt16:
6383 case glslang::EOpConvUintToInt64:
6384 case glslang::EOpConvUint64ToInt8:
6385 case glslang::EOpConvUint64ToInt16:
6386 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006387 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006388 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006389
6390 if (builder.isInSpecConstCodeGenMode()) {
6391 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006392 switch(op) {
6393 case glslang::EOpConvInt16ToUint8:
6394 case glslang::EOpConvIntToUint8:
6395 case glslang::EOpConvInt64ToUint8:
6396 case glslang::EOpConvUint16ToInt8:
6397 case glslang::EOpConvUintToInt8:
6398 case glslang::EOpConvUint64ToInt8:
6399 zero = builder.makeUint8Constant(0);
6400 break;
6401 case glslang::EOpConvInt8ToUint16:
6402 case glslang::EOpConvIntToUint16:
6403 case glslang::EOpConvInt64ToUint16:
6404 case glslang::EOpConvUint8ToInt16:
6405 case glslang::EOpConvUintToInt16:
6406 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006407 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006408 break;
6409 case glslang::EOpConvInt8ToUint:
6410 case glslang::EOpConvInt16ToUint:
6411 case glslang::EOpConvInt64ToUint:
6412 case glslang::EOpConvUint8ToInt:
6413 case glslang::EOpConvUint16ToInt:
6414 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006415 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006416 break;
6417 case glslang::EOpConvInt8ToUint64:
6418 case glslang::EOpConvInt16ToUint64:
6419 case glslang::EOpConvIntToUint64:
6420 case glslang::EOpConvUint8ToInt64:
6421 case glslang::EOpConvUint16ToInt64:
6422 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006423 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006424 break;
6425 default:
6426 assert(false && "Default missing");
6427 break;
6428 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006429 zero = makeSmearedConstant(zero, vectorSize);
6430 // Use OpIAdd, instead of OpBitcast to do the conversion when
6431 // generating for OpSpecConstantOp instruction.
6432 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6433 }
6434 // For normal run-time conversion instruction, use OpBitcast.
6435 convOp = spv::OpBitcast;
6436 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006437 case glslang::EOpConvUint64ToPtr:
6438 convOp = spv::OpConvertUToPtr;
6439 break;
6440 case glslang::EOpConvPtrToUint64:
6441 convOp = spv::OpConvertPtrToU;
6442 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006443 case glslang::EOpConvPtrToUvec2:
6444 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006445 if (builder.isVector(operand))
6446 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6447 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006448 convOp = spv::OpBitcast;
6449 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006450#endif
6451
John Kessenich140f3df2015-06-26 16:58:36 -06006452 default:
6453 break;
6454 }
6455
6456 spv::Id result = 0;
6457 if (convOp == spv::OpNop)
6458 return result;
6459
6460 if (convOp == spv::OpSelect) {
6461 zero = makeSmearedConstant(zero, vectorSize);
6462 one = makeSmearedConstant(one, vectorSize);
6463 result = builder.createTriOp(convOp, destType, operand, one, zero);
6464 } else
6465 result = builder.createUnaryOp(convOp, destType, operand);
6466
John Kessenichead86222018-03-28 18:01:20 -06006467 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006468 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006469 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006470}
6471
6472spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6473{
6474 if (vectorSize == 0)
6475 return constant;
6476
6477 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6478 std::vector<spv::Id> components;
6479 for (int c = 0; c < vectorSize; ++c)
6480 components.push_back(constant);
6481 return builder.makeCompositeConstant(vectorTypeId, components);
6482}
6483
John Kessenich426394d2015-07-23 10:22:48 -06006484// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006485spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6486 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6487 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006488{
6489 spv::Op opCode = spv::OpNop;
6490
6491 switch (op) {
6492 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006493 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006494 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006495 opCode = spv::OpAtomicIAdd;
6496 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006497 case glslang::EOpAtomicCounterSubtract:
6498 opCode = spv::OpAtomicISub;
6499 break;
John Kessenich426394d2015-07-23 10:22:48 -06006500 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006501 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006502 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006503 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6504 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006505 break;
6506 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006507 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006508 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006509 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6510 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006511 break;
6512 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006513 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006514 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006515 opCode = spv::OpAtomicAnd;
6516 break;
6517 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006518 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006519 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006520 opCode = spv::OpAtomicOr;
6521 break;
6522 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006523 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006524 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006525 opCode = spv::OpAtomicXor;
6526 break;
6527 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006528 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006529 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006530 opCode = spv::OpAtomicExchange;
6531 break;
6532 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006533 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006534 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006535 opCode = spv::OpAtomicCompareExchange;
6536 break;
6537 case glslang::EOpAtomicCounterIncrement:
6538 opCode = spv::OpAtomicIIncrement;
6539 break;
6540 case glslang::EOpAtomicCounterDecrement:
6541 opCode = spv::OpAtomicIDecrement;
6542 break;
6543 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006544 case glslang::EOpImageAtomicLoad:
6545 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006546 opCode = spv::OpAtomicLoad;
6547 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006548 case glslang::EOpAtomicStore:
6549 case glslang::EOpImageAtomicStore:
6550 opCode = spv::OpAtomicStore;
6551 break;
John Kessenich426394d2015-07-23 10:22:48 -06006552 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006553 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006554 break;
6555 }
6556
Rex Xue8fe8b02017-09-26 15:42:56 +08006557 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6558 builder.addCapability(spv::CapabilityInt64Atomics);
6559
John Kessenich426394d2015-07-23 10:22:48 -06006560 // Sort out the operands
6561 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006562 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006563 // - compare-exchange swaps the value and comparator
6564 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006565 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006566 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6567 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6568 spv::Id scopeId;
6569 if (glslangIntermediate->usingVulkanMemoryModel()) {
6570 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6571 } else {
6572 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6573 }
6574 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006575 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6576 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006577 spv::MemorySemanticsVolatileMask :
6578 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006579 spv::Id semanticsId2 = semanticsId;
6580
6581 pointerId = operands[0];
6582 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6583 // no additional operands
6584 } else if (opCode == spv::OpAtomicCompareExchange) {
6585 compareId = operands[1];
6586 valueId = operands[2];
6587 if (operands.size() > 3) {
6588 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006589 semanticsId = builder.makeUintConstant(
6590 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6591 semanticsId2 = builder.makeUintConstant(
6592 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006593 }
6594 } else if (opCode == spv::OpAtomicLoad) {
6595 if (operands.size() > 1) {
6596 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006597 semanticsId = builder.makeUintConstant(
6598 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006599 }
6600 } else {
6601 // atomic store or RMW
6602 valueId = operands[1];
6603 if (operands.size() > 2) {
6604 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006605 semanticsId = builder.makeUintConstant
6606 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006607 }
Rex Xu04db3f52015-09-16 11:44:02 +08006608 }
John Kessenich426394d2015-07-23 10:22:48 -06006609
Jeff Bolz36831c92018-09-05 10:11:41 -05006610 // Check for capabilities
6611 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006612 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6613 spv::MemorySemanticsMakeVisibleKHRMask |
6614 spv::MemorySemanticsOutputMemoryKHRMask |
6615 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006616 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6617 }
John Kessenich426394d2015-07-23 10:22:48 -06006618
Jeff Bolz36831c92018-09-05 10:11:41 -05006619 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6620 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6621 }
John Kessenich48d6e792017-10-06 21:21:48 -06006622
Jeff Bolz36831c92018-09-05 10:11:41 -05006623 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6624 spvAtomicOperands.push_back(pointerId);
6625 spvAtomicOperands.push_back(scopeId);
6626 spvAtomicOperands.push_back(semanticsId);
6627 if (opCode == spv::OpAtomicCompareExchange) {
6628 spvAtomicOperands.push_back(semanticsId2);
6629 spvAtomicOperands.push_back(valueId);
6630 spvAtomicOperands.push_back(compareId);
6631 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6632 spvAtomicOperands.push_back(valueId);
6633 }
John Kessenich48d6e792017-10-06 21:21:48 -06006634
Jeff Bolz36831c92018-09-05 10:11:41 -05006635 if (opCode == spv::OpAtomicStore) {
6636 builder.createNoResultOp(opCode, spvAtomicOperands);
6637 return 0;
6638 } else {
6639 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6640
6641 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6642 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6643 if (op == glslang::EOpAtomicCounterDecrement)
6644 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6645
6646 return resultId;
6647 }
John Kessenich426394d2015-07-23 10:22:48 -06006648}
6649
John Kessenich91cef522016-05-05 16:45:40 -06006650// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07006651spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
6652 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006653{
John Kessenich66011cb2018-03-06 16:12:04 -07006654 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6655 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006656
Rex Xu51596642016-09-21 18:56:12 +08006657 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006658 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006659 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6660
chaocf200da82016-12-20 12:44:35 -08006661 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6662 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006663 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6664 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006665 } else if (op == glslang::EOpAnyInvocation ||
6666 op == glslang::EOpAllInvocations ||
6667 op == glslang::EOpAllInvocationsEqual) {
6668 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6669 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006670 } else {
6671 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006672 if (op == glslang::EOpMinInvocationsNonUniform ||
6673 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006674 op == glslang::EOpAddInvocationsNonUniform ||
6675 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6676 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6677 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6678 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6679 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6680 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006681 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006682
Rex Xu430ef402016-10-14 17:22:23 +08006683 switch (op) {
6684 case glslang::EOpMinInvocations:
6685 case glslang::EOpMaxInvocations:
6686 case glslang::EOpAddInvocations:
6687 case glslang::EOpMinInvocationsNonUniform:
6688 case glslang::EOpMaxInvocationsNonUniform:
6689 case glslang::EOpAddInvocationsNonUniform:
6690 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006691 break;
6692 case glslang::EOpMinInvocationsInclusiveScan:
6693 case glslang::EOpMaxInvocationsInclusiveScan:
6694 case glslang::EOpAddInvocationsInclusiveScan:
6695 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6696 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6697 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6698 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006699 break;
6700 case glslang::EOpMinInvocationsExclusiveScan:
6701 case glslang::EOpMaxInvocationsExclusiveScan:
6702 case glslang::EOpAddInvocationsExclusiveScan:
6703 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6704 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6705 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6706 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006707 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006708 default:
6709 break;
Rex Xu430ef402016-10-14 17:22:23 +08006710 }
John Kessenich149afc32018-08-14 13:31:43 -06006711 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6712 spvGroupOperands.push_back(scope);
6713 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006714 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006715 spvGroupOperands.push_back(groupOp);
6716 }
Rex Xu51596642016-09-21 18:56:12 +08006717 }
6718
John Kessenich149afc32018-08-14 13:31:43 -06006719 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6720 spv::IdImmediate op = { true, *opIt };
6721 spvGroupOperands.push_back(op);
6722 }
John Kessenich91cef522016-05-05 16:45:40 -06006723
6724 switch (op) {
6725 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006726 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006727 break;
John Kessenich91cef522016-05-05 16:45:40 -06006728 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006729 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006730 break;
John Kessenich91cef522016-05-05 16:45:40 -06006731 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006732 opCode = spv::OpSubgroupAllEqualKHR;
6733 break;
Rex Xu51596642016-09-21 18:56:12 +08006734 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006735 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006736 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006737 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006738 break;
6739 case glslang::EOpReadFirstInvocation:
6740 opCode = spv::OpSubgroupFirstInvocationKHR;
6741 break;
6742 case glslang::EOpBallot:
6743 {
6744 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6745 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6746 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6747 //
6748 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6749 //
6750 spv::Id uintType = builder.makeUintType(32);
6751 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6752 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6753
6754 std::vector<spv::Id> components;
6755 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6756 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6757
6758 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6759 return builder.createUnaryOp(spv::OpBitcast, typeId,
6760 builder.createCompositeConstruct(uvec2Type, components));
6761 }
6762
Rex Xu9d93a232016-05-05 12:30:44 +08006763 case glslang::EOpMinInvocations:
6764 case glslang::EOpMaxInvocations:
6765 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006766 case glslang::EOpMinInvocationsInclusiveScan:
6767 case glslang::EOpMaxInvocationsInclusiveScan:
6768 case glslang::EOpAddInvocationsInclusiveScan:
6769 case glslang::EOpMinInvocationsExclusiveScan:
6770 case glslang::EOpMaxInvocationsExclusiveScan:
6771 case glslang::EOpAddInvocationsExclusiveScan:
6772 if (op == glslang::EOpMinInvocations ||
6773 op == glslang::EOpMinInvocationsInclusiveScan ||
6774 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006775 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006776 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006777 else {
6778 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006779 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006780 else
Rex Xu51596642016-09-21 18:56:12 +08006781 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006782 }
Rex Xu430ef402016-10-14 17:22:23 +08006783 } else if (op == glslang::EOpMaxInvocations ||
6784 op == glslang::EOpMaxInvocationsInclusiveScan ||
6785 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006786 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006787 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006788 else {
6789 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006790 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006791 else
Rex Xu51596642016-09-21 18:56:12 +08006792 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006793 }
6794 } else {
6795 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006796 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006797 else
Rex Xu51596642016-09-21 18:56:12 +08006798 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006799 }
6800
Rex Xu2bbbe062016-08-23 15:41:05 +08006801 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006802 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006803
6804 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006805 case glslang::EOpMinInvocationsNonUniform:
6806 case glslang::EOpMaxInvocationsNonUniform:
6807 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006808 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6809 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6810 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6811 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6812 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6813 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6814 if (op == glslang::EOpMinInvocationsNonUniform ||
6815 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6816 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006817 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006818 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006819 else {
6820 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006821 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006822 else
Rex Xu51596642016-09-21 18:56:12 +08006823 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006824 }
6825 }
Rex Xu430ef402016-10-14 17:22:23 +08006826 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6827 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6828 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006829 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006830 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006831 else {
6832 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006833 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006834 else
Rex Xu51596642016-09-21 18:56:12 +08006835 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006836 }
6837 }
6838 else {
6839 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006840 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006841 else
Rex Xu51596642016-09-21 18:56:12 +08006842 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006843 }
6844
Rex Xu2bbbe062016-08-23 15:41:05 +08006845 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006846 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006847
6848 break;
John Kessenich91cef522016-05-05 16:45:40 -06006849 default:
6850 logger->missingFunctionality("invocation operation");
6851 return spv::NoResult;
6852 }
Rex Xu51596642016-09-21 18:56:12 +08006853
6854 assert(opCode != spv::OpNop);
6855 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006856}
6857
Rex Xu2bbbe062016-08-23 15:41:05 +08006858// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006859spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6860 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006861{
6862 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6863 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006864 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006865 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07006866 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
6867 op == spv::OpGroupSMinNonUniformAMD ||
6868 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
6869 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006870 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
6871
6872 // Handle group invocation operations scalar by scalar.
6873 // The result type is the same type as the original type.
6874 // The algorithm is to:
6875 // - break the vector into scalars
6876 // - apply the operation to each scalar
6877 // - make a vector out the scalar results
6878
6879 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006880 int numComponents = builder.getNumComponents(operands[0]);
6881 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006882 std::vector<spv::Id> results;
6883
6884 // do each scalar op
6885 for (int comp = 0; comp < numComponents; ++comp) {
6886 std::vector<unsigned int> indexes;
6887 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006888 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6889 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006890 if (op == spv::OpSubgroupReadInvocationKHR) {
6891 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006892 spv::IdImmediate operand = { true, operands[1] };
6893 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006894 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006895 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6896 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006897 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006898 spv::IdImmediate operand = { true, operands[1] };
6899 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006900 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006901 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6902 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006903 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006904 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006905 spvGroupOperands.push_back(scalar);
6906 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006907
Rex Xub7072052016-09-26 15:53:40 +08006908 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006909 }
6910
6911 // put the pieces together
6912 return builder.createCompositeConstruct(typeId, results);
6913}
Rex Xu2bbbe062016-08-23 15:41:05 +08006914
John Kessenich66011cb2018-03-06 16:12:04 -07006915// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006916spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6917 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006918{
6919 // Add the required capabilities.
6920 switch (op) {
6921 case glslang::EOpSubgroupElect:
6922 builder.addCapability(spv::CapabilityGroupNonUniform);
6923 break;
6924 case glslang::EOpSubgroupAll:
6925 case glslang::EOpSubgroupAny:
6926 case glslang::EOpSubgroupAllEqual:
6927 builder.addCapability(spv::CapabilityGroupNonUniform);
6928 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6929 break;
6930 case glslang::EOpSubgroupBroadcast:
6931 case glslang::EOpSubgroupBroadcastFirst:
6932 case glslang::EOpSubgroupBallot:
6933 case glslang::EOpSubgroupInverseBallot:
6934 case glslang::EOpSubgroupBallotBitExtract:
6935 case glslang::EOpSubgroupBallotBitCount:
6936 case glslang::EOpSubgroupBallotInclusiveBitCount:
6937 case glslang::EOpSubgroupBallotExclusiveBitCount:
6938 case glslang::EOpSubgroupBallotFindLSB:
6939 case glslang::EOpSubgroupBallotFindMSB:
6940 builder.addCapability(spv::CapabilityGroupNonUniform);
6941 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6942 break;
6943 case glslang::EOpSubgroupShuffle:
6944 case glslang::EOpSubgroupShuffleXor:
6945 builder.addCapability(spv::CapabilityGroupNonUniform);
6946 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6947 break;
6948 case glslang::EOpSubgroupShuffleUp:
6949 case glslang::EOpSubgroupShuffleDown:
6950 builder.addCapability(spv::CapabilityGroupNonUniform);
6951 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6952 break;
6953 case glslang::EOpSubgroupAdd:
6954 case glslang::EOpSubgroupMul:
6955 case glslang::EOpSubgroupMin:
6956 case glslang::EOpSubgroupMax:
6957 case glslang::EOpSubgroupAnd:
6958 case glslang::EOpSubgroupOr:
6959 case glslang::EOpSubgroupXor:
6960 case glslang::EOpSubgroupInclusiveAdd:
6961 case glslang::EOpSubgroupInclusiveMul:
6962 case glslang::EOpSubgroupInclusiveMin:
6963 case glslang::EOpSubgroupInclusiveMax:
6964 case glslang::EOpSubgroupInclusiveAnd:
6965 case glslang::EOpSubgroupInclusiveOr:
6966 case glslang::EOpSubgroupInclusiveXor:
6967 case glslang::EOpSubgroupExclusiveAdd:
6968 case glslang::EOpSubgroupExclusiveMul:
6969 case glslang::EOpSubgroupExclusiveMin:
6970 case glslang::EOpSubgroupExclusiveMax:
6971 case glslang::EOpSubgroupExclusiveAnd:
6972 case glslang::EOpSubgroupExclusiveOr:
6973 case glslang::EOpSubgroupExclusiveXor:
6974 builder.addCapability(spv::CapabilityGroupNonUniform);
6975 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6976 break;
6977 case glslang::EOpSubgroupClusteredAdd:
6978 case glslang::EOpSubgroupClusteredMul:
6979 case glslang::EOpSubgroupClusteredMin:
6980 case glslang::EOpSubgroupClusteredMax:
6981 case glslang::EOpSubgroupClusteredAnd:
6982 case glslang::EOpSubgroupClusteredOr:
6983 case glslang::EOpSubgroupClusteredXor:
6984 builder.addCapability(spv::CapabilityGroupNonUniform);
6985 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6986 break;
6987 case glslang::EOpSubgroupQuadBroadcast:
6988 case glslang::EOpSubgroupQuadSwapHorizontal:
6989 case glslang::EOpSubgroupQuadSwapVertical:
6990 case glslang::EOpSubgroupQuadSwapDiagonal:
6991 builder.addCapability(spv::CapabilityGroupNonUniform);
6992 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6993 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006994 case glslang::EOpSubgroupPartitionedAdd:
6995 case glslang::EOpSubgroupPartitionedMul:
6996 case glslang::EOpSubgroupPartitionedMin:
6997 case glslang::EOpSubgroupPartitionedMax:
6998 case glslang::EOpSubgroupPartitionedAnd:
6999 case glslang::EOpSubgroupPartitionedOr:
7000 case glslang::EOpSubgroupPartitionedXor:
7001 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7002 case glslang::EOpSubgroupPartitionedInclusiveMul:
7003 case glslang::EOpSubgroupPartitionedInclusiveMin:
7004 case glslang::EOpSubgroupPartitionedInclusiveMax:
7005 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7006 case glslang::EOpSubgroupPartitionedInclusiveOr:
7007 case glslang::EOpSubgroupPartitionedInclusiveXor:
7008 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7009 case glslang::EOpSubgroupPartitionedExclusiveMul:
7010 case glslang::EOpSubgroupPartitionedExclusiveMin:
7011 case glslang::EOpSubgroupPartitionedExclusiveMax:
7012 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7013 case glslang::EOpSubgroupPartitionedExclusiveOr:
7014 case glslang::EOpSubgroupPartitionedExclusiveXor:
7015 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7016 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7017 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007018 default: assert(0 && "Unhandled subgroup operation!");
7019 }
7020
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007021
7022 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7023 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007024 const bool isBool = typeProxy == glslang::EbtBool;
7025
7026 spv::Op opCode = spv::OpNop;
7027
7028 // Figure out which opcode to use.
7029 switch (op) {
7030 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7031 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7032 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7033 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7034 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7035 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7036 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7037 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7038 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7039 case glslang::EOpSubgroupBallotBitCount:
7040 case glslang::EOpSubgroupBallotInclusiveBitCount:
7041 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7042 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7043 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7044 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7045 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7046 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7047 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7048 case glslang::EOpSubgroupAdd:
7049 case glslang::EOpSubgroupInclusiveAdd:
7050 case glslang::EOpSubgroupExclusiveAdd:
7051 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007052 case glslang::EOpSubgroupPartitionedAdd:
7053 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7054 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007055 if (isFloat) {
7056 opCode = spv::OpGroupNonUniformFAdd;
7057 } else {
7058 opCode = spv::OpGroupNonUniformIAdd;
7059 }
7060 break;
7061 case glslang::EOpSubgroupMul:
7062 case glslang::EOpSubgroupInclusiveMul:
7063 case glslang::EOpSubgroupExclusiveMul:
7064 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007065 case glslang::EOpSubgroupPartitionedMul:
7066 case glslang::EOpSubgroupPartitionedInclusiveMul:
7067 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007068 if (isFloat) {
7069 opCode = spv::OpGroupNonUniformFMul;
7070 } else {
7071 opCode = spv::OpGroupNonUniformIMul;
7072 }
7073 break;
7074 case glslang::EOpSubgroupMin:
7075 case glslang::EOpSubgroupInclusiveMin:
7076 case glslang::EOpSubgroupExclusiveMin:
7077 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007078 case glslang::EOpSubgroupPartitionedMin:
7079 case glslang::EOpSubgroupPartitionedInclusiveMin:
7080 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007081 if (isFloat) {
7082 opCode = spv::OpGroupNonUniformFMin;
7083 } else if (isUnsigned) {
7084 opCode = spv::OpGroupNonUniformUMin;
7085 } else {
7086 opCode = spv::OpGroupNonUniformSMin;
7087 }
7088 break;
7089 case glslang::EOpSubgroupMax:
7090 case glslang::EOpSubgroupInclusiveMax:
7091 case glslang::EOpSubgroupExclusiveMax:
7092 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007093 case glslang::EOpSubgroupPartitionedMax:
7094 case glslang::EOpSubgroupPartitionedInclusiveMax:
7095 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007096 if (isFloat) {
7097 opCode = spv::OpGroupNonUniformFMax;
7098 } else if (isUnsigned) {
7099 opCode = spv::OpGroupNonUniformUMax;
7100 } else {
7101 opCode = spv::OpGroupNonUniformSMax;
7102 }
7103 break;
7104 case glslang::EOpSubgroupAnd:
7105 case glslang::EOpSubgroupInclusiveAnd:
7106 case glslang::EOpSubgroupExclusiveAnd:
7107 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007108 case glslang::EOpSubgroupPartitionedAnd:
7109 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7110 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007111 if (isBool) {
7112 opCode = spv::OpGroupNonUniformLogicalAnd;
7113 } else {
7114 opCode = spv::OpGroupNonUniformBitwiseAnd;
7115 }
7116 break;
7117 case glslang::EOpSubgroupOr:
7118 case glslang::EOpSubgroupInclusiveOr:
7119 case glslang::EOpSubgroupExclusiveOr:
7120 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007121 case glslang::EOpSubgroupPartitionedOr:
7122 case glslang::EOpSubgroupPartitionedInclusiveOr:
7123 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007124 if (isBool) {
7125 opCode = spv::OpGroupNonUniformLogicalOr;
7126 } else {
7127 opCode = spv::OpGroupNonUniformBitwiseOr;
7128 }
7129 break;
7130 case glslang::EOpSubgroupXor:
7131 case glslang::EOpSubgroupInclusiveXor:
7132 case glslang::EOpSubgroupExclusiveXor:
7133 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007134 case glslang::EOpSubgroupPartitionedXor:
7135 case glslang::EOpSubgroupPartitionedInclusiveXor:
7136 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007137 if (isBool) {
7138 opCode = spv::OpGroupNonUniformLogicalXor;
7139 } else {
7140 opCode = spv::OpGroupNonUniformBitwiseXor;
7141 }
7142 break;
7143 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7144 case glslang::EOpSubgroupQuadSwapHorizontal:
7145 case glslang::EOpSubgroupQuadSwapVertical:
7146 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7147 default: assert(0 && "Unhandled subgroup operation!");
7148 }
7149
John Kessenich149afc32018-08-14 13:31:43 -06007150 // get the right Group Operation
7151 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007152 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007153 default:
7154 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007155 case glslang::EOpSubgroupBallotBitCount:
7156 case glslang::EOpSubgroupAdd:
7157 case glslang::EOpSubgroupMul:
7158 case glslang::EOpSubgroupMin:
7159 case glslang::EOpSubgroupMax:
7160 case glslang::EOpSubgroupAnd:
7161 case glslang::EOpSubgroupOr:
7162 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007163 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007164 break;
7165 case glslang::EOpSubgroupBallotInclusiveBitCount:
7166 case glslang::EOpSubgroupInclusiveAdd:
7167 case glslang::EOpSubgroupInclusiveMul:
7168 case glslang::EOpSubgroupInclusiveMin:
7169 case glslang::EOpSubgroupInclusiveMax:
7170 case glslang::EOpSubgroupInclusiveAnd:
7171 case glslang::EOpSubgroupInclusiveOr:
7172 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007173 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007174 break;
7175 case glslang::EOpSubgroupBallotExclusiveBitCount:
7176 case glslang::EOpSubgroupExclusiveAdd:
7177 case glslang::EOpSubgroupExclusiveMul:
7178 case glslang::EOpSubgroupExclusiveMin:
7179 case glslang::EOpSubgroupExclusiveMax:
7180 case glslang::EOpSubgroupExclusiveAnd:
7181 case glslang::EOpSubgroupExclusiveOr:
7182 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007183 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007184 break;
7185 case glslang::EOpSubgroupClusteredAdd:
7186 case glslang::EOpSubgroupClusteredMul:
7187 case glslang::EOpSubgroupClusteredMin:
7188 case glslang::EOpSubgroupClusteredMax:
7189 case glslang::EOpSubgroupClusteredAnd:
7190 case glslang::EOpSubgroupClusteredOr:
7191 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007192 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007193 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007194 case glslang::EOpSubgroupPartitionedAdd:
7195 case glslang::EOpSubgroupPartitionedMul:
7196 case glslang::EOpSubgroupPartitionedMin:
7197 case glslang::EOpSubgroupPartitionedMax:
7198 case glslang::EOpSubgroupPartitionedAnd:
7199 case glslang::EOpSubgroupPartitionedOr:
7200 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007201 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007202 break;
7203 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7204 case glslang::EOpSubgroupPartitionedInclusiveMul:
7205 case glslang::EOpSubgroupPartitionedInclusiveMin:
7206 case glslang::EOpSubgroupPartitionedInclusiveMax:
7207 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7208 case glslang::EOpSubgroupPartitionedInclusiveOr:
7209 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007210 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007211 break;
7212 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7213 case glslang::EOpSubgroupPartitionedExclusiveMul:
7214 case glslang::EOpSubgroupPartitionedExclusiveMin:
7215 case glslang::EOpSubgroupPartitionedExclusiveMax:
7216 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7217 case glslang::EOpSubgroupPartitionedExclusiveOr:
7218 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007219 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007220 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007221 }
7222
John Kessenich149afc32018-08-14 13:31:43 -06007223 // build the instruction
7224 std::vector<spv::IdImmediate> spvGroupOperands;
7225
7226 // Every operation begins with the Execution Scope operand.
7227 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7228 spvGroupOperands.push_back(executionScope);
7229
7230 // Next, for all operations that use a Group Operation, push that as an operand.
7231 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007232 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007233 spvGroupOperands.push_back(groupOperand);
7234 }
7235
John Kessenich66011cb2018-03-06 16:12:04 -07007236 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007237 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7238 spv::IdImmediate operand = { true, *opIt };
7239 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007240 }
7241
7242 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007243 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007244 switch (op) {
7245 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007246 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7247 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7248 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7249 }
7250 if (directionId != spv::NoResult) {
7251 spv::IdImmediate direction = { true, directionId };
7252 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007253 }
7254
7255 return builder.createOp(opCode, typeId, spvGroupOperands);
7256}
7257
John Kessenich8985fc92020-03-03 10:25:07 -07007258spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7259 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007260{
John Kessenich66011cb2018-03-06 16:12:04 -07007261 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7262 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007263
John Kessenich140f3df2015-06-26 16:58:36 -06007264 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007265 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007266 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007267 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007268 spv::Id typeId0 = 0;
7269 if (consumedOperands > 0)
7270 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007271 spv::Id typeId1 = 0;
7272 if (consumedOperands > 1)
7273 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007274 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007275
7276 switch (op) {
7277 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007278 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007279 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007280 else if (isUnsigned)
7281 libCall = spv::GLSLstd450UMin;
7282 else
7283 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007284 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007285 break;
7286 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007287 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007288 break;
7289 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007290 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007291 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007292 else if (isUnsigned)
7293 libCall = spv::GLSLstd450UMax;
7294 else
7295 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007296 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007297 break;
7298 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007299 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007300 break;
7301 case glslang::EOpDot:
7302 opCode = spv::OpDot;
7303 break;
7304 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007305 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007306 break;
7307
7308 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007309 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007310 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007311 else if (isUnsigned)
7312 libCall = spv::GLSLstd450UClamp;
7313 else
7314 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007315 builder.promoteScalar(precision, operands.front(), operands[1]);
7316 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007317 break;
7318 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007319 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7320 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007321 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007322 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007323 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007324 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007325 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007326 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007327 break;
7328 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007329 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007330 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007331 break;
7332 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007333 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007334 builder.promoteScalar(precision, operands[0], operands[2]);
7335 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007336 break;
7337
7338 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007339 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007340 break;
7341 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007342 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007343 break;
7344 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007345 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007346 break;
7347 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007348 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007349 break;
7350 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007351 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007352 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007353 case glslang::EOpBarrier:
7354 {
7355 // This is for the extended controlBarrier function, with four operands.
7356 // The unextended barrier() goes through createNoArgOperation.
7357 assert(operands.size() == 4);
7358 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7359 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7360 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007361 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7362 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007363 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7364 spv::MemorySemanticsMakeVisibleKHRMask |
7365 spv::MemorySemanticsOutputMemoryKHRMask |
7366 spv::MemorySemanticsVolatileMask)) {
7367 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7368 }
John Kessenich8985fc92020-03-03 10:25:07 -07007369 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7370 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007371 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7372 }
7373 return 0;
7374 }
7375 break;
7376 case glslang::EOpMemoryBarrier:
7377 {
7378 // This is for the extended memoryBarrier function, with three operands.
7379 // The unextended memoryBarrier() goes through createNoArgOperation.
7380 assert(operands.size() == 3);
7381 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7382 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7383 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7384 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7385 spv::MemorySemanticsMakeVisibleKHRMask |
7386 spv::MemorySemanticsOutputMemoryKHRMask |
7387 spv::MemorySemanticsVolatileMask)) {
7388 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7389 }
7390 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7391 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7392 }
7393 return 0;
7394 }
7395 break;
7396
John Kessenicha28f7a72019-08-06 07:00:58 -06007397#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007398 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007399 if (typeProxy == glslang::EbtFloat16)
7400 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007401 libCall = spv::GLSLstd450InterpolateAtSample;
7402 break;
7403 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007404 if (typeProxy == glslang::EbtFloat16)
7405 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007406 libCall = spv::GLSLstd450InterpolateAtOffset;
7407 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007408 case glslang::EOpAddCarry:
7409 opCode = spv::OpIAddCarry;
7410 typeId = builder.makeStructResultType(typeId0, typeId0);
7411 consumedOperands = 2;
7412 break;
7413 case glslang::EOpSubBorrow:
7414 opCode = spv::OpISubBorrow;
7415 typeId = builder.makeStructResultType(typeId0, typeId0);
7416 consumedOperands = 2;
7417 break;
7418 case glslang::EOpUMulExtended:
7419 opCode = spv::OpUMulExtended;
7420 typeId = builder.makeStructResultType(typeId0, typeId0);
7421 consumedOperands = 2;
7422 break;
7423 case glslang::EOpIMulExtended:
7424 opCode = spv::OpSMulExtended;
7425 typeId = builder.makeStructResultType(typeId0, typeId0);
7426 consumedOperands = 2;
7427 break;
7428 case glslang::EOpBitfieldExtract:
7429 if (isUnsigned)
7430 opCode = spv::OpBitFieldUExtract;
7431 else
7432 opCode = spv::OpBitFieldSExtract;
7433 break;
7434 case glslang::EOpBitfieldInsert:
7435 opCode = spv::OpBitFieldInsert;
7436 break;
7437
7438 case glslang::EOpFma:
7439 libCall = spv::GLSLstd450Fma;
7440 break;
7441 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007442 {
7443 libCall = spv::GLSLstd450FrexpStruct;
7444 assert(builder.isPointerType(typeId1));
7445 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007446 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007447 if (width == 16)
7448 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7449 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007450 if (builder.getNumComponents(operands[0]) == 1)
7451 frexpIntType = builder.makeIntegerType(width, true);
7452 else
John Kessenich8985fc92020-03-03 10:25:07 -07007453 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7454 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007455 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7456 consumedOperands = 1;
7457 }
John Kessenich55e7d112015-11-15 21:33:39 -07007458 break;
7459 case glslang::EOpLdexp:
7460 libCall = spv::GLSLstd450Ldexp;
7461 break;
7462
Rex Xu574ab042016-04-14 16:53:07 +08007463 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007464 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007465
John Kessenich66011cb2018-03-06 16:12:04 -07007466 case glslang::EOpSubgroupBroadcast:
7467 case glslang::EOpSubgroupBallotBitExtract:
7468 case glslang::EOpSubgroupShuffle:
7469 case glslang::EOpSubgroupShuffleXor:
7470 case glslang::EOpSubgroupShuffleUp:
7471 case glslang::EOpSubgroupShuffleDown:
7472 case glslang::EOpSubgroupClusteredAdd:
7473 case glslang::EOpSubgroupClusteredMul:
7474 case glslang::EOpSubgroupClusteredMin:
7475 case glslang::EOpSubgroupClusteredMax:
7476 case glslang::EOpSubgroupClusteredAnd:
7477 case glslang::EOpSubgroupClusteredOr:
7478 case glslang::EOpSubgroupClusteredXor:
7479 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007480 case glslang::EOpSubgroupPartitionedAdd:
7481 case glslang::EOpSubgroupPartitionedMul:
7482 case glslang::EOpSubgroupPartitionedMin:
7483 case glslang::EOpSubgroupPartitionedMax:
7484 case glslang::EOpSubgroupPartitionedAnd:
7485 case glslang::EOpSubgroupPartitionedOr:
7486 case glslang::EOpSubgroupPartitionedXor:
7487 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7488 case glslang::EOpSubgroupPartitionedInclusiveMul:
7489 case glslang::EOpSubgroupPartitionedInclusiveMin:
7490 case glslang::EOpSubgroupPartitionedInclusiveMax:
7491 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7492 case glslang::EOpSubgroupPartitionedInclusiveOr:
7493 case glslang::EOpSubgroupPartitionedInclusiveXor:
7494 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7495 case glslang::EOpSubgroupPartitionedExclusiveMul:
7496 case glslang::EOpSubgroupPartitionedExclusiveMin:
7497 case glslang::EOpSubgroupPartitionedExclusiveMax:
7498 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7499 case glslang::EOpSubgroupPartitionedExclusiveOr:
7500 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007501 return createSubgroupOperation(op, typeId, operands, typeProxy);
7502
Rex Xu9d93a232016-05-05 12:30:44 +08007503 case glslang::EOpSwizzleInvocations:
7504 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7505 libCall = spv::SwizzleInvocationsAMD;
7506 break;
7507 case glslang::EOpSwizzleInvocationsMasked:
7508 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7509 libCall = spv::SwizzleInvocationsMaskedAMD;
7510 break;
7511 case glslang::EOpWriteInvocation:
7512 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7513 libCall = spv::WriteInvocationAMD;
7514 break;
7515
7516 case glslang::EOpMin3:
7517 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7518 if (isFloat)
7519 libCall = spv::FMin3AMD;
7520 else {
7521 if (isUnsigned)
7522 libCall = spv::UMin3AMD;
7523 else
7524 libCall = spv::SMin3AMD;
7525 }
7526 break;
7527 case glslang::EOpMax3:
7528 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7529 if (isFloat)
7530 libCall = spv::FMax3AMD;
7531 else {
7532 if (isUnsigned)
7533 libCall = spv::UMax3AMD;
7534 else
7535 libCall = spv::SMax3AMD;
7536 }
7537 break;
7538 case glslang::EOpMid3:
7539 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7540 if (isFloat)
7541 libCall = spv::FMid3AMD;
7542 else {
7543 if (isUnsigned)
7544 libCall = spv::UMid3AMD;
7545 else
7546 libCall = spv::SMid3AMD;
7547 }
7548 break;
7549
7550 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007551 if (typeProxy == glslang::EbtFloat16)
7552 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007553 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7554 libCall = spv::InterpolateAtVertexAMD;
7555 break;
Chao Chen3c366992018-09-19 11:41:59 -07007556
Chao Chenb50c02e2018-09-19 11:42:24 -07007557 case glslang::EOpReportIntersectionNV:
7558 {
7559 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007560 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007561 }
7562 break;
7563 case glslang::EOpTraceNV:
7564 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007565 builder.createNoResultOp(spv::OpTraceNV, operands);
7566 return 0;
7567 }
7568 break;
7569 case glslang::EOpExecuteCallableNV:
7570 {
7571 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007572 return 0;
7573 }
7574 break;
Chao Chen3c366992018-09-19 11:41:59 -07007575 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7576 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7577 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007578 case glslang::EOpCooperativeMatrixMulAdd:
7579 opCode = spv::OpCooperativeMatrixMulAddNV;
7580 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007581#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007582 default:
7583 return 0;
7584 }
7585
7586 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007587 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007588 // Use an extended instruction from the standard library.
7589 // Construct the call arguments, without modifying the original operands vector.
7590 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7591 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007592 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007593 } else if (opCode == spv::OpDot && !isFloat) {
7594 // int dot(int, int)
7595 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7596 const int componentCount = builder.getNumComponents(operands[0]);
7597 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7598 builder.setPrecision(mulOp, precision);
7599 id = builder.createCompositeExtract(mulOp, typeId, 0);
7600 for (int i = 1; i < componentCount; ++i) {
7601 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07007602 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01007603 }
John Kessenich2359bd02015-12-06 19:29:11 -07007604 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007605 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007606 case 0:
7607 // should all be handled by visitAggregate and createNoArgOperation
7608 assert(0);
7609 return 0;
7610 case 1:
7611 // should all be handled by createUnaryOperation
7612 assert(0);
7613 return 0;
7614 case 2:
7615 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7616 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007617 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007618 // anything 3 or over doesn't have l-value operands, so all should be consumed
7619 assert(consumedOperands == operands.size());
7620 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007621 break;
7622 }
7623 }
7624
John Kessenichb9197c82019-08-11 07:41:45 -06007625#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007626 // Decode the return types that were structures
7627 switch (op) {
7628 case glslang::EOpAddCarry:
7629 case glslang::EOpSubBorrow:
7630 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7631 id = builder.createCompositeExtract(id, typeId0, 0);
7632 break;
7633 case glslang::EOpUMulExtended:
7634 case glslang::EOpIMulExtended:
7635 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7636 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7637 break;
7638 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007639 {
7640 assert(operands.size() == 2);
7641 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7642 // "exp" is floating-point type (from HLSL intrinsic)
7643 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7644 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7645 builder.createStore(member1, operands[1]);
7646 } else
7647 // "exp" is integer type (from GLSL built-in function)
7648 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7649 id = builder.createCompositeExtract(id, typeId0, 0);
7650 }
John Kessenich55e7d112015-11-15 21:33:39 -07007651 break;
7652 default:
7653 break;
7654 }
John Kessenichb9197c82019-08-11 07:41:45 -06007655#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007656
John Kessenich32cfd492016-02-02 12:37:46 -07007657 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007658}
7659
Rex Xu9d93a232016-05-05 12:30:44 +08007660// Intrinsics with no arguments (or no return value, and no precision).
7661spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007662{
Jeff Bolz36831c92018-09-05 10:11:41 -05007663 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07007664 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
7665 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007666
7667 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007668 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007669 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007670 if (glslangIntermediate->usingVulkanMemoryModel()) {
7671 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7672 spv::MemorySemanticsOutputMemoryKHRMask |
7673 spv::MemorySemanticsAcquireReleaseMask);
7674 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7675 } else {
7676 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7677 }
John Kessenich82979362017-12-11 04:02:24 -07007678 } else {
7679 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7680 spv::MemorySemanticsWorkgroupMemoryMask |
7681 spv::MemorySemanticsAcquireReleaseMask);
7682 }
John Kessenich140f3df2015-06-26 16:58:36 -06007683 return 0;
7684 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007685 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7686 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007687 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007688 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007689 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7690 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007691 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007692 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007693 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7694 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007695 return 0;
7696 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007697 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7698 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007699 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007700#ifndef GLSLANG_WEB
7701 case glslang::EOpMemoryBarrierAtomicCounter:
7702 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7703 spv::MemorySemanticsAcquireReleaseMask);
7704 return 0;
7705 case glslang::EOpMemoryBarrierImage:
7706 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7707 spv::MemorySemanticsAcquireReleaseMask);
7708 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007709 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007710 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007711 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007712 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007713 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007714 case glslang::EOpDeviceMemoryBarrier:
7715 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7716 spv::MemorySemanticsImageMemoryMask |
7717 spv::MemorySemanticsAcquireReleaseMask);
7718 return 0;
7719 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7720 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7721 spv::MemorySemanticsImageMemoryMask |
7722 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007723 return 0;
7724 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007725 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7726 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007727 return 0;
7728 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007729 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7730 spv::MemorySemanticsWorkgroupMemoryMask |
7731 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007732 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007733 case glslang::EOpSubgroupBarrier:
7734 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7735 spv::MemorySemanticsAcquireReleaseMask);
7736 return spv::NoResult;
7737 case glslang::EOpSubgroupMemoryBarrier:
7738 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7739 spv::MemorySemanticsAcquireReleaseMask);
7740 return spv::NoResult;
7741 case glslang::EOpSubgroupMemoryBarrierBuffer:
7742 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7743 spv::MemorySemanticsAcquireReleaseMask);
7744 return spv::NoResult;
7745 case glslang::EOpSubgroupMemoryBarrierImage:
7746 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7747 spv::MemorySemanticsAcquireReleaseMask);
7748 return spv::NoResult;
7749 case glslang::EOpSubgroupMemoryBarrierShared:
7750 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7751 spv::MemorySemanticsAcquireReleaseMask);
7752 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06007753
7754 case glslang::EOpEmitVertex:
7755 builder.createNoResultOp(spv::OpEmitVertex);
7756 return 0;
7757 case glslang::EOpEndPrimitive:
7758 builder.createNoResultOp(spv::OpEndPrimitive);
7759 return 0;
7760
John Kessenich66011cb2018-03-06 16:12:04 -07007761 case glslang::EOpSubgroupElect: {
7762 std::vector<spv::Id> operands;
7763 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7764 }
Rex Xu9d93a232016-05-05 12:30:44 +08007765 case glslang::EOpTime:
7766 {
7767 std::vector<spv::Id> args; // Dummy arguments
7768 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7769 return builder.setPrecision(id, precision);
7770 }
Chao Chenb50c02e2018-09-19 11:42:24 -07007771 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007772 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007773 return 0;
7774 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007775 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007776 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007777
7778 case glslang::EOpBeginInvocationInterlock:
7779 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7780 return 0;
7781 case glslang::EOpEndInvocationInterlock:
7782 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7783 return 0;
7784
Jeff Bolzba6170b2019-07-01 09:23:23 -05007785 case glslang::EOpIsHelperInvocation:
7786 {
7787 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08007788 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
7789 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
7790 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05007791 }
7792
amhagan91fb0092019-07-10 21:14:38 -04007793 case glslang::EOpReadClockSubgroupKHR: {
7794 std::vector<spv::Id> args;
7795 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
7796 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7797 builder.addCapability(spv::CapabilityShaderClockKHR);
7798 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7799 }
7800
7801 case glslang::EOpReadClockDeviceKHR: {
7802 std::vector<spv::Id> args;
7803 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
7804 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7805 builder.addCapability(spv::CapabilityShaderClockKHR);
7806 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7807 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06007808#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007809 default:
John Kessenich155d3512019-08-08 23:29:20 -06007810 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007811 }
John Kessenich155d3512019-08-08 23:29:20 -06007812
7813 logger->missingFunctionality("unknown operation with no arguments");
7814
7815 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007816}
7817
7818spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7819{
John Kessenich2f273362015-07-18 22:34:27 -06007820 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007821 spv::Id id;
7822 if (symbolValues.end() != iter) {
7823 id = iter->second;
7824 return id;
7825 }
7826
7827 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06007828 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
7829 auto forcedType = getForcedType(builtIn, symbol->getType());
7830 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06007831 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06007832 if (forcedType.second != spv::NoType)
7833 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06007834
Rex Xuc884b4a2016-06-29 15:03:44 +08007835 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007836 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7837 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7838 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06007839#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007840 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06007841 if (symbol->getQualifier().hasComponent())
7842 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
7843 if (symbol->getQualifier().hasIndex())
7844 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07007845#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007846 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007847 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06007848 // atomic counters use this:
7849 if (symbol->getQualifier().hasOffset())
7850 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007851 }
7852
scygan2c864272016-05-18 18:09:17 +02007853 if (symbol->getQualifier().hasLocation())
7854 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007855 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007856 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007857 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007858 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007859 }
John Kessenich140f3df2015-06-26 16:58:36 -06007860 if (symbol->getQualifier().hasSet())
7861 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007862 else if (IsDescriptorResource(symbol->getType())) {
7863 // default to 0
7864 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7865 }
John Kessenich140f3df2015-06-26 16:58:36 -06007866 if (symbol->getQualifier().hasBinding())
7867 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007868 else if (IsDescriptorResource(symbol->getType())) {
7869 // default to 0
7870 builder.addDecoration(id, spv::DecorationBinding, 0);
7871 }
John Kessenich6c292d32016-02-15 20:58:50 -07007872 if (symbol->getQualifier().hasAttachment())
7873 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007874 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007875 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007876 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007877 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007878 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7879 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7880 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7881 }
7882 if (symbol->getQualifier().hasXfbOffset())
7883 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007884 }
7885
John Kessenichb9197c82019-08-11 07:41:45 -06007886 // add built-in variable decoration
7887 if (builtIn != spv::BuiltInMax) {
7888 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
7889 }
7890
7891#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08007892 if (symbol->getType().isImage()) {
7893 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07007894 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
7895 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007896 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007897 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007898 }
7899
John Kessenich5611c6d2018-04-05 11:25:02 -06007900 // nonuniform
7901 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7902
chaoc0ad6a4e2016-12-19 16:29:34 -08007903 if (builtIn == spv::BuiltInSampleMask) {
7904 spv::Decoration decoration;
7905 // GL_NV_sample_mask_override_coverage extension
7906 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007907 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007908 else
7909 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007910 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007911 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07007912 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08007913 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7914 }
7915 }
chaoc771d89f2017-01-13 01:10:53 -08007916 else if (builtIn == spv::BuiltInLayer) {
7917 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007918 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007919 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007920 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7921 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7922 }
John Kessenichb41bff62017-08-11 13:07:17 -06007923 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007924 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7925 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007926 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7927 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7928 }
7929 }
7930
chaoc6e5acae2016-12-20 13:28:52 -08007931 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007932 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007933 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007934 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7935 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007936 if (symbol->getQualifier().pervertexNV) {
7937 builder.addDecoration(id, spv::DecorationPerVertexNV);
7938 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7939 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7940 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007941
John Kessenich5d610ee2018-03-07 18:05:55 -07007942 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7943 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7944 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7945 symbol->getType().getQualifier().semanticName);
7946 }
7947
John Kessenich7015bd62019-08-01 03:28:08 -06007948 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07007949 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
7950 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007951 }
John Kessenichb9197c82019-08-11 07:41:45 -06007952#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007953
John Kessenich140f3df2015-06-26 16:58:36 -06007954 return id;
7955}
7956
John Kessenicha28f7a72019-08-06 07:00:58 -06007957#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007958// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7959void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7960{
7961 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007962 if (qualifier.perPrimitiveNV) {
7963 // Need to add capability/extension for fragment shader.
7964 // Mesh shader already adds this by default.
7965 if (glslangIntermediate->getStage() == EShLangFragment) {
7966 builder.addCapability(spv::CapabilityMeshShadingNV);
7967 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7968 }
Chao Chen3c366992018-09-19 11:41:59 -07007969 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007970 }
Chao Chen3c366992018-09-19 11:41:59 -07007971 if (qualifier.perViewNV)
7972 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7973 if (qualifier.perTaskNV)
7974 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7975 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007976 if (qualifier.perPrimitiveNV) {
7977 // Need to add capability/extension for fragment shader.
7978 // Mesh shader already adds this by default.
7979 if (glslangIntermediate->getStage() == EShLangFragment) {
7980 builder.addCapability(spv::CapabilityMeshShadingNV);
7981 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7982 }
Chao Chen3c366992018-09-19 11:41:59 -07007983 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007984 }
Chao Chen3c366992018-09-19 11:41:59 -07007985 if (qualifier.perViewNV)
7986 builder.addDecoration(id, spv::DecorationPerViewNV);
7987 if (qualifier.perTaskNV)
7988 builder.addDecoration(id, spv::DecorationPerTaskNV);
7989 }
7990}
7991#endif
7992
John Kessenich55e7d112015-11-15 21:33:39 -07007993// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007994// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007995//
7996// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7997//
7998// Recursively walk the nodes. The nodes form a tree whose leaves are
7999// regular constants, which themselves are trees that createSpvConstant()
8000// recursively walks. So, this function walks the "top" of the tree:
8001// - emit specialization constant-building instructions for specConstant
8002// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008003spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008004{
John Kessenich7cc0e282016-03-20 00:46:02 -06008005 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008006
qining4f4bb812016-04-03 23:55:17 -04008007 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008008 if (! node.getQualifier().specConstant) {
8009 // hand off to the non-spec-constant path
8010 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8011 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008012 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8013 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8014 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008015 }
8016
8017 // We now know we have a specialization constant to build
8018
John Kessenichd94c0032016-05-30 19:29:40 -06008019 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008020 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8021 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8022 std::vector<spv::Id> dimConstId;
8023 for (int dim = 0; dim < 3; ++dim) {
8024 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8025 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008026 if (specConst) {
8027 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8028 glslangIntermediate->getLocalSizeSpecId(dim));
8029 }
qining4f4bb812016-04-03 23:55:17 -04008030 }
8031 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8032 }
8033
8034 // An AST node labelled as specialization constant should be a symbol node.
8035 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8036 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008037 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008038 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008039 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8040 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8041 // will set the builder into spec constant op instruction generating mode.
8042 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008043 result = accessChainLoad(sub_tree->getType());
8044 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008045 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008046 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008047 } else {
8048 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008049 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008050 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008051 builder.addName(result, sn->getName().c_str());
8052 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008053 }
qining4f4bb812016-04-03 23:55:17 -04008054
8055 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8056 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008057 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008058 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008059}
8060
John Kessenich140f3df2015-06-26 16:58:36 -06008061// Use 'consts' as the flattened glslang source of scalar constants to recursively
8062// build the aggregate SPIR-V constant.
8063//
8064// If there are not enough elements present in 'consts', 0 will be substituted;
8065// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8066//
John Kessenich8985fc92020-03-03 10:25:07 -07008067spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8068 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008069{
8070 // vector of constants for SPIR-V
8071 std::vector<spv::Id> spvConsts;
8072
8073 // Type is used for struct and array constants
8074 spv::Id typeId = convertGlslangToSpvType(glslangType);
8075
8076 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008077 glslang::TType elementType(glslangType, 0);
8078 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008079 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008080 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008081 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008082 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008083 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008084 } else if (glslangType.isCoopMat()) {
8085 glslang::TType componentType(glslangType.getBasicType());
8086 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008087 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008088 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8089 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008090 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008091 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008092 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8093 bool zero = nextConst >= consts.size();
8094 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008095 case glslang::EbtInt:
8096 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8097 break;
8098 case glslang::EbtUint:
8099 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8100 break;
8101 case glslang::EbtFloat:
8102 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8103 break;
8104 case glslang::EbtBool:
8105 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8106 break;
8107#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008108 case glslang::EbtInt8:
8109 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8110 break;
8111 case glslang::EbtUint8:
8112 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8113 break;
8114 case glslang::EbtInt16:
8115 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8116 break;
8117 case glslang::EbtUint16:
8118 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8119 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008120 case glslang::EbtInt64:
8121 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8122 break;
8123 case glslang::EbtUint64:
8124 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8125 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008126 case glslang::EbtDouble:
8127 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8128 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008129 case glslang::EbtFloat16:
8130 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8131 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008132#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008133 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008134 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008135 break;
8136 }
8137 ++nextConst;
8138 }
8139 } else {
8140 // we have a non-aggregate (scalar) constant
8141 bool zero = nextConst >= consts.size();
8142 spv::Id scalar = 0;
8143 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008144 case glslang::EbtInt:
8145 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8146 break;
8147 case glslang::EbtUint:
8148 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8149 break;
8150 case glslang::EbtFloat:
8151 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8152 break;
8153 case glslang::EbtBool:
8154 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8155 break;
8156#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008157 case glslang::EbtInt8:
8158 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8159 break;
8160 case glslang::EbtUint8:
8161 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8162 break;
8163 case glslang::EbtInt16:
8164 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8165 break;
8166 case glslang::EbtUint16:
8167 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8168 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008169 case glslang::EbtInt64:
8170 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8171 break;
8172 case glslang::EbtUint64:
8173 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8174 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008175 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008176 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008177 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008178 case glslang::EbtFloat16:
8179 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8180 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008181 case glslang::EbtReference:
8182 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8183 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8184 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008185#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008186 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008187 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008188 break;
8189 }
8190 ++nextConst;
8191 return scalar;
8192 }
8193
8194 return builder.makeCompositeConstant(typeId, spvConsts);
8195}
8196
John Kessenich7c1aa102015-10-15 13:29:11 -06008197// Return true if the node is a constant or symbol whose reading has no
8198// non-trivial observable cost or effect.
8199bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8200{
8201 // don't know what this is
8202 if (node == nullptr)
8203 return false;
8204
8205 // a constant is safe
8206 if (node->getAsConstantUnion() != nullptr)
8207 return true;
8208
8209 // not a symbol means non-trivial
8210 if (node->getAsSymbolNode() == nullptr)
8211 return false;
8212
8213 // a symbol, depends on what's being read
8214 switch (node->getType().getQualifier().storage) {
8215 case glslang::EvqTemporary:
8216 case glslang::EvqGlobal:
8217 case glslang::EvqIn:
8218 case glslang::EvqInOut:
8219 case glslang::EvqConst:
8220 case glslang::EvqConstReadOnly:
8221 case glslang::EvqUniform:
8222 return true;
8223 default:
8224 return false;
8225 }
qining25262b32016-05-06 17:25:16 -04008226}
John Kessenich7c1aa102015-10-15 13:29:11 -06008227
8228// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008229// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008230// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008231// Return true if trivial.
8232bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8233{
8234 if (node == nullptr)
8235 return false;
8236
John Kessenich84cc15f2017-05-24 16:44:47 -06008237 // count non scalars as trivial, as well as anything coming from HLSL
8238 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008239 return true;
8240
John Kessenich7c1aa102015-10-15 13:29:11 -06008241 // symbols and constants are trivial
8242 if (isTrivialLeaf(node))
8243 return true;
8244
8245 // otherwise, it needs to be a simple operation or one or two leaf nodes
8246
8247 // not a simple operation
8248 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8249 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8250 if (binaryNode == nullptr && unaryNode == nullptr)
8251 return false;
8252
8253 // not on leaf nodes
8254 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8255 return false;
8256
8257 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8258 return false;
8259 }
8260
8261 switch (node->getAsOperator()->getOp()) {
8262 case glslang::EOpLogicalNot:
8263 case glslang::EOpConvIntToBool:
8264 case glslang::EOpConvUintToBool:
8265 case glslang::EOpConvFloatToBool:
8266 case glslang::EOpConvDoubleToBool:
8267 case glslang::EOpEqual:
8268 case glslang::EOpNotEqual:
8269 case glslang::EOpLessThan:
8270 case glslang::EOpGreaterThan:
8271 case glslang::EOpLessThanEqual:
8272 case glslang::EOpGreaterThanEqual:
8273 case glslang::EOpIndexDirect:
8274 case glslang::EOpIndexDirectStruct:
8275 case glslang::EOpLogicalXor:
8276 case glslang::EOpAny:
8277 case glslang::EOpAll:
8278 return true;
8279 default:
8280 return false;
8281 }
8282}
8283
8284// Emit short-circuiting code, where 'right' is never evaluated unless
8285// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008286spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8287 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008288{
8289 spv::Id boolTypeId = builder.makeBoolType();
8290
8291 // emit left operand
8292 builder.clearAccessChain();
8293 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008294 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008295
8296 // Operands to accumulate OpPhi operands
8297 std::vector<spv::Id> phiOperands;
8298 // accumulate left operand's phi information
8299 phiOperands.push_back(leftId);
8300 phiOperands.push_back(builder.getBuildPoint()->getId());
8301
8302 // Make the two kinds of operation symmetric with a "!"
8303 // || => emit "if (! left) result = right"
8304 // && => emit "if ( left) result = right"
8305 //
8306 // TODO: this runtime "not" for || could be avoided by adding functionality
8307 // to 'builder' to have an "else" without an "then"
8308 if (op == glslang::EOpLogicalOr)
8309 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8310
8311 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008312 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008313
8314 // emit right operand as the "then" part of the "if"
8315 builder.clearAccessChain();
8316 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008317 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008318
8319 // accumulate left operand's phi information
8320 phiOperands.push_back(rightId);
8321 phiOperands.push_back(builder.getBuildPoint()->getId());
8322
8323 // finish the "if"
8324 ifBuilder.makeEndIf();
8325
8326 // phi together the two results
8327 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8328}
8329
John Kessenicha28f7a72019-08-06 07:00:58 -06008330#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008331// Return type Id of the imported set of extended instructions corresponds to the name.
8332// Import this set if it has not been imported yet.
8333spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8334{
8335 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8336 return extBuiltinMap[name];
8337 else {
Rex Xu51596642016-09-21 18:56:12 +08008338 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008339 spv::Id extBuiltins = builder.import(name);
8340 extBuiltinMap[name] = extBuiltins;
8341 return extBuiltins;
8342 }
8343}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008344#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008345
John Kessenich140f3df2015-06-26 16:58:36 -06008346}; // end anonymous namespace
8347
8348namespace glslang {
8349
John Kessenich68d78fd2015-07-12 19:28:10 -06008350void GetSpirvVersion(std::string& version)
8351{
John Kessenich9e55f632015-07-15 10:03:39 -06008352 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008353 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008354 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008355 version = buf;
8356}
8357
John Kessenicha372a3e2017-11-02 22:32:14 -06008358// For low-order part of the generator's magic number. Bump up
8359// when there is a change in the style (e.g., if SSA form changes,
8360// or a different instruction sequence to do something gets used).
8361int GetSpirvGeneratorVersion()
8362{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008363 // return 1; // start
8364 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008365 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008366 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008367 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008368 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8369 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008370 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
8371 return 8; // switch to new dead block eliminator; use OpUnreachable
John Kessenicha372a3e2017-11-02 22:32:14 -06008372}
8373
John Kessenich140f3df2015-06-26 16:58:36 -06008374// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008375void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008376{
8377 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008378 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008379 if (out.fail())
8380 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008381 for (int i = 0; i < (int)spirv.size(); ++i) {
8382 unsigned int word = spirv[i];
8383 out.write((const char*)&word, 4);
8384 }
8385 out.close();
8386}
8387
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008388// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008389void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008390{
John Kessenich155d3512019-08-08 23:29:20 -06008391#ifndef GLSLANG_WEB
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008392 std::ofstream out;
8393 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008394 if (out.fail())
8395 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008396 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008397 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008398 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008399 if (varName != nullptr) {
8400 out << "\t #pragma once" << std::endl;
8401 out << "const uint32_t " << varName << "[] = {" << std::endl;
8402 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008403 const int WORDS_PER_LINE = 8;
8404 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8405 out << "\t";
8406 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8407 const unsigned int word = spirv[i + j];
8408 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8409 if (i + j + 1 < (int)spirv.size()) {
8410 out << ",";
8411 }
8412 }
8413 out << std::endl;
8414 }
Flavio15017db2017-02-15 14:29:33 -08008415 if (varName != nullptr) {
8416 out << "};";
8417 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008418 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008419#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008420}
8421
John Kessenich140f3df2015-06-26 16:58:36 -06008422//
8423// Set up the glslang traversal
8424//
John Kessenich4e11b612018-08-30 16:56:59 -06008425void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008426{
Lei Zhang17535f72016-05-04 15:55:59 -04008427 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008428 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008429}
8430
John Kessenich4e11b612018-08-30 16:56:59 -06008431void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008432 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008433{
John Kessenich140f3df2015-06-26 16:58:36 -06008434 TIntermNode* root = intermediate.getTreeRoot();
8435
8436 if (root == 0)
8437 return;
8438
John Kessenich4e11b612018-08-30 16:56:59 -06008439 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008440 if (options == nullptr)
8441 options = &defaultOptions;
8442
John Kessenich4e11b612018-08-30 16:56:59 -06008443 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008444
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008445 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008446 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008447 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008448 it.dumpSpv(spirv);
8449
GregFfb03a552018-03-29 11:49:14 -06008450#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008451 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8452 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008453 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8454 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008455 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008456 prelegalization = false;
8457 }
John Kessenich717c80a2018-08-23 15:17:10 -06008458
John Kessenich4e11b612018-08-30 16:56:59 -06008459 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008460 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008461
John Kessenich717c80a2018-08-23 15:17:10 -06008462 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008463 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008464
GregFcd1f1692017-09-21 18:40:22 -06008465#endif
8466
John Kessenich4e11b612018-08-30 16:56:59 -06008467 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008468}
8469
8470}; // end namespace glslang