blob: 12c6e49175afaef968668dcb2e379282e80cf327 [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 Kessenichb23d2322018-12-14 10:47:35 -07003// Copyright (C) 2015-2018 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 {
90 spv::Decoration precision;
91 spv::Decoration noContraction;
John Kessenich5611c6d2018-04-05 11:25:02 -060092 spv::Decoration nonUniform;
John Kessenichead86222018-03-28 18:01:20 -060093};
94
95} // namespace
qining4c912612016-04-01 10:35:16 -040096
John Kessenich140f3df2015-06-26 16:58:36 -060097//
98// The main holder of information for translating glslang to SPIR-V.
99//
100// Derives from the AST walking base class.
101//
102class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
103public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700104 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
105 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700106 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600107
108 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
109 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
110 void visitConstantUnion(glslang::TIntermConstantUnion*);
111 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
112 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
113 void visitSymbol(glslang::TIntermSymbol* symbol);
114 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
115 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
116 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
117
John Kessenichfca82622016-11-26 13:23:20 -0700118 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700119 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600120
121protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700122 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
123 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
124
Rex Xu17ff3432016-10-14 17:41:45 +0800125 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800126 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600127 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500128 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
129 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
130 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
131 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100132 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700133 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700134 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
135 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700136 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600137 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600138 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich9c14f772019-06-17 08:38:35 -0600139 spv::Id createSpvVariable(const glslang::TIntermSymbol*, spv::Id forcedType);
John Kessenich140f3df2015-06-26 16:58:36 -0600140 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600141 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
142 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
143 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600144 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600145 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600146 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600147 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600148 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
149 glslang::TLayoutPacking, const glslang::TQualifier&);
150 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
151 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700152 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700153 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800154 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600155 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700156 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700157 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
158 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700159 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
160 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100161 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600162
John Kessenich6fccb3c2016-09-19 16:01:41 -0600163 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600164 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600165 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600166 void makeFunctions(const glslang::TIntermSequence&);
167 void makeGlobalInitializers(const glslang::TIntermSequence&);
168 void visitFunctions(const glslang::TIntermSequence&);
169 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500170 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -0600171 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
172 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600173 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
174
John Kessenichead86222018-03-28 18:01:20 -0600175 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
176 glslang::TBasicType typeProxy, bool reduceComparison = true);
177 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
178 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500179 glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -0600180 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
181 glslang::TBasicType typeProxy);
182 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
183 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600184 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600185 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Jeff Bolz38a52fc2019-06-14 09:56:28 -0500186 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
Rex Xu51596642016-09-21 18:56:12 +0800187 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800188 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700189 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600190 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800191 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600192 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700193 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
qining08408382016-03-21 09:51:37 -0400194 spv::Id createSpvConstant(const glslang::TIntermTyped&);
195 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600196 bool isTrivialLeaf(const glslang::TIntermTyped* node);
197 bool isTrivial(const glslang::TIntermTyped* node);
198 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800199 spv::Id getExtBuiltins(const char* name);
John Kessenich66011cb2018-03-06 16:12:04 -0700200 void addPre13Extension(const char* ext)
201 {
202 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
203 builder.addExtension(ext);
204 }
John Kessenich9c14f772019-06-17 08:38:35 -0600205 std::pair<spv::Id, spv::Id> getForcedType(spv::BuiltIn, const glslang::TType&);
206 spv::Id translateForcedType(spv::Id object);
Jeff Bolz53134492019-06-25 13:31:10 -0500207 spv::Id createCompositeConstruct(spv::Id typeId, std::vector<spv::Id> constituents);
John Kessenich140f3df2015-06-26 16:58:36 -0600208
John Kessenich121853f2017-05-31 17:11:16 -0600209 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600210 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600211 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700212 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600213 int sequenceDepth;
214
Lei Zhang17535f72016-05-04 15:55:59 -0400215 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400216
John Kessenich140f3df2015-06-26 16:58:36 -0600217 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
218 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700219 bool inEntryPoint;
220 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700221 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700222 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600223 const glslang::TIntermediate* glslangIntermediate;
John Kessenich605afc72019-06-17 23:33:09 -0600224 bool nanMinMaxClamp; // true if use NMin/NMax/NClamp instead of FMin/FMax/FClamp
John Kessenich140f3df2015-06-26 16:58:36 -0600225 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800226 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600227
John Kessenich2f273362015-07-18 22:34:27 -0600228 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600229 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600230 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700231 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700232 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
233 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600234 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700235 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600236 // Map pointee types for EbtReference to their forward pointers
237 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich9c14f772019-06-17 08:38:35 -0600238 // Type forcing, for when SPIR-V wants a different type than the AST,
239 // requiring local translation to and from SPIR-V type on every access.
240 // Maps <builtin-variable-id -> AST-required-type-id>
241 std::unordered_map<spv::Id, spv::Id> forceType;
John Kessenich140f3df2015-06-26 16:58:36 -0600242};
243
244//
245// Helper functions for translating glslang representations to SPIR-V enumerants.
246//
247
248// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700249spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600250{
John Kessenich66e2faf2016-03-12 18:34:36 -0700251 switch (source) {
252 case glslang::EShSourceGlsl:
253 switch (profile) {
254 case ENoProfile:
255 case ECoreProfile:
256 case ECompatibilityProfile:
257 return spv::SourceLanguageGLSL;
258 case EEsProfile:
259 return spv::SourceLanguageESSL;
260 default:
261 return spv::SourceLanguageUnknown;
262 }
263 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600264 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600265 default:
266 return spv::SourceLanguageUnknown;
267 }
268}
269
270// Translate glslang language (stage) to SPIR-V execution model.
271spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
272{
273 switch (stage) {
274 case EShLangVertex: return spv::ExecutionModelVertex;
John Kessenicha28f7a72019-08-06 07:00:58 -0600275 case EShLangFragment: return spv::ExecutionModelFragment;
276#ifndef GLSLANG_WEB
277 case EShLangCompute: return spv::ExecutionModelGLCompute;
John Kessenich140f3df2015-06-26 16:58:36 -0600278 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
279 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
280 case EShLangGeometry: return spv::ExecutionModelGeometry;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700281 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
282 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
283 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
284 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
285 case EShLangMissNV: return spv::ExecutionModelMissNV;
286 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700287 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
288 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
289#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600290 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700291 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600292 return spv::ExecutionModelFragment;
293 }
294}
295
John Kessenich140f3df2015-06-26 16:58:36 -0600296// Translate glslang sampler type to SPIR-V dimensionality.
297spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
298{
299 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700300 case glslang::Esd1D: return spv::Dim1D;
301 case glslang::Esd2D: return spv::Dim2D;
302 case glslang::Esd3D: return spv::Dim3D;
303 case glslang::EsdCube: return spv::DimCube;
304 case glslang::EsdRect: return spv::DimRect;
305 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700306 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600307 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700308 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600309 return spv::Dim2D;
310 }
311}
312
John Kessenichf6640762016-08-01 19:44:00 -0600313// Translate glslang precision to SPIR-V precision decorations.
314spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600315{
John Kessenichf6640762016-08-01 19:44:00 -0600316 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700317 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600318 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600319 default:
320 return spv::NoPrecision;
321 }
322}
323
John Kessenichf6640762016-08-01 19:44:00 -0600324// Translate glslang type to SPIR-V precision decorations.
325spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
326{
327 return TranslatePrecisionDecoration(type.getQualifier().precision);
328}
329
John Kessenich140f3df2015-06-26 16:58:36 -0600330// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600331spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600332{
333 if (type.getBasicType() == glslang::EbtBlock) {
334 switch (type.getQualifier().storage) {
335 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600336 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600337 case glslang::EvqVaryingIn: return spv::DecorationBlock;
338 case glslang::EvqVaryingOut: return spv::DecorationBlock;
John Kessenicha28f7a72019-08-06 07:00:58 -0600339#ifndef GLSLANG_WEB
Chao Chenb50c02e2018-09-19 11:42:24 -0700340 case glslang::EvqPayloadNV: return spv::DecorationBlock;
341 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
342 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700343 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
344 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700345#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600346 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700347 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600348 break;
349 }
350 }
351
John Kessenich4016e382016-07-15 11:53:56 -0600352 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600353}
354
Rex Xu1da878f2016-02-21 20:59:01 +0800355// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500356void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800357{
Jeff Bolz36831c92018-09-05 10:11:41 -0500358 if (!useVulkanMemoryModel) {
359 if (qualifier.coherent)
360 memory.push_back(spv::DecorationCoherent);
361 if (qualifier.volatil) {
362 memory.push_back(spv::DecorationVolatile);
363 memory.push_back(spv::DecorationCoherent);
364 }
John Kessenich14b85d32018-06-04 15:36:03 -0600365 }
Rex Xu1da878f2016-02-21 20:59:01 +0800366 if (qualifier.restrict)
367 memory.push_back(spv::DecorationRestrict);
368 if (qualifier.readonly)
369 memory.push_back(spv::DecorationNonWritable);
370 if (qualifier.writeonly)
371 memory.push_back(spv::DecorationNonReadable);
372}
373
John Kessenich140f3df2015-06-26 16:58:36 -0600374// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700375spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600376{
377 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700378 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600379 case glslang::ElmRowMajor:
380 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700381 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600382 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700383 default:
384 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600385 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600386 }
387 } else {
388 switch (type.getBasicType()) {
389 default:
John Kessenich4016e382016-07-15 11:53:56 -0600390 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600391 break;
392 case glslang::EbtBlock:
393 switch (type.getQualifier().storage) {
394 case glslang::EvqUniform:
395 case glslang::EvqBuffer:
396 switch (type.getQualifier().layoutPacking) {
397 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600398 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
399 default:
John Kessenich4016e382016-07-15 11:53:56 -0600400 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600401 }
402 case glslang::EvqVaryingIn:
403 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700404 if (type.getQualifier().isTaskMemory()) {
405 switch (type.getQualifier().layoutPacking) {
406 case glslang::ElpShared: return spv::DecorationGLSLShared;
407 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
408 default: break;
409 }
410 } else {
411 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
412 }
John Kessenich4016e382016-07-15 11:53:56 -0600413 return spv::DecorationMax;
John Kessenicha28f7a72019-08-06 07:00:58 -0600414#ifndef GLSLANG_WEB
Chao Chenb50c02e2018-09-19 11:42:24 -0700415 case glslang::EvqPayloadNV:
416 case glslang::EvqPayloadInNV:
417 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700418 case glslang::EvqCallableDataNV:
419 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700420 return spv::DecorationMax;
421#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600422 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700423 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600424 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600425 }
426 }
427 }
428}
429
430// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600431// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700432// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800433spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600434{
Rex Xubbceed72016-05-21 09:40:44 +0800435 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700436 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600437 return spv::DecorationMax;
John Kessenich7015bd62019-08-01 03:28:08 -0600438 else if (qualifier.isNonPerspective())
John Kessenich55e7d112015-11-15 21:33:39 -0700439 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700440 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600441 return spv::DecorationFlat;
John Kessenicha28f7a72019-08-06 07:00:58 -0600442 else if (qualifier.isExplicitInterpolation()) {
Rex Xu17ff3432016-10-14 17:41:45 +0800443 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800444 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800445 }
Rex Xubbceed72016-05-21 09:40:44 +0800446 else
John Kessenich4016e382016-07-15 11:53:56 -0600447 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800448}
449
450// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600451// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800452// should be applied.
453spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
454{
455 if (qualifier.patch)
456 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700457 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600458 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700459 else if (qualifier.sample) {
460 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600461 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700462 } else
John Kessenich4016e382016-07-15 11:53:56 -0600463 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600464}
465
John Kessenich92187592016-02-01 13:45:25 -0700466// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700467spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600468{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700469 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600470 return spv::DecorationInvariant;
471 else
John Kessenich4016e382016-07-15 11:53:56 -0600472 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600473}
474
qining9220dbb2016-05-04 17:34:38 -0400475// If glslang type is noContraction, return SPIR-V NoContraction decoration.
476spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
477{
John Kessenicha28f7a72019-08-06 07:00:58 -0600478 if (qualifier.isNoContraction())
qining9220dbb2016-05-04 17:34:38 -0400479 return spv::DecorationNoContraction;
480 else
John Kessenich4016e382016-07-15 11:53:56 -0600481 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400482}
483
John Kessenich5611c6d2018-04-05 11:25:02 -0600484// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
485spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
486{
487 if (qualifier.isNonUniform()) {
488 builder.addExtension("SPV_EXT_descriptor_indexing");
489 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
490 return spv::DecorationNonUniformEXT;
491 } else
492 return spv::DecorationMax;
493}
494
Jeff Bolz36831c92018-09-05 10:11:41 -0500495spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
496{
497 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage) {
498 return spv::MemoryAccessMaskNone;
499 }
500 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
501 if (coherentFlags.volatil ||
502 coherentFlags.coherent ||
503 coherentFlags.devicecoherent ||
504 coherentFlags.queuefamilycoherent ||
505 coherentFlags.workgroupcoherent ||
506 coherentFlags.subgroupcoherent) {
507 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
508 spv::MemoryAccessMakePointerVisibleKHRMask;
509 }
510 if (coherentFlags.nonprivate) {
511 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
512 }
513 if (coherentFlags.volatil) {
514 mask = mask | spv::MemoryAccessVolatileMask;
515 }
516 if (mask != spv::MemoryAccessMaskNone) {
517 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
518 }
519 return mask;
520}
521
522spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
523{
524 if (!glslangIntermediate->usingVulkanMemoryModel()) {
525 return spv::ImageOperandsMaskNone;
526 }
527 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
528 if (coherentFlags.volatil ||
529 coherentFlags.coherent ||
530 coherentFlags.devicecoherent ||
531 coherentFlags.queuefamilycoherent ||
532 coherentFlags.workgroupcoherent ||
533 coherentFlags.subgroupcoherent) {
534 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
535 spv::ImageOperandsMakeTexelVisibleKHRMask;
536 }
537 if (coherentFlags.nonprivate) {
538 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
539 }
540 if (coherentFlags.volatil) {
541 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
542 }
543 if (mask != spv::ImageOperandsMaskNone) {
544 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
545 }
546 return mask;
547}
548
549spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
550{
551 spv::Builder::AccessChain::CoherentFlags flags;
552 flags.coherent = type.getQualifier().coherent;
553 flags.devicecoherent = type.getQualifier().devicecoherent;
554 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
555 // shared variables are implicitly workgroupcoherent in GLSL.
556 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
557 type.getQualifier().storage == glslang::EvqShared;
558 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600559 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500560 // *coherent variables are implicitly nonprivate in GLSL
561 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500562 flags.subgroupcoherent ||
563 flags.workgroupcoherent ||
564 flags.queuefamilycoherent ||
565 flags.devicecoherent ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600566 flags.coherent ||
567 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500568 flags.isImage = type.getBasicType() == glslang::EbtSampler;
569 return flags;
570}
571
572spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
573{
574 spv::Scope scope;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600575 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500576 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
577 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
578 } else if (coherentFlags.devicecoherent) {
579 scope = spv::ScopeDevice;
580 } else if (coherentFlags.queuefamilycoherent) {
581 scope = spv::ScopeQueueFamilyKHR;
582 } else if (coherentFlags.workgroupcoherent) {
583 scope = spv::ScopeWorkgroup;
584 } else if (coherentFlags.subgroupcoherent) {
585 scope = spv::ScopeSubgroup;
586 } else {
587 scope = spv::ScopeMax;
588 }
589 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
590 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
591 }
592 return scope;
593}
594
David Netoa901ffe2016-06-08 14:11:40 +0100595// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
596// associated capabilities when required. For some built-in variables, a capability
597// is generated only when using the variable in an executable instruction, but not when
598// just declaring a struct member variable with it. This is true for PointSize,
599// ClipDistance, and CullDistance.
600spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600601{
602 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700603 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600604 // Defer adding the capability until the built-in is actually used.
605 if (! memberDeclaration) {
606 switch (glslangIntermediate->getStage()) {
607 case EShLangGeometry:
608 builder.addCapability(spv::CapabilityGeometryPointSize);
609 break;
610 case EShLangTessControl:
611 case EShLangTessEvaluation:
612 builder.addCapability(spv::CapabilityTessellationPointSize);
613 break;
614 default:
615 break;
616 }
John Kessenich92187592016-02-01 13:45:25 -0700617 }
618 return spv::BuiltInPointSize;
619
John Kessenicha28f7a72019-08-06 07:00:58 -0600620 case glslang::EbvPosition: return spv::BuiltInPosition;
621 case glslang::EbvVertexId: return spv::BuiltInVertexId;
622 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
623 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
624 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
625
626 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
627 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
628 case glslang::EbvFace: return spv::BuiltInFrontFacing;
629 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
630
631#ifndef GLSLANG_WEB
John Kessenichebb50532016-05-16 19:22:05 -0600632 // These *Distance capabilities logically belong here, but if the member is declared and
633 // then never used, consumers of SPIR-V prefer the capability not be declared.
634 // They are now generated when used, rather than here when declared.
635 // Potentially, the specification should be more clear what the minimum
636 // use needed is to trigger the capability.
637 //
John Kessenich92187592016-02-01 13:45:25 -0700638 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100639 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800640 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700641 return spv::BuiltInClipDistance;
642
643 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100644 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800645 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700646 return spv::BuiltInCullDistance;
647
648 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600649 builder.addCapability(spv::CapabilityMultiViewport);
650 if (glslangIntermediate->getStage() == EShLangVertex ||
651 glslangIntermediate->getStage() == EShLangTessControl ||
652 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800653
John Kessenichba6a3c22017-09-13 13:22:50 -0600654 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
655 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800656 }
John Kessenich92187592016-02-01 13:45:25 -0700657 return spv::BuiltInViewportIndex;
658
John Kessenich5e801132016-02-15 11:09:46 -0700659 case glslang::EbvSampleId:
660 builder.addCapability(spv::CapabilitySampleRateShading);
661 return spv::BuiltInSampleId;
662
663 case glslang::EbvSamplePosition:
664 builder.addCapability(spv::CapabilitySampleRateShading);
665 return spv::BuiltInSamplePosition;
666
667 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700668 return spv::BuiltInSampleMask;
669
John Kessenich78a45572016-07-08 14:05:15 -0600670 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700671 if (glslangIntermediate->getStage() == EShLangMeshNV) {
672 return spv::BuiltInLayer;
673 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600674 builder.addCapability(spv::CapabilityGeometry);
675 if (glslangIntermediate->getStage() == EShLangVertex ||
676 glslangIntermediate->getStage() == EShLangTessControl ||
677 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800678
John Kessenichba6a3c22017-09-13 13:22:50 -0600679 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
680 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800681 }
John Kessenich78a45572016-07-08 14:05:15 -0600682 return spv::BuiltInLayer;
683
John Kessenichda581a22015-10-14 14:10:30 -0600684 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700685 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800686 builder.addCapability(spv::CapabilityDrawParameters);
687 return spv::BuiltInBaseVertex;
688
John Kessenichda581a22015-10-14 14:10:30 -0600689 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700690 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800691 builder.addCapability(spv::CapabilityDrawParameters);
692 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200693
John Kessenichda581a22015-10-14 14:10:30 -0600694 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700695 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800696 builder.addCapability(spv::CapabilityDrawParameters);
697 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200698
699 case glslang::EbvPrimitiveId:
700 if (glslangIntermediate->getStage() == EShLangFragment)
701 builder.addCapability(spv::CapabilityGeometry);
702 return spv::BuiltInPrimitiveId;
703
Rex Xu37cdcee2017-06-29 17:46:34 +0800704 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800705 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
706 builder.addCapability(spv::CapabilityStencilExportEXT);
707 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800708
John Kessenich140f3df2015-06-26 16:58:36 -0600709 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600710 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
711 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
712 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
713 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
John Kessenich140f3df2015-06-26 16:58:36 -0600714 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
715 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
716 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
717 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
718 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
719 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
720 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800721
Rex Xu574ab042016-04-14 16:53:07 +0800722 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800723 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800724 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
725 return spv::BuiltInSubgroupSize;
726
Rex Xu574ab042016-04-14 16:53:07 +0800727 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800728 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800729 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
730 return spv::BuiltInSubgroupLocalInvocationId;
731
Rex Xu574ab042016-04-14 16:53:07 +0800732 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800733 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
734 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600735 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800736
Rex Xu574ab042016-04-14 16:53:07 +0800737 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800738 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
739 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600740 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800741
Rex Xu574ab042016-04-14 16:53:07 +0800742 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800743 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
744 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600745 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800746
Rex Xu574ab042016-04-14 16:53:07 +0800747 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800748 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
749 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600750 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800751
Rex Xu574ab042016-04-14 16:53:07 +0800752 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800753 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
754 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600755 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800756
John Kessenich66011cb2018-03-06 16:12:04 -0700757 case glslang::EbvNumSubgroups:
758 builder.addCapability(spv::CapabilityGroupNonUniform);
759 return spv::BuiltInNumSubgroups;
760
761 case glslang::EbvSubgroupID:
762 builder.addCapability(spv::CapabilityGroupNonUniform);
763 return spv::BuiltInSubgroupId;
764
765 case glslang::EbvSubgroupSize2:
766 builder.addCapability(spv::CapabilityGroupNonUniform);
767 return spv::BuiltInSubgroupSize;
768
769 case glslang::EbvSubgroupInvocation2:
770 builder.addCapability(spv::CapabilityGroupNonUniform);
771 return spv::BuiltInSubgroupLocalInvocationId;
772
773 case glslang::EbvSubgroupEqMask2:
774 builder.addCapability(spv::CapabilityGroupNonUniform);
775 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
776 return spv::BuiltInSubgroupEqMask;
777
778 case glslang::EbvSubgroupGeMask2:
779 builder.addCapability(spv::CapabilityGroupNonUniform);
780 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
781 return spv::BuiltInSubgroupGeMask;
782
783 case glslang::EbvSubgroupGtMask2:
784 builder.addCapability(spv::CapabilityGroupNonUniform);
785 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
786 return spv::BuiltInSubgroupGtMask;
787
788 case glslang::EbvSubgroupLeMask2:
789 builder.addCapability(spv::CapabilityGroupNonUniform);
790 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
791 return spv::BuiltInSubgroupLeMask;
792
793 case glslang::EbvSubgroupLtMask2:
794 builder.addCapability(spv::CapabilityGroupNonUniform);
795 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
796 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600797
Rex Xu17ff3432016-10-14 17:41:45 +0800798 case glslang::EbvBaryCoordNoPersp:
799 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
800 return spv::BuiltInBaryCoordNoPerspAMD;
801
802 case glslang::EbvBaryCoordNoPerspCentroid:
803 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
804 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
805
806 case glslang::EbvBaryCoordNoPerspSample:
807 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
808 return spv::BuiltInBaryCoordNoPerspSampleAMD;
809
810 case glslang::EbvBaryCoordSmooth:
811 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
812 return spv::BuiltInBaryCoordSmoothAMD;
813
814 case glslang::EbvBaryCoordSmoothCentroid:
815 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
816 return spv::BuiltInBaryCoordSmoothCentroidAMD;
817
818 case glslang::EbvBaryCoordSmoothSample:
819 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
820 return spv::BuiltInBaryCoordSmoothSampleAMD;
821
822 case glslang::EbvBaryCoordPullModel:
823 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
824 return spv::BuiltInBaryCoordPullModelAMD;
chaoc771d89f2017-01-13 01:10:53 -0800825
John Kessenich6c8aaac2017-02-27 01:20:51 -0700826 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700827 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700828 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700829 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700830
831 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700832 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700833 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700834 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700835
Daniel Koch5154db52018-11-26 10:01:58 -0500836 case glslang::EbvFragSizeEXT:
837 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
838 builder.addCapability(spv::CapabilityFragmentDensityEXT);
839 return spv::BuiltInFragSizeEXT;
840
841 case glslang::EbvFragInvocationCountEXT:
842 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
843 builder.addCapability(spv::CapabilityFragmentDensityEXT);
844 return spv::BuiltInFragInvocationCountEXT;
845
chaoc771d89f2017-01-13 01:10:53 -0800846 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800847 if (!memberDeclaration) {
848 builder.addExtension(spv::E_SPV_NV_viewport_array2);
849 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
850 }
chaoc771d89f2017-01-13 01:10:53 -0800851 return spv::BuiltInViewportMaskNV;
852 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800853 if (!memberDeclaration) {
854 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
855 builder.addCapability(spv::CapabilityShaderStereoViewNV);
856 }
chaoc771d89f2017-01-13 01:10:53 -0800857 return spv::BuiltInSecondaryPositionNV;
858 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800859 if (!memberDeclaration) {
860 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
861 builder.addCapability(spv::CapabilityShaderStereoViewNV);
862 }
chaoc771d89f2017-01-13 01:10:53 -0800863 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800864 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800865 if (!memberDeclaration) {
866 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
867 builder.addCapability(spv::CapabilityPerViewAttributesNV);
868 }
chaocdf3956c2017-02-14 14:52:34 -0800869 return spv::BuiltInPositionPerViewNV;
870 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800871 if (!memberDeclaration) {
872 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
873 builder.addCapability(spv::CapabilityPerViewAttributesNV);
874 }
chaocdf3956c2017-02-14 14:52:34 -0800875 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700876 case glslang::EbvFragFullyCoveredNV:
877 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
878 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
879 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700880 case glslang::EbvFragmentSizeNV:
881 builder.addExtension(spv::E_SPV_NV_shading_rate);
882 builder.addCapability(spv::CapabilityShadingRateNV);
883 return spv::BuiltInFragmentSizeNV;
884 case glslang::EbvInvocationsPerPixelNV:
885 builder.addExtension(spv::E_SPV_NV_shading_rate);
886 builder.addCapability(spv::CapabilityShadingRateNV);
887 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700888
Daniel Koch593a4e02019-05-27 16:46:31 -0400889 // ray tracing
Chao Chenb50c02e2018-09-19 11:42:24 -0700890 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700891 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700892 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700893 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700894 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700895 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700896 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700897 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700898 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700899 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700900 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700901 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700902 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700903 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700904 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700905 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700906 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700907 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700908 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700909 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700910 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700911 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700912 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700913 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700914 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700915 return spv::BuiltInWorldToObjectNV;
916 case glslang::EbvIncomingRayFlagsNV:
917 return spv::BuiltInIncomingRayFlagsNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400918
919 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700920 case glslang::EbvBaryCoordNV:
921 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
922 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
923 return spv::BuiltInBaryCoordNV;
924 case glslang::EbvBaryCoordNoPerspNV:
925 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
926 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
927 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400928
929 // mesh shaders
930 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700931 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400932 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700933 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400934 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700935 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400936 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700937 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400938 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700939 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400940 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700941 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400942 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700943 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400944 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700945 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch2cb2f192019-06-04 08:43:32 -0400946
947 // sm builtins
948 case glslang::EbvWarpsPerSM:
949 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
950 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
951 return spv::BuiltInWarpsPerSMNV;
952 case glslang::EbvSMCount:
953 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
954 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
955 return spv::BuiltInSMCountNV;
956 case glslang::EbvWarpID:
957 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
958 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
959 return spv::BuiltInWarpIDNV;
960 case glslang::EbvSMID:
961 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
962 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
963 return spv::BuiltInSMIDNV;
John Kessenicha28f7a72019-08-06 07:00:58 -0600964#endif
965
Rex Xu3e783f92017-02-22 16:44:48 +0800966 default:
967 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600968 }
969}
970
Rex Xufc618912015-09-09 16:42:49 +0800971// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700972spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800973{
974 assert(type.getBasicType() == glslang::EbtSampler);
975
John Kessenich5d0fa972016-02-15 11:57:00 -0700976 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -0600977 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -0700978 case glslang::ElfRg32f:
979 case glslang::ElfRg16f:
980 case glslang::ElfR11fG11fB10f:
981 case glslang::ElfR16f:
982 case glslang::ElfRgba16:
983 case glslang::ElfRgb10A2:
984 case glslang::ElfRg16:
985 case glslang::ElfRg8:
986 case glslang::ElfR16:
987 case glslang::ElfR8:
988 case glslang::ElfRgba16Snorm:
989 case glslang::ElfRg16Snorm:
990 case glslang::ElfRg8Snorm:
991 case glslang::ElfR16Snorm:
992 case glslang::ElfR8Snorm:
993
994 case glslang::ElfRg32i:
995 case glslang::ElfRg16i:
996 case glslang::ElfRg8i:
997 case glslang::ElfR16i:
998 case glslang::ElfR8i:
999
1000 case glslang::ElfRgb10a2ui:
1001 case glslang::ElfRg32ui:
1002 case glslang::ElfRg16ui:
1003 case glslang::ElfRg8ui:
1004 case glslang::ElfR16ui:
1005 case glslang::ElfR8ui:
1006 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1007 break;
1008
1009 default:
1010 break;
1011 }
1012
1013 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001014 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001015 case glslang::ElfNone: return spv::ImageFormatUnknown;
1016 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1017 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1018 case glslang::ElfR32f: return spv::ImageFormatR32f;
1019 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1020 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1021 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1022 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1023 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1024 case glslang::ElfR16f: return spv::ImageFormatR16f;
1025 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1026 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1027 case glslang::ElfRg16: return spv::ImageFormatRg16;
1028 case glslang::ElfRg8: return spv::ImageFormatRg8;
1029 case glslang::ElfR16: return spv::ImageFormatR16;
1030 case glslang::ElfR8: return spv::ImageFormatR8;
1031 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1032 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1033 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1034 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1035 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1036 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1037 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1038 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1039 case glslang::ElfR32i: return spv::ImageFormatR32i;
1040 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1041 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1042 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1043 case glslang::ElfR16i: return spv::ImageFormatR16i;
1044 case glslang::ElfR8i: return spv::ImageFormatR8i;
1045 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1046 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1047 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1048 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1049 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1050 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1051 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1052 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1053 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1054 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001055 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001056 }
1057}
1058
John Kesseniche18fd202018-01-30 11:01:39 -07001059spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001060{
John Kesseniche18fd202018-01-30 11:01:39 -07001061 if (selectionNode.getFlatten())
1062 return spv::SelectionControlFlattenMask;
1063 if (selectionNode.getDontFlatten())
1064 return spv::SelectionControlDontFlattenMask;
1065 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001066}
1067
John Kesseniche18fd202018-01-30 11:01:39 -07001068spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001069{
John Kesseniche18fd202018-01-30 11:01:39 -07001070 if (switchNode.getFlatten())
1071 return spv::SelectionControlFlattenMask;
1072 if (switchNode.getDontFlatten())
1073 return spv::SelectionControlDontFlattenMask;
1074 return spv::SelectionControlMaskNone;
1075}
1076
John Kessenicha2858d92018-01-31 08:11:18 -07001077// return a non-0 dependency if the dependency argument must be set
1078spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001079 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001080{
1081 spv::LoopControlMask control = spv::LoopControlMaskNone;
1082
1083 if (loopNode.getDontUnroll())
1084 control = control | spv::LoopControlDontUnrollMask;
1085 if (loopNode.getUnroll())
1086 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001087 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001088 control = control | spv::LoopControlDependencyInfiniteMask;
1089 else if (loopNode.getLoopDependency() > 0) {
1090 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001091 operands.push_back((unsigned int)loopNode.getLoopDependency());
1092 }
1093 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1094 if (loopNode.getMinIterations() > 0) {
1095 control = control | spv::LoopControlMinIterationsMask;
1096 operands.push_back(loopNode.getMinIterations());
1097 }
1098 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1099 control = control | spv::LoopControlMaxIterationsMask;
1100 operands.push_back(loopNode.getMaxIterations());
1101 }
1102 if (loopNode.getIterationMultiple() > 1) {
1103 control = control | spv::LoopControlIterationMultipleMask;
1104 operands.push_back(loopNode.getIterationMultiple());
1105 }
1106 if (loopNode.getPeelCount() > 0) {
1107 control = control | spv::LoopControlPeelCountMask;
1108 operands.push_back(loopNode.getPeelCount());
1109 }
1110 if (loopNode.getPartialCount() > 0) {
1111 control = control | spv::LoopControlPartialCountMask;
1112 operands.push_back(loopNode.getPartialCount());
1113 }
John Kessenicha2858d92018-01-31 08:11:18 -07001114 }
John Kesseniche18fd202018-01-30 11:01:39 -07001115
1116 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001117}
1118
John Kessenicha5c5fb62017-05-05 05:09:58 -06001119// Translate glslang type to SPIR-V storage class.
1120spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1121{
1122 if (type.getQualifier().isPipeInput())
1123 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001124 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001125 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001126
1127 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001128 type.getQualifier().storage == glslang::EvqUniform) {
1129#ifndef GLSLANG_WEB
John Kessenichbed4e4f2017-09-08 02:38:07 -06001130 if (type.getBasicType() == glslang::EbtAtomicUint)
1131 return spv::StorageClassAtomicCounter;
John Kessenicha28f7a72019-08-06 07:00:58 -06001132#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001133 if (type.containsOpaque())
1134 return spv::StorageClassUniformConstant;
1135 }
1136
John Kessenicha28f7a72019-08-06 07:00:58 -06001137#ifndef GLSLANG_WEB
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001138 if (type.getQualifier().isUniformOrBuffer() &&
1139 type.getQualifier().layoutShaderRecordNV) {
1140 return spv::StorageClassShaderRecordBufferNV;
1141 }
1142#endif
1143
John Kessenichbed4e4f2017-09-08 02:38:07 -06001144 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001145 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001146 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001147 }
1148
1149 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha28f7a72019-08-06 07:00:58 -06001150#ifndef GLSLANG_WEB
John Kessenich7015bd62019-08-01 03:28:08 -06001151 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001152 return spv::StorageClassPushConstant;
John Kessenicha28f7a72019-08-06 07:00:58 -06001153#endif
John Kessenicha5c5fb62017-05-05 05:09:58 -06001154 if (type.getBasicType() == glslang::EbtBlock)
1155 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001156 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001157 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001158
1159 switch (type.getQualifier().storage) {
John Kessenichbed4e4f2017-09-08 02:38:07 -06001160 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1161 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1162 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenicha28f7a72019-08-06 07:00:58 -06001163#ifndef GLSLANG_WEB
1164 case glslang::EvqShared: return spv::StorageClassWorkgroup;
Ashwin Leleff1783d2018-10-22 16:41:44 -07001165 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1166 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1167 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1168 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1169 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001170#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001171 default:
1172 assert(0);
1173 break;
1174 }
1175
1176 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001177}
1178
John Kessenich5611c6d2018-04-05 11:25:02 -06001179// Add capabilities pertaining to how an array is indexed.
1180void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1181 const glslang::TType& indexType)
1182{
1183 if (indexType.getQualifier().isNonUniform()) {
1184 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001185 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001186 if (baseType.getBasicType() == glslang::EbtSampler) {
1187 if (baseType.getQualifier().hasAttachment())
1188 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001189 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001190 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001191 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001192 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1193 else if (baseType.isImage())
1194 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1195 else if (baseType.isTexture())
1196 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1197 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1198 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1199 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1200 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1201 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1202 }
1203 } else {
1204 // assume a dynamically uniform index
1205 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001206 if (baseType.getQualifier().hasAttachment()) {
1207 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001208 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001209 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001210 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001211 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001212 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001213 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001214 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001215 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001216 }
1217 }
1218}
1219
qining25262b32016-05-06 17:25:16 -04001220// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001221// descriptor set.
1222bool IsDescriptorResource(const glslang::TType& type)
1223{
John Kessenichf7497e22016-03-08 21:36:22 -07001224 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001225 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001226 return type.getQualifier().isUniformOrBuffer() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001227 ! type.getQualifier().isShaderRecordNV() &&
1228 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001229
1230 // non block...
1231 // basically samplerXXX/subpass/sampler/texture are all included
1232 // if they are the global-scope-class, not the function parameter
1233 // (or local, if they ever exist) class.
1234 if (type.getBasicType() == glslang::EbtSampler)
1235 return type.getQualifier().isUniformOrBuffer();
1236
1237 // None of the above.
1238 return false;
1239}
1240
John Kesseniche0b6cad2015-12-24 10:30:13 -07001241void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1242{
1243 if (child.layoutMatrix == glslang::ElmNone)
1244 child.layoutMatrix = parent.layoutMatrix;
1245
1246 if (parent.invariant)
1247 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001248 if (parent.flat)
1249 child.flat = true;
1250 if (parent.centroid)
1251 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001252#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001253 if (parent.nopersp)
1254 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001255 if (parent.explicitInterp)
1256 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001257 if (parent.perPrimitiveNV)
1258 child.perPrimitiveNV = true;
1259 if (parent.perViewNV)
1260 child.perViewNV = true;
1261 if (parent.perTaskNV)
1262 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001263 if (parent.patch)
1264 child.patch = true;
1265 if (parent.sample)
1266 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001267 if (parent.coherent)
1268 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001269 if (parent.devicecoherent)
1270 child.devicecoherent = true;
1271 if (parent.queuefamilycoherent)
1272 child.queuefamilycoherent = true;
1273 if (parent.workgroupcoherent)
1274 child.workgroupcoherent = true;
1275 if (parent.subgroupcoherent)
1276 child.subgroupcoherent = true;
1277 if (parent.nonprivate)
1278 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001279 if (parent.volatil)
1280 child.volatil = true;
1281 if (parent.restrict)
1282 child.restrict = true;
1283 if (parent.readonly)
1284 child.readonly = true;
1285 if (parent.writeonly)
1286 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001287#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001288}
1289
John Kessenichf2b7f332016-09-01 17:05:23 -06001290bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001291{
John Kessenich7b9fa252016-01-21 18:56:57 -07001292 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001293 // - struct members might inherit from a struct declaration
1294 // (note that non-block structs don't explicitly inherit,
1295 // only implicitly, meaning no decoration involved)
1296 // - affect decorations on the struct members
1297 // (note smooth does not, and expecting something like volatile
1298 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001299 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001300 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001301}
1302
John Kessenich140f3df2015-06-26 16:58:36 -06001303//
1304// Implement the TGlslangToSpvTraverser class.
1305//
1306
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001307TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001308 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1309 : TIntermTraverser(true, false, true),
1310 options(options),
1311 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001312 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001313 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001314 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich605afc72019-06-17 23:33:09 -06001315 glslangIntermediate(glslangIntermediate),
1316 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp())
John Kessenich140f3df2015-06-26 16:58:36 -06001317{
1318 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1319
1320 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001321 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1322 glslangIntermediate->getVersion());
1323
John Kessenich121853f2017-05-31 17:11:16 -06001324 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001325 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001326 builder.setSourceFile(glslangIntermediate->getSourceFile());
1327
1328 // Set the source shader's text. If for SPV version 1.0, include
1329 // a preamble in comments stating the OpModuleProcessed instructions.
1330 // Otherwise, emit those as actual instructions.
1331 std::string text;
1332 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1333 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001334 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001335 text.append("// OpModuleProcessed ");
1336 text.append(processes[p]);
1337 text.append("\n");
1338 } else
1339 builder.addModuleProcessed(processes[p]);
1340 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001341 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001342 text.append("#line 1\n");
1343 text.append(glslangIntermediate->getSourceText());
1344 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001345 // Pass name and text for all included files
1346 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1347 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1348 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001349 }
John Kessenich140f3df2015-06-26 16:58:36 -06001350 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001351
1352 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1353 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1354
1355 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1356 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
1357 builder.addExtension(spv::E_SPV_EXT_physical_storage_buffer);
1358 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1359 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001360 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001361 memoryModel = spv::MemoryModelVulkanKHR;
1362 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
Jeff Bolz36831c92018-09-05 10:11:41 -05001363 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
Jeff Bolz36831c92018-09-05 10:11:41 -05001364 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001365 builder.setMemoryModel(addressingModel, memoryModel);
1366
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001367 if (glslangIntermediate->usingVariablePointers()) {
1368 builder.addCapability(spv::CapabilityVariablePointers);
1369 }
1370
John Kessenicheee9d532016-09-19 18:09:30 -06001371 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1372 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001373
1374 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001375 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1376 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001377 builder.addSourceExtension(it->c_str());
1378
1379 // Add the top-level modes for this shader.
1380
John Kessenich92187592016-02-01 13:45:25 -07001381 if (glslangIntermediate->getXfbMode()) {
1382 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001383 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001384 }
John Kessenich140f3df2015-06-26 16:58:36 -06001385
1386 unsigned int mode;
1387 switch (glslangIntermediate->getStage()) {
1388 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001389 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001390 break;
1391
John Kessenicha28f7a72019-08-06 07:00:58 -06001392 case EShLangFragment:
1393 builder.addCapability(spv::CapabilityShader);
1394 if (glslangIntermediate->getPixelCenterInteger())
1395 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1396
1397 if (glslangIntermediate->getOriginUpperLeft())
1398 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1399 else
1400 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1401
1402 if (glslangIntermediate->getEarlyFragmentTests())
1403 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1404
1405 if (glslangIntermediate->getPostDepthCoverage()) {
1406 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1407 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1408 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1409 }
1410
1411 switch(glslangIntermediate->getDepth()) {
1412 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1413 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1414 default: mode = spv::ExecutionModeMax; break;
1415 }
1416 if (mode != spv::ExecutionModeMax)
1417 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1418
1419 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1420 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1421
1422 switch (glslangIntermediate->getInterlockOrdering()) {
1423 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT; break;
1424 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT; break;
1425 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT; break;
1426 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT; break;
1427 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT; break;
1428 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT; break;
1429 default: mode = spv::ExecutionModeMax; break;
1430 }
1431 if (mode != spv::ExecutionModeMax) {
1432 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1433 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1434 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1435 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1436 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1437 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1438 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1439 } else {
1440 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1441 }
1442 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1443 }
1444
1445 break;
1446
1447#ifndef GLSLANG_WEB
1448 case EShLangCompute:
1449 builder.addCapability(spv::CapabilityShader);
1450 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1451 glslangIntermediate->getLocalSize(1),
1452 glslangIntermediate->getLocalSize(2));
1453 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1454 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1455 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1456 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1457 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1458 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1459 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1460 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1461 }
1462 break;
steve-lunarge7412492017-03-23 11:56:07 -06001463 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001464 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001465 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001466
steve-lunarge7412492017-03-23 11:56:07 -06001467 glslang::TLayoutGeometry primitive;
1468
1469 if (glslangIntermediate->getStage() == EShLangTessControl) {
1470 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1471 primitive = glslangIntermediate->getOutputPrimitive();
1472 } else {
1473 primitive = glslangIntermediate->getInputPrimitive();
1474 }
1475
1476 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001477 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1478 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1479 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001480 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001481 }
John Kessenich4016e382016-07-15 11:53:56 -06001482 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001483 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1484
John Kesseniche6903322015-10-13 16:29:02 -06001485 switch (glslangIntermediate->getVertexSpacing()) {
1486 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1487 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1488 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001489 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001490 }
John Kessenich4016e382016-07-15 11:53:56 -06001491 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001492 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1493
1494 switch (glslangIntermediate->getVertexOrder()) {
1495 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1496 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001497 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001498 }
John Kessenich4016e382016-07-15 11:53:56 -06001499 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001500 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1501
1502 if (glslangIntermediate->getPointMode())
1503 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001504 break;
1505
1506 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001507 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001508 switch (glslangIntermediate->getInputPrimitive()) {
1509 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1510 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1511 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001512 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001513 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001514 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001515 }
John Kessenich4016e382016-07-15 11:53:56 -06001516 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001517 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001518
John Kessenich140f3df2015-06-26 16:58:36 -06001519 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1520
1521 switch (glslangIntermediate->getOutputPrimitive()) {
1522 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1523 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1524 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001525 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001526 }
John Kessenich4016e382016-07-15 11:53:56 -06001527 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001528 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1529 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1530 break;
1531
Chao Chenb50c02e2018-09-19 11:42:24 -07001532 case EShLangRayGenNV:
1533 case EShLangIntersectNV:
1534 case EShLangAnyHitNV:
1535 case EShLangClosestHitNV:
1536 case EShLangMissNV:
1537 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001538 builder.addCapability(spv::CapabilityRayTracingNV);
1539 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001540 break;
Chao Chen3c366992018-09-19 11:41:59 -07001541 case EShLangTaskNV:
1542 case EShLangMeshNV:
1543 builder.addCapability(spv::CapabilityMeshShadingNV);
1544 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1545 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1546 glslangIntermediate->getLocalSize(1),
1547 glslangIntermediate->getLocalSize(2));
1548 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1549 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1550 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1551
1552 switch (glslangIntermediate->getOutputPrimitive()) {
1553 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1554 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1555 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1556 default: mode = spv::ExecutionModeMax; break;
1557 }
1558 if (mode != spv::ExecutionModeMax)
1559 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1560 }
1561 break;
1562#endif
1563
John Kessenich140f3df2015-06-26 16:58:36 -06001564 default:
1565 break;
1566 }
John Kessenich140f3df2015-06-26 16:58:36 -06001567}
1568
John Kessenichfca82622016-11-26 13:23:20 -07001569// Finish creating SPV, after the traversal is complete.
1570void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001571{
John Kessenichf04c51b2018-08-03 15:56:12 -06001572 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001573 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001574 builder.setBuildPoint(shaderEntry->getLastBlock());
1575 builder.leaveFunction();
1576 }
1577
John Kessenich7ba63412015-12-20 17:37:07 -07001578 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001579 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1580 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001581
John Kessenich23d27752019-07-28 02:12:10 -06001582#ifndef GLSLANG_WEB
John Kessenichf04c51b2018-08-03 15:56:12 -06001583 // Add capabilities, extensions, remove unneeded decorations, etc.,
1584 // based on the resulting SPIR-V.
1585 builder.postProcess();
John Kessenich23d27752019-07-28 02:12:10 -06001586#endif
John Kessenich7ba63412015-12-20 17:37:07 -07001587}
1588
John Kessenichfca82622016-11-26 13:23:20 -07001589// Write the SPV into 'out'.
1590void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001591{
John Kessenichfca82622016-11-26 13:23:20 -07001592 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001593}
1594
1595//
1596// Implement the traversal functions.
1597//
1598// Return true from interior nodes to have the external traversal
1599// continue on to children. Return false if children were
1600// already processed.
1601//
1602
1603//
qining25262b32016-05-06 17:25:16 -04001604// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001605// - uniform/input reads
1606// - output writes
1607// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1608// - something simple that degenerates into the last bullet
1609//
1610void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1611{
qining75d1d802016-04-06 14:42:01 -04001612 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1613 if (symbol->getType().getQualifier().isSpecConstant())
1614 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1615
John Kessenich140f3df2015-06-26 16:58:36 -06001616 // getSymbolId() will set up all the IO decorations on the first call.
1617 // Formal function parameters were mapped during makeFunctions().
1618 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001619
John Kessenich7ba63412015-12-20 17:37:07 -07001620 if (builder.isPointer(id)) {
John Kessenich9c14f772019-06-17 08:38:35 -06001621 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
John Kessenich7c7731e2019-01-04 16:47:06 +07001622 // Consider adding to the OpEntryPoint interface list.
1623 // Only looking at structures if they have at least one member.
1624 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1625 spv::StorageClass sc = builder.getStorageClass(id);
1626 // Before SPIR-V 1.4, we only want to include Input and Output.
1627 // Starting with SPIR-V 1.4, we want all globals.
1628 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1629 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001630 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001631 }
John Kessenich5f77d862017-09-19 11:09:59 -06001632 }
John Kessenich9c14f772019-06-17 08:38:35 -06001633
1634 // If the SPIR-V type is required to be different than the AST type,
1635 // translate now from the SPIR-V type to the AST type, for the consuming
1636 // operation.
1637 // Note this turns it from an l-value to an r-value.
1638 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1639 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1640 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001641 }
1642
1643 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001644 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001645 // Prepare to generate code for the access
1646
1647 // L-value chains will be computed left to right. We're on the symbol now,
1648 // which is the left-most part of the access chain, so now is "clear" time,
1649 // followed by setting the base.
1650 builder.clearAccessChain();
1651
1652 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001653 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001654 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001655 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001656 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001657 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001658 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001659 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001660 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1661 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001662 builder.setAccessChainRValue(id);
1663 else
1664 builder.setAccessChainLValue(id);
1665 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001666
1667 // Process linkage-only nodes for any special additional interface work.
1668 if (linkageOnly) {
1669 if (glslangIntermediate->getHlslFunctionality1()) {
1670 // Map implicit counter buffers to their originating buffers, which should have been
1671 // seen by now, given earlier pruning of unused counters, and preservation of order
1672 // of declaration.
1673 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1674 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1675 // Save possible originating buffers for counter buffers, keyed by
1676 // making the potential counter-buffer name.
1677 std::string keyName = symbol->getName().c_str();
1678 keyName = glslangIntermediate->addCounterBufferName(keyName);
1679 counterOriginator[keyName] = symbol;
1680 } else {
1681 // Handle a counter buffer, by finding the saved originating buffer.
1682 std::string keyName = symbol->getName().c_str();
1683 auto it = counterOriginator.find(keyName);
1684 if (it != counterOriginator.end()) {
1685 id = getSymbolId(it->second);
1686 if (id != spv::NoResult) {
1687 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001688 if (counterId != spv::NoResult) {
1689 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001690 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001691 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001692 }
1693 }
1694 }
1695 }
1696 }
1697 }
John Kessenich140f3df2015-06-26 16:58:36 -06001698}
1699
1700bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1701{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001702 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001703
qining40887662016-04-03 22:20:42 -04001704 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1705 if (node->getType().getQualifier().isSpecConstant())
1706 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1707
John Kessenich140f3df2015-06-26 16:58:36 -06001708 // First, handle special cases
1709 switch (node->getOp()) {
1710 case glslang::EOpAssign:
1711 case glslang::EOpAddAssign:
1712 case glslang::EOpSubAssign:
1713 case glslang::EOpMulAssign:
1714 case glslang::EOpVectorTimesMatrixAssign:
1715 case glslang::EOpVectorTimesScalarAssign:
1716 case glslang::EOpMatrixTimesScalarAssign:
1717 case glslang::EOpMatrixTimesMatrixAssign:
1718 case glslang::EOpDivAssign:
1719 case glslang::EOpModAssign:
1720 case glslang::EOpAndAssign:
1721 case glslang::EOpInclusiveOrAssign:
1722 case glslang::EOpExclusiveOrAssign:
1723 case glslang::EOpLeftShiftAssign:
1724 case glslang::EOpRightShiftAssign:
1725 // A bin-op assign "a += b" means the same thing as "a = a + b"
1726 // where a is evaluated before b. For a simple assignment, GLSL
1727 // says to evaluate the left before the right. So, always, left
1728 // node then right node.
1729 {
1730 // get the left l-value, save it away
1731 builder.clearAccessChain();
1732 node->getLeft()->traverse(this);
1733 spv::Builder::AccessChain lValue = builder.getAccessChain();
1734
1735 // evaluate the right
1736 builder.clearAccessChain();
1737 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001738 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001739
1740 if (node->getOp() != glslang::EOpAssign) {
1741 // the left is also an r-value
1742 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001743 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001744
1745 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001746 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001747 TranslateNoContractionDecoration(node->getType().getQualifier()),
1748 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001749 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001750 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1751 node->getType().getBasicType());
1752
1753 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001754 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001755 }
1756
1757 // store the result
1758 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001759 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001760
1761 // assignments are expressions having an rValue after they are evaluated...
1762 builder.clearAccessChain();
1763 builder.setAccessChainRValue(rValue);
1764 }
1765 return false;
1766 case glslang::EOpIndexDirect:
1767 case glslang::EOpIndexDirectStruct:
1768 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001769 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001770 // Get the left part of the access chain.
1771 node->getLeft()->traverse(this);
1772
1773 // Add the next element in the chain
1774
David Netoa901ffe2016-06-08 14:11:40 +01001775 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001776 if (! node->getLeft()->getType().isArray() &&
1777 node->getLeft()->getType().isVector() &&
1778 node->getOp() == glslang::EOpIndexDirect) {
1779 // This is essentially a hard-coded vector swizzle of size 1,
1780 // so short circuit the access-chain stuff with a swizzle.
1781 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001782 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001783 int dummySize;
1784 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1785 TranslateCoherent(node->getLeft()->getType()),
1786 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001787 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001788
1789 // Load through a block reference is performed with a dot operator that
1790 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1791 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001792 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001793 !node->getLeft()->getType().isArray() &&
1794 node->getOp() == glslang::EOpIndexDirectStruct)
1795 {
1796 spv::Id left = accessChainLoad(node->getLeft()->getType());
1797 builder.clearAccessChain();
1798 builder.setAccessChainLValue(left);
1799 }
1800
David Netoa901ffe2016-06-08 14:11:40 +01001801 int spvIndex = glslangIndex;
1802 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1803 node->getOp() == glslang::EOpIndexDirectStruct)
1804 {
1805 // This may be, e.g., an anonymous block-member selection, which generally need
1806 // index remapping due to hidden members in anonymous blocks.
1807 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1808 assert(remapper.size() > 0);
1809 spvIndex = remapper[glslangIndex];
1810 }
John Kessenichebb50532016-05-16 19:22:05 -06001811
David Netoa901ffe2016-06-08 14:11:40 +01001812 // normal case for indexing array or structure or block
Jeff Bolz7895e472019-03-06 13:34:10 -06001813 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001814
1815 // Add capabilities here for accessing PointSize and clip/cull distance.
1816 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001817 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001818 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001819 }
1820 }
1821 return false;
1822 case glslang::EOpIndexIndirect:
1823 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001824 // Array, matrix, or vector indirection with variable index.
1825 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001826 // matrices are arrays of vectors, so will also work for a matrix.
1827 // Will use the access chain's 'component' for variable index into a vector.
1828
1829 // This adapter is building access chains left to right.
1830 // Set up the access chain to the left.
1831 node->getLeft()->traverse(this);
1832
1833 // save it so that computing the right side doesn't trash it
1834 spv::Builder::AccessChain partial = builder.getAccessChain();
1835
1836 // compute the next index in the chain
1837 builder.clearAccessChain();
1838 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001839 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001840
John Kessenich5611c6d2018-04-05 11:25:02 -06001841 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1842
John Kessenich140f3df2015-06-26 16:58:36 -06001843 // restore the saved access chain
1844 builder.setAccessChain(partial);
1845
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001846 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1847 int dummySize;
1848 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1849 TranslateCoherent(node->getLeft()->getType()),
1850 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1851 } else
Jeff Bolz7895e472019-03-06 13:34:10 -06001852 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001853 }
1854 return false;
1855 case glslang::EOpVectorSwizzle:
1856 {
1857 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001858 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001859 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001860 int dummySize;
1861 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1862 TranslateCoherent(node->getLeft()->getType()),
1863 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001864 }
1865 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001866 case glslang::EOpMatrixSwizzle:
1867 logger->missingFunctionality("matrix swizzle");
1868 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001869 case glslang::EOpLogicalOr:
1870 case glslang::EOpLogicalAnd:
1871 {
1872
1873 // These may require short circuiting, but can sometimes be done as straight
1874 // binary operations. The right operand must be short circuited if it has
1875 // side effects, and should probably be if it is complex.
1876 if (isTrivial(node->getRight()->getAsTyped()))
1877 break; // handle below as a normal binary operation
1878 // otherwise, we need to do dynamic short circuiting on the right operand
1879 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1880 builder.clearAccessChain();
1881 builder.setAccessChainRValue(result);
1882 }
1883 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001884 default:
1885 break;
1886 }
1887
1888 // Assume generic binary op...
1889
John Kessenich32cfd492016-02-02 12:37:46 -07001890 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001891 builder.clearAccessChain();
1892 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001893 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001894
John Kessenich32cfd492016-02-02 12:37:46 -07001895 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001896 builder.clearAccessChain();
1897 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001898 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001899
John Kessenich32cfd492016-02-02 12:37:46 -07001900 // get result
John Kessenichead86222018-03-28 18:01:20 -06001901 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001902 TranslateNoContractionDecoration(node->getType().getQualifier()),
1903 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001904 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001905 convertGlslangToSpvType(node->getType()), left, right,
1906 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001907
John Kessenich50e57562015-12-21 21:21:11 -07001908 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001909 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001910 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001911 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001912 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001913 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001914 return false;
1915 }
John Kessenich140f3df2015-06-26 16:58:36 -06001916}
1917
John Kessenich9c14f772019-06-17 08:38:35 -06001918// Figure out what, if any, type changes are needed when accessing a specific built-in.
1919// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
1920// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
1921std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(spv::BuiltIn builtIn,
1922 const glslang::TType& glslangType)
1923{
1924 switch(builtIn)
1925 {
1926 case spv::BuiltInSubgroupEqMask:
1927 case spv::BuiltInSubgroupGeMask:
1928 case spv::BuiltInSubgroupGtMask:
1929 case spv::BuiltInSubgroupLeMask:
1930 case spv::BuiltInSubgroupLtMask: {
1931 // these require changing a 64-bit scaler -> a vector of 32-bit components
1932 if (glslangType.isVector())
1933 break;
1934 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
1935 builder.makeUintType(64));
1936 return ret;
1937 }
1938 default:
1939 break;
1940 }
1941
1942 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
1943 return ret;
1944}
1945
1946// For an object previously identified (see getForcedType() and forceType)
1947// as needing type translations, do the translation needed for a load, turning
1948// an L-value into in R-value.
1949spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
1950{
1951 const auto forceIt = forceType.find(object);
1952 if (forceIt == forceType.end())
1953 return object;
1954
1955 spv::Id desiredTypeId = forceIt->second;
1956 spv::Id objectTypeId = builder.getTypeId(object);
1957 assert(builder.isPointerType(objectTypeId));
1958 objectTypeId = builder.getContainedTypeId(objectTypeId);
1959 if (builder.isVectorType(objectTypeId) &&
1960 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
1961 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
1962 // handle 32-bit v.xy* -> 64-bit
1963 builder.clearAccessChain();
1964 builder.setAccessChainLValue(object);
1965 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
1966 std::vector<spv::Id> components;
1967 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
1968 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
1969
1970 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
1971 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
1972 builder.createCompositeConstruct(vecType, components));
1973 } else {
1974 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
1975 }
1976 } else {
1977 logger->missingFunctionality("forcing non 32-bit vector type");
1978 }
1979
1980 return object;
1981}
1982
John Kessenich140f3df2015-06-26 16:58:36 -06001983bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1984{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001985 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001986
qining40887662016-04-03 22:20:42 -04001987 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1988 if (node->getType().getQualifier().isSpecConstant())
1989 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1990
John Kessenichfc51d282015-08-19 13:34:18 -06001991 spv::Id result = spv::NoResult;
1992
1993 // try texturing first
1994 result = createImageTextureFunctionCall(node);
1995 if (result != spv::NoResult) {
1996 builder.clearAccessChain();
1997 builder.setAccessChainRValue(result);
1998
1999 return false; // done with this node
2000 }
2001
2002 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002003
2004 if (node->getOp() == glslang::EOpArrayLength) {
2005 // Quite special; won't want to evaluate the operand.
2006
John Kessenich5611c6d2018-04-05 11:25:02 -06002007 // Currently, the front-end does not allow .length() on an array until it is sized,
2008 // except for the last block membeor of an SSBO.
2009 // TODO: If this changes, link-time sized arrays might show up here, and need their
2010 // size extracted.
2011
John Kessenichc9a80832015-09-12 12:17:44 -06002012 // Normal .length() would have been constant folded by the front-end.
2013 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002014 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002015
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002016 spv::Id length;
2017 if (node->getOperand()->getType().isCoopMat()) {
2018 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2019
2020 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2021 assert(builder.isCooperativeMatrixType(typeId));
2022
2023 length = builder.createCooperativeMatrixLength(typeId);
2024 } else {
2025 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2026 block->traverse(this);
2027 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
2028 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2029 }
John Kessenichc9a80832015-09-12 12:17:44 -06002030
John Kessenich8c869672018-11-28 07:01:37 -07002031 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2032 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2033 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002034 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2035 if (builder.isInSpecConstCodeGenMode()) {
2036 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2037 } else {
2038 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2039 }
2040 }
John Kessenich8c869672018-11-28 07:01:37 -07002041
John Kessenichc9a80832015-09-12 12:17:44 -06002042 builder.clearAccessChain();
2043 builder.setAccessChainRValue(length);
2044
2045 return false;
2046 }
2047
John Kessenichfc51d282015-08-19 13:34:18 -06002048 // Start by evaluating the operand
2049
John Kessenich8c8505c2016-07-26 12:50:38 -06002050 // Does it need a swizzle inversion? If so, evaluation is inverted;
2051 // operate first on the swizzle base, then apply the swizzle.
2052 spv::Id invertedType = spv::NoType;
2053 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
2054 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2055 invertedType = getInvertedSwizzleType(*node->getOperand());
2056
John Kessenich140f3df2015-06-26 16:58:36 -06002057 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002058 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002059 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002060 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002061 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002062 operandNode = node->getOperand();
2063
2064 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002065
Rex Xufc618912015-09-09 16:42:49 +08002066 spv::Id operand = spv::NoResult;
2067
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002068 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2069
Rex Xufc618912015-09-09 16:42:49 +08002070 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2071 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002072 node->getOp() == glslang::EOpAtomicCounter ||
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002073 node->getOp() == glslang::EOpInterpolateAtCentroid) {
Rex Xufc618912015-09-09 16:42:49 +08002074 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002075 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2076 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2077 } else
John Kessenich32cfd492016-02-02 12:37:46 -07002078 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002079
John Kessenichead86222018-03-28 18:01:20 -06002080 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002081 TranslateNoContractionDecoration(node->getType().getQualifier()),
2082 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002083
2084 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002085 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06002086 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002087
2088 // if not, then possibly an operation
2089 if (! result)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002090 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002091
2092 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002093 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002094 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002095 builder.addDecoration(result, decorations.nonUniform);
2096 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002097
John Kessenich140f3df2015-06-26 16:58:36 -06002098 builder.clearAccessChain();
2099 builder.setAccessChainRValue(result);
2100
2101 return false; // done with this node
2102 }
2103
2104 // it must be a special case, check...
2105 switch (node->getOp()) {
2106 case glslang::EOpPostIncrement:
2107 case glslang::EOpPostDecrement:
2108 case glslang::EOpPreIncrement:
2109 case glslang::EOpPreDecrement:
2110 {
2111 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002112 spv::Id one = 0;
2113 if (node->getBasicType() == glslang::EbtFloat)
2114 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002115#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002116 else if (node->getBasicType() == glslang::EbtDouble)
2117 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002118 else if (node->getBasicType() == glslang::EbtFloat16)
2119 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002120 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2121 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002122 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2123 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002124 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2125 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002126#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002127 else
2128 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002129 glslang::TOperator op;
2130 if (node->getOp() == glslang::EOpPreIncrement ||
2131 node->getOp() == glslang::EOpPostIncrement)
2132 op = glslang::EOpAdd;
2133 else
2134 op = glslang::EOpSub;
2135
John Kessenichead86222018-03-28 18:01:20 -06002136 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002137 convertGlslangToSpvType(node->getType()), operand, one,
2138 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002139 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002140
2141 // The result of operation is always stored, but conditionally the
2142 // consumed result. The consumed result is always an r-value.
2143 builder.accessChainStore(result);
2144 builder.clearAccessChain();
2145 if (node->getOp() == glslang::EOpPreIncrement ||
2146 node->getOp() == glslang::EOpPreDecrement)
2147 builder.setAccessChainRValue(result);
2148 else
2149 builder.setAccessChainRValue(operand);
2150 }
2151
2152 return false;
2153
2154 case glslang::EOpEmitStreamVertex:
2155 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2156 return false;
2157 case glslang::EOpEndStreamPrimitive:
2158 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2159 return false;
2160
2161 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002162 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002163 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002164 }
John Kessenich140f3df2015-06-26 16:58:36 -06002165}
2166
Jeff Bolz53134492019-06-25 13:31:10 -05002167// Construct a composite object, recursively copying members if their types don't match
2168spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2169{
2170 for (int c = 0; c < (int)constituents.size(); ++c) {
2171 spv::Id& constituent = constituents[c];
2172 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2173 spv::Id rType = builder.getTypeId(constituent);
2174 if (lType != rType) {
2175 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2176 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2177 } else if (builder.isStructType(rType)) {
2178 std::vector<spv::Id> rTypeConstituents;
2179 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2180 for (int i = 0; i < numrTypeConstituents; ++i) {
2181 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, builder.getContainedTypeId(rType, i), i));
2182 }
2183 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2184 } else {
2185 assert(builder.isArrayType(rType));
2186 std::vector<spv::Id> rTypeConstituents;
2187 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2188
2189 spv::Id elementRType = builder.getContainedTypeId(rType);
2190 for (int i = 0; i < numrTypeConstituents; ++i) {
2191 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2192 }
2193 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2194 }
2195 }
2196 }
2197 return builder.createCompositeConstruct(resultTypeId, constituents);
2198}
2199
John Kessenich140f3df2015-06-26 16:58:36 -06002200bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2201{
qining27e04a02016-04-14 16:40:20 -04002202 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2203 if (node->getType().getQualifier().isSpecConstant())
2204 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2205
John Kessenichfc51d282015-08-19 13:34:18 -06002206 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002207 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2208 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002209
2210 // try texturing
2211 result = createImageTextureFunctionCall(node);
2212 if (result != spv::NoResult) {
2213 builder.clearAccessChain();
2214 builder.setAccessChainRValue(result);
2215
2216 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002217 }
2218#ifndef GLSLANG_WEB
2219 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002220 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002221 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002222 // "imageStore" is a special case, which has no result
2223 return false;
2224 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002225#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002226
John Kessenich140f3df2015-06-26 16:58:36 -06002227 glslang::TOperator binOp = glslang::EOpNull;
2228 bool reduceComparison = true;
2229 bool isMatrix = false;
2230 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002231 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002232
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002233 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2234
John Kessenich140f3df2015-06-26 16:58:36 -06002235 assert(node->getOp());
2236
John Kessenichf6640762016-08-01 19:44:00 -06002237 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002238
2239 switch (node->getOp()) {
2240 case glslang::EOpSequence:
2241 {
2242 if (preVisit)
2243 ++sequenceDepth;
2244 else
2245 --sequenceDepth;
2246
2247 if (sequenceDepth == 1) {
2248 // If this is the parent node of all the functions, we want to see them
2249 // early, so all call points have actual SPIR-V functions to reference.
2250 // In all cases, still let the traverser visit the children for us.
2251 makeFunctions(node->getAsAggregate()->getSequence());
2252
John Kessenich6fccb3c2016-09-19 16:01:41 -06002253 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002254 // anything else gets there, so visit out of order, doing them all now.
2255 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2256
John Kessenich6a60c2f2016-12-08 21:01:59 -07002257 // 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 -06002258 // so do them manually.
2259 visitFunctions(node->getAsAggregate()->getSequence());
2260
2261 return false;
2262 }
2263
2264 return true;
2265 }
2266 case glslang::EOpLinkerObjects:
2267 {
2268 if (visit == glslang::EvPreVisit)
2269 linkageOnly = true;
2270 else
2271 linkageOnly = false;
2272
2273 return true;
2274 }
2275 case glslang::EOpComma:
2276 {
2277 // processing from left to right naturally leaves the right-most
2278 // lying around in the access chain
2279 glslang::TIntermSequence& glslangOperands = node->getSequence();
2280 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2281 glslangOperands[i]->traverse(this);
2282
2283 return false;
2284 }
2285 case glslang::EOpFunction:
2286 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002287 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002288 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002289 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002290 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002291 } else {
2292 handleFunctionEntry(node);
2293 }
2294 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002295 if (inEntryPoint)
2296 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002297 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002298 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002299 }
2300
2301 return true;
2302 case glslang::EOpParameters:
2303 // Parameters will have been consumed by EOpFunction processing, but not
2304 // the body, so we still visited the function node's children, making this
2305 // child redundant.
2306 return false;
2307 case glslang::EOpFunctionCall:
2308 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002309 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002310 if (node->isUserDefined())
2311 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002312 // assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
John Kessenich6c292d32016-02-15 20:58:50 -07002313 if (result) {
2314 builder.clearAccessChain();
2315 builder.setAccessChainRValue(result);
2316 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002317 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002318
2319 return false;
2320 }
2321 case glslang::EOpConstructMat2x2:
2322 case glslang::EOpConstructMat2x3:
2323 case glslang::EOpConstructMat2x4:
2324 case glslang::EOpConstructMat3x2:
2325 case glslang::EOpConstructMat3x3:
2326 case glslang::EOpConstructMat3x4:
2327 case glslang::EOpConstructMat4x2:
2328 case glslang::EOpConstructMat4x3:
2329 case glslang::EOpConstructMat4x4:
2330 case glslang::EOpConstructDMat2x2:
2331 case glslang::EOpConstructDMat2x3:
2332 case glslang::EOpConstructDMat2x4:
2333 case glslang::EOpConstructDMat3x2:
2334 case glslang::EOpConstructDMat3x3:
2335 case glslang::EOpConstructDMat3x4:
2336 case glslang::EOpConstructDMat4x2:
2337 case glslang::EOpConstructDMat4x3:
2338 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002339 case glslang::EOpConstructIMat2x2:
2340 case glslang::EOpConstructIMat2x3:
2341 case glslang::EOpConstructIMat2x4:
2342 case glslang::EOpConstructIMat3x2:
2343 case glslang::EOpConstructIMat3x3:
2344 case glslang::EOpConstructIMat3x4:
2345 case glslang::EOpConstructIMat4x2:
2346 case glslang::EOpConstructIMat4x3:
2347 case glslang::EOpConstructIMat4x4:
2348 case glslang::EOpConstructUMat2x2:
2349 case glslang::EOpConstructUMat2x3:
2350 case glslang::EOpConstructUMat2x4:
2351 case glslang::EOpConstructUMat3x2:
2352 case glslang::EOpConstructUMat3x3:
2353 case glslang::EOpConstructUMat3x4:
2354 case glslang::EOpConstructUMat4x2:
2355 case glslang::EOpConstructUMat4x3:
2356 case glslang::EOpConstructUMat4x4:
2357 case glslang::EOpConstructBMat2x2:
2358 case glslang::EOpConstructBMat2x3:
2359 case glslang::EOpConstructBMat2x4:
2360 case glslang::EOpConstructBMat3x2:
2361 case glslang::EOpConstructBMat3x3:
2362 case glslang::EOpConstructBMat3x4:
2363 case glslang::EOpConstructBMat4x2:
2364 case glslang::EOpConstructBMat4x3:
2365 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002366 case glslang::EOpConstructF16Mat2x2:
2367 case glslang::EOpConstructF16Mat2x3:
2368 case glslang::EOpConstructF16Mat2x4:
2369 case glslang::EOpConstructF16Mat3x2:
2370 case glslang::EOpConstructF16Mat3x3:
2371 case glslang::EOpConstructF16Mat3x4:
2372 case glslang::EOpConstructF16Mat4x2:
2373 case glslang::EOpConstructF16Mat4x3:
2374 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002375 isMatrix = true;
2376 // fall through
2377 case glslang::EOpConstructFloat:
2378 case glslang::EOpConstructVec2:
2379 case glslang::EOpConstructVec3:
2380 case glslang::EOpConstructVec4:
2381 case glslang::EOpConstructDouble:
2382 case glslang::EOpConstructDVec2:
2383 case glslang::EOpConstructDVec3:
2384 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002385 case glslang::EOpConstructFloat16:
2386 case glslang::EOpConstructF16Vec2:
2387 case glslang::EOpConstructF16Vec3:
2388 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002389 case glslang::EOpConstructBool:
2390 case glslang::EOpConstructBVec2:
2391 case glslang::EOpConstructBVec3:
2392 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002393 case glslang::EOpConstructInt8:
2394 case glslang::EOpConstructI8Vec2:
2395 case glslang::EOpConstructI8Vec3:
2396 case glslang::EOpConstructI8Vec4:
2397 case glslang::EOpConstructUint8:
2398 case glslang::EOpConstructU8Vec2:
2399 case glslang::EOpConstructU8Vec3:
2400 case glslang::EOpConstructU8Vec4:
2401 case glslang::EOpConstructInt16:
2402 case glslang::EOpConstructI16Vec2:
2403 case glslang::EOpConstructI16Vec3:
2404 case glslang::EOpConstructI16Vec4:
2405 case glslang::EOpConstructUint16:
2406 case glslang::EOpConstructU16Vec2:
2407 case glslang::EOpConstructU16Vec3:
2408 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002409 case glslang::EOpConstructInt:
2410 case glslang::EOpConstructIVec2:
2411 case glslang::EOpConstructIVec3:
2412 case glslang::EOpConstructIVec4:
2413 case glslang::EOpConstructUint:
2414 case glslang::EOpConstructUVec2:
2415 case glslang::EOpConstructUVec3:
2416 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002417 case glslang::EOpConstructInt64:
2418 case glslang::EOpConstructI64Vec2:
2419 case glslang::EOpConstructI64Vec3:
2420 case glslang::EOpConstructI64Vec4:
2421 case glslang::EOpConstructUint64:
2422 case glslang::EOpConstructU64Vec2:
2423 case glslang::EOpConstructU64Vec3:
2424 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002425 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002426 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002427 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002428 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002429 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002430 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002431 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002432 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002433 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002434 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002435 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002436 else if (node->getOp() == glslang::EOpConstructStruct ||
2437 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2438 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002439 std::vector<spv::Id> constituents;
2440 for (int c = 0; c < (int)arguments.size(); ++c)
2441 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002442 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002443 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002444 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002445 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002446 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002447
2448 builder.clearAccessChain();
2449 builder.setAccessChainRValue(constructed);
2450
2451 return false;
2452 }
2453
2454 // These six are component-wise compares with component-wise results.
2455 // Forward on to createBinaryOperation(), requesting a vector result.
2456 case glslang::EOpLessThan:
2457 case glslang::EOpGreaterThan:
2458 case glslang::EOpLessThanEqual:
2459 case glslang::EOpGreaterThanEqual:
2460 case glslang::EOpVectorEqual:
2461 case glslang::EOpVectorNotEqual:
2462 {
2463 // Map the operation to a binary
2464 binOp = node->getOp();
2465 reduceComparison = false;
2466 switch (node->getOp()) {
2467 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2468 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2469 default: binOp = node->getOp(); break;
2470 }
2471
2472 break;
2473 }
2474 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002475 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002476 binOp = glslang::EOpMul;
2477 break;
2478 case glslang::EOpOuterProduct:
2479 // two vectors multiplied to make a matrix
2480 binOp = glslang::EOpOuterProduct;
2481 break;
2482 case glslang::EOpDot:
2483 {
qining25262b32016-05-06 17:25:16 -04002484 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002485 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002486 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002487 binOp = glslang::EOpMul;
2488 break;
2489 }
2490 case glslang::EOpMod:
2491 // when an aggregate, this is the floating-point mod built-in function,
2492 // which can be emitted by the one in createBinaryOperation()
2493 binOp = glslang::EOpMod;
2494 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002495
2496#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002497 case glslang::EOpEmitVertex:
2498 case glslang::EOpEndPrimitive:
2499 case glslang::EOpBarrier:
2500 case glslang::EOpMemoryBarrier:
2501 case glslang::EOpMemoryBarrierAtomicCounter:
2502 case glslang::EOpMemoryBarrierBuffer:
2503 case glslang::EOpMemoryBarrierImage:
2504 case glslang::EOpMemoryBarrierShared:
2505 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002506 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002507 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002508 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002509 case glslang::EOpWorkgroupMemoryBarrier:
2510 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002511 case glslang::EOpSubgroupBarrier:
2512 case glslang::EOpSubgroupMemoryBarrier:
2513 case glslang::EOpSubgroupMemoryBarrierBuffer:
2514 case glslang::EOpSubgroupMemoryBarrierImage:
2515 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002516 noReturnValue = true;
2517 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2518 break;
2519
Jeff Bolz36831c92018-09-05 10:11:41 -05002520 case glslang::EOpAtomicStore:
2521 noReturnValue = true;
2522 // fallthrough
2523 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002524 case glslang::EOpAtomicAdd:
2525 case glslang::EOpAtomicMin:
2526 case glslang::EOpAtomicMax:
2527 case glslang::EOpAtomicAnd:
2528 case glslang::EOpAtomicOr:
2529 case glslang::EOpAtomicXor:
2530 case glslang::EOpAtomicExchange:
2531 case glslang::EOpAtomicCompSwap:
2532 atomic = true;
2533 break;
2534
John Kessenich0d0c6d32017-07-23 16:08:26 -06002535 case glslang::EOpAtomicCounterAdd:
2536 case glslang::EOpAtomicCounterSubtract:
2537 case glslang::EOpAtomicCounterMin:
2538 case glslang::EOpAtomicCounterMax:
2539 case glslang::EOpAtomicCounterAnd:
2540 case glslang::EOpAtomicCounterOr:
2541 case glslang::EOpAtomicCounterXor:
2542 case glslang::EOpAtomicCounterExchange:
2543 case glslang::EOpAtomicCounterCompSwap:
2544 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2545 builder.addCapability(spv::CapabilityAtomicStorageOps);
2546 atomic = true;
2547 break;
2548
Chao Chenb50c02e2018-09-19 11:42:24 -07002549 case glslang::EOpIgnoreIntersectionNV:
2550 case glslang::EOpTerminateRayNV:
2551 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002552 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002553 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2554 noReturnValue = true;
2555 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002556 case glslang::EOpCooperativeMatrixLoad:
2557 case glslang::EOpCooperativeMatrixStore:
2558 noReturnValue = true;
2559 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002560 case glslang::EOpBeginInvocationInterlock:
2561 case glslang::EOpEndInvocationInterlock:
2562 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2563 noReturnValue = true;
2564 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002565#endif
Chao Chen3c366992018-09-19 11:41:59 -07002566
John Kessenich140f3df2015-06-26 16:58:36 -06002567 default:
2568 break;
2569 }
2570
2571 //
2572 // See if it maps to a regular operation.
2573 //
John Kessenich140f3df2015-06-26 16:58:36 -06002574 if (binOp != glslang::EOpNull) {
2575 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2576 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2577 assert(left && right);
2578
2579 builder.clearAccessChain();
2580 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002581 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002582
2583 builder.clearAccessChain();
2584 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002585 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002586
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002587 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002588 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002589 TranslateNoContractionDecoration(node->getType().getQualifier()),
2590 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002591 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002592 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002593 left->getType().getBasicType(), reduceComparison);
2594
2595 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002596 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002597 builder.clearAccessChain();
2598 builder.setAccessChainRValue(result);
2599
2600 return false;
2601 }
2602
John Kessenich426394d2015-07-23 10:22:48 -06002603 //
2604 // Create the list of operands.
2605 //
John Kessenich140f3df2015-06-26 16:58:36 -06002606 glslang::TIntermSequence& glslangOperands = node->getSequence();
2607 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002608 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002609 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002610 // special case l-value operands; there are just a few
2611 bool lvalue = false;
2612 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002613 case glslang::EOpModf:
2614 if (arg == 1)
2615 lvalue = true;
2616 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002617#ifndef GLSLANG_WEB
2618 case glslang::EOpFrexp:
2619 if (arg == 1)
2620 lvalue = true;
2621 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002622 case glslang::EOpInterpolateAtSample:
2623 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002624 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002625 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002626 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002627
2628 // Does it need a swizzle inversion? If so, evaluation is inverted;
2629 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002630 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002631 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2632 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2633 }
Rex Xu7a26c172015-12-08 17:12:09 +08002634 break;
Rex Xud4782c12015-09-06 16:30:11 +08002635 case glslang::EOpAtomicAdd:
2636 case glslang::EOpAtomicMin:
2637 case glslang::EOpAtomicMax:
2638 case glslang::EOpAtomicAnd:
2639 case glslang::EOpAtomicOr:
2640 case glslang::EOpAtomicXor:
2641 case glslang::EOpAtomicExchange:
2642 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002643 case glslang::EOpAtomicLoad:
2644 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002645 case glslang::EOpAtomicCounterAdd:
2646 case glslang::EOpAtomicCounterSubtract:
2647 case glslang::EOpAtomicCounterMin:
2648 case glslang::EOpAtomicCounterMax:
2649 case glslang::EOpAtomicCounterAnd:
2650 case glslang::EOpAtomicCounterOr:
2651 case glslang::EOpAtomicCounterXor:
2652 case glslang::EOpAtomicCounterExchange:
2653 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002654 if (arg == 0)
2655 lvalue = true;
2656 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002657 case glslang::EOpAddCarry:
2658 case glslang::EOpSubBorrow:
2659 if (arg == 2)
2660 lvalue = true;
2661 break;
2662 case glslang::EOpUMulExtended:
2663 case glslang::EOpIMulExtended:
2664 if (arg >= 2)
2665 lvalue = true;
2666 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002667 case glslang::EOpCooperativeMatrixLoad:
2668 if (arg == 0 || arg == 1)
2669 lvalue = true;
2670 break;
2671 case glslang::EOpCooperativeMatrixStore:
2672 if (arg == 1)
2673 lvalue = true;
2674 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002675#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002676 default:
2677 break;
2678 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002679 builder.clearAccessChain();
2680 if (invertedType != spv::NoType && arg == 0)
2681 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2682 else
2683 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002684
2685 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2686 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2687
2688 if (arg == 1) {
2689 // fold "element" parameter into the access chain
2690 spv::Builder::AccessChain save = builder.getAccessChain();
2691 builder.clearAccessChain();
2692 glslangOperands[2]->traverse(this);
2693
2694 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2695
2696 builder.setAccessChain(save);
2697
2698 // Point to the first element of the array.
2699 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002700 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002701
2702 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2703 unsigned int alignment = builder.getAccessChain().alignment;
2704
2705 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2706 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2707 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2708 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2709 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2710 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2711 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2712 }
2713
2714 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2715
2716 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2717 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2718 }
2719
2720 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2721 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2722 }
2723 } else if (arg == 2) {
2724 continue;
2725 }
2726 }
2727
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002728 if (lvalue) {
John Kessenich140f3df2015-06-26 16:58:36 -06002729 operands.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002730 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2731 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2732 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002733 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002734 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002735 }
John Kessenich140f3df2015-06-26 16:58:36 -06002736 }
John Kessenich426394d2015-07-23 10:22:48 -06002737
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002738 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002739 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2740 std::vector<spv::IdImmediate> idImmOps;
2741
2742 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2743 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2744 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2745 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2746 // get the pointee type
2747 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2748 assert(builder.isCooperativeMatrixType(typeId));
2749 // do the op
2750 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2751 // store the result to the pointer (out param 'm')
2752 builder.createStore(result, operands[0]);
2753 result = 0;
2754 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2755 std::vector<spv::IdImmediate> idImmOps;
2756
2757 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2758 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2759 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2760 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2761 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2762
2763 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2764 result = 0;
2765 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002766 // Handle all atomics
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002767 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
John Kessenich426394d2015-07-23 10:22:48 -06002768 } else {
2769 // Pass through to generic operations.
2770 switch (glslangOperands.size()) {
2771 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002772 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002773 break;
2774 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002775 {
2776 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002777 TranslateNoContractionDecoration(node->getType().getQualifier()),
2778 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002779 result = createUnaryOperation(
2780 node->getOp(), decorations,
2781 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002782 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06002783 }
John Kessenich426394d2015-07-23 10:22:48 -06002784 break;
2785 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002786 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002787 break;
2788 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002789 if (invertedType)
2790 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002791 }
2792
2793 if (noReturnValue)
2794 return false;
2795
2796 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002797 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002798 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002799 } else {
2800 builder.clearAccessChain();
2801 builder.setAccessChainRValue(result);
2802 return false;
2803 }
2804}
2805
John Kessenich433e9ff2017-01-26 20:31:11 -07002806// This path handles both if-then-else and ?:
2807// The if-then-else has a node type of void, while
2808// ?: has either a void or a non-void node type
2809//
2810// Leaving the result, when not void:
2811// GLSL only has r-values as the result of a :?, but
2812// if we have an l-value, that can be more efficient if it will
2813// become the base of a complex r-value expression, because the
2814// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002815bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2816{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002817 // see if OpSelect can handle it
2818 const auto isOpSelectable = [&]() {
2819 if (node->getBasicType() == glslang::EbtVoid)
2820 return false;
2821 // OpSelect can do all other types starting with SPV 1.4
2822 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2823 // pre-1.4, only scalars and vectors can be handled
2824 if ((!node->getType().isScalar() && !node->getType().isVector()))
2825 return false;
2826 }
2827 return true;
2828 };
2829
John Kessenich4bee5312018-02-20 21:29:05 -07002830 // See if it simple and safe, or required, to execute both sides.
2831 // Crucially, side effects must be either semantically required or avoided,
2832 // and there are performance trade-offs.
2833 // Return true if required or a good idea (and safe) to execute both sides,
2834 // false otherwise.
2835 const auto bothSidesPolicy = [&]() -> bool {
2836 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002837 if (node->getTrueBlock() == nullptr ||
2838 node->getFalseBlock() == nullptr)
2839 return false;
2840
John Kessenich4bee5312018-02-20 21:29:05 -07002841 // required? (unless we write additional code to look for side effects
2842 // and make performance trade-offs if none are present)
2843 if (!node->getShortCircuit())
2844 return true;
2845
2846 // if not required to execute both, decide based on performance/practicality...
2847
John Kessenich0c1e71a2019-01-10 18:23:06 +07002848 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002849 return false;
2850
John Kessenich433e9ff2017-01-26 20:31:11 -07002851 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2852 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2853
2854 // return true if a single operand to ? : is okay for OpSelect
2855 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002856 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002857 };
2858
2859 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2860 operandOkay(node->getFalseBlock()->getAsTyped());
2861 };
2862
John Kessenich4bee5312018-02-20 21:29:05 -07002863 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2864 // emit the condition before doing anything with selection
2865 node->getCondition()->traverse(this);
2866 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2867
2868 // Find a way of executing both sides and selecting the right result.
2869 const auto executeBothSides = [&]() -> void {
2870 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002871 node->getTrueBlock()->traverse(this);
2872 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2873 node->getFalseBlock()->traverse(this);
2874 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2875
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002876 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002877
John Kessenich4bee5312018-02-20 21:29:05 -07002878 // done if void
2879 if (node->getBasicType() == glslang::EbtVoid)
2880 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002881
John Kessenich4bee5312018-02-20 21:29:05 -07002882 // emit code to select between trueValue and falseValue
2883
2884 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002885 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002886 // Emit OpSelect for this selection.
2887
2888 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002889 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2890 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002891 condition = builder.smearScalar(spv::NoPrecision, condition,
2892 builder.makeVectorType(builder.makeBoolType(),
2893 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002894 }
John Kessenich4bee5312018-02-20 21:29:05 -07002895
2896 // OpSelect
2897 result = builder.createTriOp(spv::OpSelect,
2898 convertGlslangToSpvType(node->getType()), condition,
2899 trueValue, falseValue);
2900
2901 builder.clearAccessChain();
2902 builder.setAccessChainRValue(result);
2903 } else {
2904 // We need control flow to select the result.
2905 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2906 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2907
2908 // Selection control:
2909 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2910
2911 // make an "if" based on the value created by the condition
2912 spv::Builder::If ifBuilder(condition, control, builder);
2913
2914 // emit the "then" statement
2915 builder.createStore(trueValue, result);
2916 ifBuilder.makeBeginElse();
2917 // emit the "else" statement
2918 builder.createStore(falseValue, result);
2919
2920 // finish off the control flow
2921 ifBuilder.makeEndIf();
2922
2923 builder.clearAccessChain();
2924 builder.setAccessChainLValue(result);
2925 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002926 };
2927
John Kessenich4bee5312018-02-20 21:29:05 -07002928 // Execute the one side needed, as per the condition
2929 const auto executeOneSide = [&]() {
2930 // Always emit control flow.
2931 if (node->getBasicType() != glslang::EbtVoid)
2932 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002933
John Kessenich4bee5312018-02-20 21:29:05 -07002934 // Selection control:
2935 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2936
2937 // make an "if" based on the value created by the condition
2938 spv::Builder::If ifBuilder(condition, control, builder);
2939
2940 // emit the "then" statement
2941 if (node->getTrueBlock() != nullptr) {
2942 node->getTrueBlock()->traverse(this);
2943 if (result != spv::NoResult)
2944 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2945 }
2946
2947 if (node->getFalseBlock() != nullptr) {
2948 ifBuilder.makeBeginElse();
2949 // emit the "else" statement
2950 node->getFalseBlock()->traverse(this);
2951 if (result != spv::NoResult)
2952 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2953 }
2954
2955 // finish off the control flow
2956 ifBuilder.makeEndIf();
2957
2958 if (result != spv::NoResult) {
2959 builder.clearAccessChain();
2960 builder.setAccessChainLValue(result);
2961 }
2962 };
2963
2964 // Try for OpSelect (or a requirement to execute both sides)
2965 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002966 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2967 if (node->getType().getQualifier().isSpecConstant())
2968 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002969 executeBothSides();
2970 } else
2971 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002972
2973 return false;
2974}
2975
2976bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2977{
2978 // emit and get the condition before doing anything with switch
2979 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002980 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002981
Rex Xu57e65922017-07-04 23:23:40 +08002982 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002983 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002984
John Kessenich140f3df2015-06-26 16:58:36 -06002985 // browse the children to sort out code segments
2986 int defaultSegment = -1;
2987 std::vector<TIntermNode*> codeSegments;
2988 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2989 std::vector<int> caseValues;
2990 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2991 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2992 TIntermNode* child = *c;
2993 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002994 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002995 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002996 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002997 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2998 } else
2999 codeSegments.push_back(child);
3000 }
3001
qining25262b32016-05-06 17:25:16 -04003002 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003003 // statements between the last case and the end of the switch statement
3004 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3005 (int)codeSegments.size() == defaultSegment)
3006 codeSegments.push_back(nullptr);
3007
3008 // make the switch statement
3009 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08003010 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003011
3012 // emit all the code in the segments
3013 breakForLoop.push(false);
3014 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3015 builder.nextSwitchSegment(segmentBlocks, s);
3016 if (codeSegments[s])
3017 codeSegments[s]->traverse(this);
3018 else
3019 builder.addSwitchBreak();
3020 }
3021 breakForLoop.pop();
3022
3023 builder.endSwitch(segmentBlocks);
3024
3025 return false;
3026}
3027
3028void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3029{
3030 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003031 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003032
3033 builder.clearAccessChain();
3034 builder.setAccessChainRValue(constant);
3035}
3036
3037bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3038{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003039 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003040 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003041
3042 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003043 std::vector<unsigned int> operands;
3044 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003045
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003046 // Spec requires back edges to target header blocks, and every header block
3047 // must dominate its merge block. Make a header block first to ensure these
3048 // conditions are met. By definition, it will contain OpLoopMerge, followed
3049 // by a block-ending branch. But we don't want to put any other body/test
3050 // instructions in it, since the body/test may have arbitrary instructions,
3051 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003052 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003053 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003054 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003055 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003056 spv::Block& test = builder.makeNewBlock();
3057 builder.createBranch(&test);
3058
3059 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003060 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003061 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003062 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3063
3064 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003065 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003066 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003067 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003068 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003069 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003070
3071 builder.setBuildPoint(&blocks.continue_target);
3072 if (node->getTerminal())
3073 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003074 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003075 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003076 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003077 builder.createBranch(&blocks.body);
3078
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003079 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003080 builder.setBuildPoint(&blocks.body);
3081 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003082 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003083 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003084 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003085
3086 builder.setBuildPoint(&blocks.continue_target);
3087 if (node->getTerminal())
3088 node->getTerminal()->traverse(this);
3089 if (node->getTest()) {
3090 node->getTest()->traverse(this);
3091 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003092 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003093 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003094 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003095 // TODO: unless there was a break/return/discard instruction
3096 // somewhere in the body, this is an infinite loop, so we should
3097 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003098 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003099 }
John Kessenich140f3df2015-06-26 16:58:36 -06003100 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003101 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003102 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003103 return false;
3104}
3105
3106bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3107{
3108 if (node->getExpression())
3109 node->getExpression()->traverse(this);
3110
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003111 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003112
John Kessenich140f3df2015-06-26 16:58:36 -06003113 switch (node->getFlowOp()) {
3114 case glslang::EOpKill:
3115 builder.makeDiscard();
3116 break;
3117 case glslang::EOpBreak:
3118 if (breakForLoop.top())
3119 builder.createLoopExit();
3120 else
3121 builder.addSwitchBreak();
3122 break;
3123 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003124 builder.createLoopContinue();
3125 break;
3126 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003127 if (node->getExpression()) {
3128 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3129 spv::Id returnId = accessChainLoad(glslangReturnType);
3130 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3131 builder.clearAccessChain();
3132 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3133 builder.setAccessChainLValue(copyId);
3134 multiTypeStore(glslangReturnType, returnId);
3135 returnId = builder.createLoad(copyId);
3136 }
3137 builder.makeReturn(false, returnId);
3138 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003139 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003140
3141 builder.clearAccessChain();
3142 break;
3143
Jeff Bolzba6170b2019-07-01 09:23:23 -05003144 case glslang::EOpDemote:
3145 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3146 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3147 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3148 break;
3149
John Kessenich140f3df2015-06-26 16:58:36 -06003150 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003151 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003152 break;
3153 }
3154
3155 return false;
3156}
3157
John Kessenich9c14f772019-06-17 08:38:35 -06003158spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003159{
qining25262b32016-05-06 17:25:16 -04003160 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003161 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003162 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003163 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003164 spv::Id result = createSpvConstant(*node);
3165 if (result != spv::NoResult)
3166 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003167 }
3168
3169 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003170 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003171 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3172 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003173
Rex Xucabbb782017-03-24 13:41:14 +08003174 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
3175 node->getType().containsBasicType(glslang::EbtInt16) ||
3176 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08003177 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003178 switch (storageClass) {
3179 case spv::StorageClassInput:
3180 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07003181 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003182 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003183 break;
3184 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07003185 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003186 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06003187 break;
3188 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07003189 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003190 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3191 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003192 else
3193 builder.addCapability(spv::CapabilityStorageUniform16);
3194 break;
3195 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003196 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06003197 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
3198 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3199 break;
3200 default:
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003201 if (node->getType().containsBasicType(glslang::EbtFloat16))
3202 builder.addCapability(spv::CapabilityFloat16);
3203 if (node->getType().containsBasicType(glslang::EbtInt16) ||
3204 node->getType().containsBasicType(glslang::EbtUint16))
3205 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003206 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003207 }
3208 }
Rex Xuf89ad982017-04-07 23:22:33 +08003209
John Kessenich312dcfb2018-07-03 13:19:51 -06003210 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
3211 node->getType().containsBasicType(glslang::EbtUint8);
3212 if (contains8BitType) {
3213 if (storageClass == spv::StorageClassPushConstant) {
3214 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3215 builder.addCapability(spv::CapabilityStoragePushConstant8);
3216 } else if (storageClass == spv::StorageClassUniform) {
3217 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3218 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003219 } else if (storageClass == spv::StorageClassStorageBuffer) {
3220 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3221 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003222 } else {
3223 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003224 }
3225 }
3226
John Kessenich140f3df2015-06-26 16:58:36 -06003227 const char* name = node->getName().c_str();
3228 if (glslang::IsAnonymous(name))
3229 name = "";
3230
3231 return builder.createVariable(storageClass, spvType, name);
3232}
3233
3234// Return type Id of the sampled type.
3235spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3236{
3237 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003238 case glslang::EbtInt: return builder.makeIntType(32);
3239 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003240 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003241#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003242 case glslang::EbtFloat16:
3243 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3244 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3245 return builder.makeFloatType(16);
3246#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003247 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003248 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003249 return builder.makeFloatType(32);
3250 }
3251}
3252
John Kessenich8c8505c2016-07-26 12:50:38 -06003253// If node is a swizzle operation, return the type that should be used if
3254// the swizzle base is first consumed by another operation, before the swizzle
3255// is applied.
3256spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3257{
John Kessenichecba76f2017-01-06 00:34:48 -07003258 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003259 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3260 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3261 else
3262 return spv::NoType;
3263}
3264
3265// When inverting a swizzle with a parent op, this function
3266// will apply the swizzle operation to a completed parent operation.
3267spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3268{
3269 std::vector<unsigned> swizzle;
3270 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3271 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3272}
3273
John Kessenich8c8505c2016-07-26 12:50:38 -06003274// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3275void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3276{
3277 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3278 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3279 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3280}
3281
John Kessenich3ac051e2015-12-20 11:29:16 -07003282// Convert from a glslang type to an SPV type, by calling into a
3283// recursive version of this function. This establishes the inherited
3284// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003285spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003286{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003287 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003288}
3289
3290// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003291// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003292// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003293spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003294 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3295 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003296{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003297 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003298
3299 switch (type.getBasicType()) {
3300 case glslang::EbtVoid:
3301 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003302 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003303 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003304 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003305 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3306 // a 32-bit int where non-0 means true.
3307 if (explicitLayout != glslang::ElpNone)
3308 spvType = builder.makeUintType(32);
3309 else
3310 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003311 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003312 case glslang::EbtInt:
3313 spvType = builder.makeIntType(32);
3314 break;
3315 case glslang::EbtUint:
3316 spvType = builder.makeUintType(32);
3317 break;
3318 case glslang::EbtFloat:
3319 spvType = builder.makeFloatType(32);
3320 break;
3321#ifndef GLSLANG_WEB
3322 case glslang::EbtDouble:
3323 spvType = builder.makeFloatType(64);
3324 break;
3325 case glslang::EbtFloat16:
3326 spvType = builder.makeFloatType(16);
3327 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003328 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003329 spvType = builder.makeIntType(8);
3330 break;
3331 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003332 spvType = builder.makeUintType(8);
3333 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003334 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003335 spvType = builder.makeIntType(16);
3336 break;
3337 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003338 spvType = builder.makeUintType(16);
3339 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003340 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003341 spvType = builder.makeIntType(64);
3342 break;
3343 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003344 spvType = builder.makeUintType(64);
3345 break;
John Kessenich426394d2015-07-23 10:22:48 -06003346 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003347 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003348 spvType = builder.makeUintType(32);
3349 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003350 case glslang::EbtAccStructNV:
3351 spvType = builder.makeAccelerationStructureNVType();
3352 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003353 case glslang::EbtReference:
3354 {
3355 // Make the forward pointer, then recurse to convert the structure type, then
3356 // patch up the forward pointer with a real pointer type.
3357 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3358 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3359 forwardPointers[type.getReferentType()] = forwardId;
3360 }
3361 spvType = forwardPointers[type.getReferentType()];
3362 if (!forwardReferenceOnly) {
3363 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3364 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3365 forwardPointers[type.getReferentType()],
3366 referentType);
3367 }
3368 }
3369 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003370#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003371 case glslang::EbtSampler:
3372 {
3373 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003374 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003375 spvType = builder.makeSamplerType();
3376 } else {
3377 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003378 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3379 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3380 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3381 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003382 // already has both image and sampler, make the combined type
3383 spvType = builder.makeSampledImageType(spvType);
3384 }
John Kessenich55e7d112015-11-15 21:33:39 -07003385 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003386 }
John Kessenich140f3df2015-06-26 16:58:36 -06003387 break;
3388 case glslang::EbtStruct:
3389 case glslang::EbtBlock:
3390 {
3391 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003392 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003393
3394 // Try to share structs for different layouts, but not yet for other
3395 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003396 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003397 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003398 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003399 break;
3400
3401 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003402 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003403 memberRemapper[glslangMembers].resize(glslangMembers->size());
3404 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003405 }
3406 break;
3407 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003408 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003409 break;
3410 }
3411
3412 if (type.isMatrix())
3413 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3414 else {
3415 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3416 if (type.getVectorSize() > 1)
3417 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3418 }
3419
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003420 if (type.isCoopMat()) {
3421 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3422 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3423 if (type.getBasicType() == glslang::EbtFloat16)
3424 builder.addCapability(spv::CapabilityFloat16);
3425
3426 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3427 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3428 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3429
3430 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3431 }
3432
John Kessenich140f3df2015-06-26 16:58:36 -06003433 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003434 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3435
John Kessenichc9a80832015-09-12 12:17:44 -06003436 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003437 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003438 // We need to decorate array strides for types needing explicit layout, except blocks.
3439 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003440 // Use a dummy glslang type for querying internal strides of
3441 // arrays of arrays, but using just a one-dimensional array.
3442 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003443 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3444 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003445
3446 // Will compute the higher-order strides here, rather than making a whole
3447 // pile of types and doing repetitive recursion on their contents.
3448 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3449 }
John Kessenichf8842e52016-01-04 19:22:56 -07003450
3451 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003452 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003453 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003454 if (stride > 0)
3455 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003456 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003457 }
3458 } else {
3459 // single-dimensional array, and don't yet have stride
3460
John Kessenichf8842e52016-01-04 19:22:56 -07003461 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003462 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3463 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003464 }
John Kessenich31ed4832015-09-09 17:51:38 -06003465
John Kessenichead86222018-03-28 18:01:20 -06003466 // Do the outer dimension, which might not be known for a runtime-sized array.
3467 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3468 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003469 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003470 else {
3471 if (!lastBufferBlockMember) {
3472 builder.addExtension("SPV_EXT_descriptor_indexing");
3473 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3474 }
John Kessenichead86222018-03-28 18:01:20 -06003475 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003476 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003477 if (stride > 0)
3478 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003479 }
3480
3481 return spvType;
3482}
3483
John Kessenich0e737842017-03-24 18:38:16 -06003484// TODO: this functionality should exist at a higher level, in creating the AST
3485//
3486// Identify interface members that don't have their required extension turned on.
3487//
3488bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3489{
John Kessenicha28f7a72019-08-06 07:00:58 -06003490#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003491 auto& extensions = glslangIntermediate->getRequestedExtensions();
3492
Rex Xubcf291a2017-03-29 23:01:36 +08003493 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3494 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3495 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003496 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3497 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3498 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003499
3500 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3501 if (member.getFieldName() == "gl_ViewportMask" &&
3502 extensions.find("GL_NV_viewport_array2") == extensions.end())
3503 return true;
3504 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3505 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3506 return true;
3507 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3508 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3509 return true;
3510 }
3511#endif
John Kessenich0e737842017-03-24 18:38:16 -06003512
3513 return false;
3514};
3515
John Kessenich6090df02016-06-30 21:18:02 -06003516// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3517// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3518// Mutually recursive with convertGlslangToSpvType().
3519spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3520 const glslang::TTypeList* glslangMembers,
3521 glslang::TLayoutPacking explicitLayout,
3522 const glslang::TQualifier& qualifier)
3523{
3524 // Create a vector of struct types for SPIR-V to consume
3525 std::vector<spv::Id> spvMembers;
3526 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003527 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003528 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3529 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3530 if (glslangMember.hiddenMember()) {
3531 ++memberDelta;
3532 if (type.getBasicType() == glslang::EbtBlock)
3533 memberRemapper[glslangMembers][i] = -1;
3534 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003535 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003536 if (filterMember(glslangMember)) {
3537 memberDelta++;
3538 memberRemapper[glslangMembers][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003539 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003540 }
3541 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003542 }
John Kessenich6090df02016-06-30 21:18:02 -06003543 // modify just this child's view of the qualifier
3544 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3545 InheritQualifiers(memberQualifier, qualifier);
3546
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003547 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003548 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003549 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003550
3551 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003552 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3553 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003554
3555 // Make forward pointers for any pointer members, and create a list of members to
3556 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003557 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003558 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3559 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3560 }
3561 spvMembers.push_back(
3562 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3563 } else {
3564 spvMembers.push_back(
3565 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3566 }
John Kessenich6090df02016-06-30 21:18:02 -06003567 }
3568 }
3569
3570 // Make the SPIR-V type
3571 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003572 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003573 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3574
3575 // Decorate it
3576 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3577
John Kessenichd72f4882019-01-16 14:55:37 +07003578 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003579 auto it = deferredForwardPointers[i];
3580 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3581 }
3582
John Kessenich6090df02016-06-30 21:18:02 -06003583 return spvType;
3584}
3585
3586void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3587 const glslang::TTypeList* glslangMembers,
3588 glslang::TLayoutPacking explicitLayout,
3589 const glslang::TQualifier& qualifier,
3590 spv::Id spvType)
3591{
3592 // Name and decorate the non-hidden members
3593 int offset = -1;
3594 int locationOffset = 0; // for use within the members of this struct
3595 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3596 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3597 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003598 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003599 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003600 if (filterMember(glslangMember))
3601 continue;
3602 }
John Kessenich6090df02016-06-30 21:18:02 -06003603
3604 // modify just this child's view of the qualifier
3605 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3606 InheritQualifiers(memberQualifier, qualifier);
3607
3608 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003609 if (member < 0)
3610 continue;
3611
3612 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3613 builder.addMemberDecoration(spvType, member,
3614 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3615 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3616 // Add interpolation and auxiliary storage decorations only to
3617 // top-level members of Input and Output storage classes
3618 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3619 type.getQualifier().storage == glslang::EvqVaryingOut) {
3620 if (type.getBasicType() == glslang::EbtBlock ||
3621 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3622 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3623 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003624#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003625 addMeshNVDecoration(spvType, member, memberQualifier);
3626#endif
John Kessenich6090df02016-06-30 21:18:02 -06003627 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003628 }
3629 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003630
John Kessenich5d610ee2018-03-07 18:05:55 -07003631 if (type.getBasicType() == glslang::EbtBlock &&
3632 qualifier.storage == glslang::EvqBuffer) {
3633 // Add memory decorations only to top-level members of shader storage block
3634 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003635 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003636 for (unsigned int i = 0; i < memory.size(); ++i)
3637 builder.addMemberDecoration(spvType, member, memory[i]);
3638 }
John Kessenich6090df02016-06-30 21:18:02 -06003639
John Kessenich5d610ee2018-03-07 18:05:55 -07003640 // Location assignment was already completed correctly by the front end,
3641 // just track whether a member needs to be decorated.
3642 // Ignore member locations if the container is an array, as that's
3643 // ill-specified and decisions have been made to not allow this.
3644 if (! type.isArray() && memberQualifier.hasLocation())
3645 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003646
John Kessenich5d610ee2018-03-07 18:05:55 -07003647 if (qualifier.hasLocation()) // track for upcoming inheritance
3648 locationOffset += glslangIntermediate->computeTypeLocationSize(
3649 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003650
John Kessenich5d610ee2018-03-07 18:05:55 -07003651 // component, XFB, others
3652 if (glslangMember.getQualifier().hasComponent())
3653 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3654 glslangMember.getQualifier().layoutComponent);
3655 if (glslangMember.getQualifier().hasXfbOffset())
3656 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3657 glslangMember.getQualifier().layoutXfbOffset);
3658 else if (explicitLayout != glslang::ElpNone) {
3659 // figure out what to do with offset, which is accumulating
3660 int nextOffset;
3661 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3662 if (offset >= 0)
3663 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3664 offset = nextOffset;
3665 }
John Kessenich6090df02016-06-30 21:18:02 -06003666
John Kessenich5d610ee2018-03-07 18:05:55 -07003667 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3668 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3669 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003670
John Kessenich5d610ee2018-03-07 18:05:55 -07003671 // built-in variable decorations
3672 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3673 if (builtIn != spv::BuiltInMax)
3674 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003675
John Kessenich5611c6d2018-04-05 11:25:02 -06003676 // nonuniform
3677 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3678
John Kessenichead86222018-03-28 18:01:20 -06003679 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3680 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3681 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3682 memberQualifier.semanticName);
3683 }
3684
John Kessenicha28f7a72019-08-06 07:00:58 -06003685#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003686 if (builtIn == spv::BuiltInLayer) {
3687 // SPV_NV_viewport_array2 extension
3688 if (glslangMember.getQualifier().layoutViewportRelative){
3689 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3690 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3691 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003692 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003693 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3694 builder.addMemberDecoration(spvType, member,
3695 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3696 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3697 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3698 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003699 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003700 }
3701 if (glslangMember.getQualifier().layoutPassthrough) {
3702 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3703 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3704 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3705 }
chaoc771d89f2017-01-13 01:10:53 -08003706#endif
John Kessenich6090df02016-06-30 21:18:02 -06003707 }
3708
3709 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003710 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3711 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003712}
3713
John Kessenich6c292d32016-02-15 20:58:50 -07003714// Turn the expression forming the array size into an id.
3715// This is not quite trivial, because of specialization constants.
3716// Sometimes, a raw constant is turned into an Id, and sometimes
3717// a specialization constant expression is.
3718spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3719{
3720 // First, see if this is sized with a node, meaning a specialization constant:
3721 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3722 if (specNode != nullptr) {
3723 builder.clearAccessChain();
3724 specNode->traverse(this);
3725 return accessChainLoad(specNode->getAsTyped()->getType());
3726 }
qining25262b32016-05-06 17:25:16 -04003727
John Kessenich6c292d32016-02-15 20:58:50 -07003728 // Otherwise, need a compile-time (front end) size, get it:
3729 int size = arraySizes.getDimSize(dim);
3730 assert(size > 0);
3731 return builder.makeUintConstant(size);
3732}
3733
John Kessenich103bef92016-02-08 21:38:15 -07003734// Wrap the builder's accessChainLoad to:
3735// - localize handling of RelaxedPrecision
3736// - use the SPIR-V inferred type instead of another conversion of the glslang type
3737// (avoids unnecessary work and possible type punning for structures)
3738// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003739spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3740{
John Kessenich103bef92016-02-08 21:38:15 -07003741 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003742
3743 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3744 coherentFlags |= TranslateCoherent(type);
3745
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003746 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003747 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003748
John Kessenich5611c6d2018-04-05 11:25:02 -06003749 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003750 TranslateNonUniformDecoration(type.getQualifier()),
3751 nominalTypeId,
3752 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003753 TranslateMemoryScope(coherentFlags),
3754 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003755
3756 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003757 if (type.getBasicType() == glslang::EbtBool) {
3758 if (builder.isScalarType(nominalTypeId)) {
3759 // Conversion for bool
3760 spv::Id boolType = builder.makeBoolType();
3761 if (nominalTypeId != boolType)
3762 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3763 } else if (builder.isVectorType(nominalTypeId)) {
3764 // Conversion for bvec
3765 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3766 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3767 if (nominalTypeId != bvecType)
3768 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3769 }
3770 }
John Kessenich103bef92016-02-08 21:38:15 -07003771
3772 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003773}
3774
Rex Xu27253232016-02-23 17:51:09 +08003775// Wrap the builder's accessChainStore to:
3776// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003777//
3778// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003779void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3780{
3781 // Need to convert to abstract types when necessary
3782 if (type.getBasicType() == glslang::EbtBool) {
3783 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3784
3785 if (builder.isScalarType(nominalTypeId)) {
3786 // Conversion for bool
3787 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003788 if (nominalTypeId != boolType) {
3789 // keep these outside arguments, for determinant order-of-evaluation
3790 spv::Id one = builder.makeUintConstant(1);
3791 spv::Id zero = builder.makeUintConstant(0);
3792 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3793 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003794 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003795 } else if (builder.isVectorType(nominalTypeId)) {
3796 // Conversion for bvec
3797 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3798 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003799 if (nominalTypeId != bvecType) {
3800 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003801 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3802 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3803 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003804 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003805 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3806 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003807 }
3808 }
3809
Jeff Bolz36831c92018-09-05 10:11:41 -05003810 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3811 coherentFlags |= TranslateCoherent(type);
3812
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003813 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003814 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003815
Jeff Bolz36831c92018-09-05 10:11:41 -05003816 builder.accessChainStore(rvalue,
3817 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003818 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003819}
3820
John Kessenich4bf71552016-09-02 11:20:21 -06003821// For storing when types match at the glslang level, but not might match at the
3822// SPIR-V level.
3823//
3824// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003825// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003826// as in a member-decorated way.
3827//
3828// NOTE: This function can handle any store request; if it's not special it
3829// simplifies to a simple OpStore.
3830//
3831// Implicitly uses the existing builder.accessChain as the storage target.
3832void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3833{
John Kessenichb3e24e42016-09-11 12:33:43 -06003834 // we only do the complex path here if it's an aggregate
3835 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003836 accessChainStore(type, rValue);
3837 return;
3838 }
3839
John Kessenichb3e24e42016-09-11 12:33:43 -06003840 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003841 spv::Id rType = builder.getTypeId(rValue);
3842 spv::Id lValue = builder.accessChainGetLValue();
3843 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3844 if (lType == rType) {
3845 accessChainStore(type, rValue);
3846 return;
3847 }
3848
John Kessenichb3e24e42016-09-11 12:33:43 -06003849 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003850 // where the two types were the same type in GLSL. This requires member
3851 // by member copy, recursively.
3852
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003853 // SPIR-V 1.4 added an instruction to do help do this.
3854 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3855 // However, bool in uniform space is changed to int, so
3856 // OpCopyLogical does not work for that.
3857 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3858 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3859 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3860 if (lBool == rBool) {
3861 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3862 accessChainStore(type, logicalCopy);
3863 return;
3864 }
3865 }
3866
John Kessenichb3e24e42016-09-11 12:33:43 -06003867 // If an array, copy element by element.
3868 if (type.isArray()) {
3869 glslang::TType glslangElementType(type, 0);
3870 spv::Id elementRType = builder.getContainedTypeId(rType);
3871 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3872 // get the source member
3873 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003874
John Kessenichb3e24e42016-09-11 12:33:43 -06003875 // set up the target storage
3876 builder.clearAccessChain();
3877 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003878 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003879
John Kessenichb3e24e42016-09-11 12:33:43 -06003880 // store the member
3881 multiTypeStore(glslangElementType, elementRValue);
3882 }
3883 } else {
3884 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003885
John Kessenichb3e24e42016-09-11 12:33:43 -06003886 // loop over structure members
3887 const glslang::TTypeList& members = *type.getStruct();
3888 for (int m = 0; m < (int)members.size(); ++m) {
3889 const glslang::TType& glslangMemberType = *members[m].type;
3890
3891 // get the source member
3892 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3893 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3894
3895 // set up the target storage
3896 builder.clearAccessChain();
3897 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003898 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003899
3900 // store the member
3901 multiTypeStore(glslangMemberType, memberRValue);
3902 }
John Kessenich4bf71552016-09-02 11:20:21 -06003903 }
3904}
3905
John Kessenichf85e8062015-12-19 13:57:10 -07003906// Decide whether or not this type should be
3907// decorated with offsets and strides, and if so
3908// whether std140 or std430 rules should be applied.
3909glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003910{
John Kessenichf85e8062015-12-19 13:57:10 -07003911 // has to be a block
3912 if (type.getBasicType() != glslang::EbtBlock)
3913 return glslang::ElpNone;
3914
Chao Chen3c366992018-09-19 11:41:59 -07003915 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003916 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003917 type.getQualifier().storage != glslang::EvqBuffer &&
3918 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003919 return glslang::ElpNone;
3920
3921 // return the layout to use
3922 switch (type.getQualifier().layoutPacking) {
3923 case glslang::ElpStd140:
3924 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003925 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003926 return type.getQualifier().layoutPacking;
3927 default:
3928 return glslang::ElpNone;
3929 }
John Kessenich31ed4832015-09-09 17:51:38 -06003930}
3931
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003932// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003933int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003934{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003935 int size;
John Kessenich49987892015-12-29 17:11:44 -07003936 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003937 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003938
3939 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003940}
3941
John Kessenich49987892015-12-29 17:11:44 -07003942// 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 -07003943// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003944int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003945{
John Kessenich49987892015-12-29 17:11:44 -07003946 glslang::TType elementType;
3947 elementType.shallowCopy(matrixType);
3948 elementType.clearArraySizes();
3949
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003950 int size;
John Kessenich49987892015-12-29 17:11:44 -07003951 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003952 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003953
3954 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003955}
3956
John Kessenich5e4b1242015-08-06 22:53:06 -06003957// Given a member type of a struct, realign the current offset for it, and compute
3958// the next (not yet aligned) offset for the next member, which will get aligned
3959// on the next call.
3960// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3961// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3962// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003963void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003964 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003965{
3966 // this will get a positive value when deemed necessary
3967 nextOffset = -1;
3968
John Kessenich5e4b1242015-08-06 22:53:06 -06003969 // override anything in currentOffset with user-set offset
3970 if (memberType.getQualifier().hasOffset())
3971 currentOffset = memberType.getQualifier().layoutOffset;
3972
3973 // It could be that current linker usage in glslang updated all the layoutOffset,
3974 // in which case the following code does not matter. But, that's not quite right
3975 // once cross-compilation unit GLSL validation is done, as the original user
3976 // settings are needed in layoutOffset, and then the following will come into play.
3977
John Kessenichf85e8062015-12-19 13:57:10 -07003978 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003979 if (! memberType.getQualifier().hasOffset())
3980 currentOffset = -1;
3981
3982 return;
3983 }
3984
John Kessenichf85e8062015-12-19 13:57:10 -07003985 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003986 if (currentOffset < 0)
3987 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003988
John Kessenich5e4b1242015-08-06 22:53:06 -06003989 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3990 // but possibly not yet correctly aligned.
3991
3992 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003993 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003994 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003995
3996 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003997 // TODO: make this consistent in early phases of code:
3998 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3999 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4000 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004001 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004002 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004003 int dummySize;
4004 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4005 if (componentAlignment <= 4)
4006 memberAlignment = componentAlignment;
4007 }
4008
4009 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004010 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004011
4012 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004013 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004014 glslang::RoundToPow2(currentOffset, 16);
4015
John Kessenich5e4b1242015-08-06 22:53:06 -06004016 nextOffset = currentOffset + memberSize;
4017}
4018
David Netoa901ffe2016-06-08 14:11:40 +01004019void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004020{
David Netoa901ffe2016-06-08 14:11:40 +01004021 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4022 switch (glslangBuiltIn)
4023 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004024 case glslang::EbvPointSize:
4025#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004026 case glslang::EbvClipDistance:
4027 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004028 case glslang::EbvViewportMaskNV:
4029 case glslang::EbvSecondaryPositionNV:
4030 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004031 case glslang::EbvPositionPerViewNV:
4032 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004033 case glslang::EbvTaskCountNV:
4034 case glslang::EbvPrimitiveCountNV:
4035 case glslang::EbvPrimitiveIndicesNV:
4036 case glslang::EbvClipDistancePerViewNV:
4037 case glslang::EbvCullDistancePerViewNV:
4038 case glslang::EbvLayerPerViewNV:
4039 case glslang::EbvMeshViewCountNV:
4040 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004041#endif
David Netoa901ffe2016-06-08 14:11:40 +01004042 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4043 // Alternately, we could just call this for any glslang built-in, since the
4044 // capability already guards against duplicates.
4045 TranslateBuiltInDecoration(glslangBuiltIn, false);
4046 break;
4047 default:
4048 // Capabilities were already generated when the struct was declared.
4049 break;
4050 }
John Kessenichebb50532016-05-16 19:22:05 -06004051}
4052
John Kessenich6fccb3c2016-09-19 16:01:41 -06004053bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004054{
John Kessenicheee9d532016-09-19 18:09:30 -06004055 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004056}
4057
John Kessenichd41993d2017-09-10 15:21:05 -06004058// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004059// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4060// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004061bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004062{
John Kessenich6a14f782017-12-04 02:48:10 -07004063 assert(qualifier == glslang::EvqIn ||
4064 qualifier == glslang::EvqOut ||
4065 qualifier == glslang::EvqInOut ||
4066 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004067 return qualifier != glslang::EvqConstReadOnly;
4068}
4069
4070// Is parameter pass-by-original?
4071bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4072 bool implicitThisParam)
4073{
4074 if (implicitThisParam) // implicit this
4075 return true;
4076 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004077 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004078 return paramType.containsOpaque() || // sampler, etc.
4079 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4080}
4081
John Kessenich140f3df2015-06-26 16:58:36 -06004082// Make all the functions, skeletally, without actually visiting their bodies.
4083void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4084{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004085 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004086 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4087 if (paramPrecision != spv::NoPrecision)
4088 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004089 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004090 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004091 // Original and non-writable params pass the pointer directly and
4092 // use restrict/aliased, others are stored to a pointer in Function
4093 // memory and use RestrictPointer/AliasedPointer.
4094 if (originalParam(type.getQualifier().storage, type, false) ||
4095 !writableParam(type.getQualifier().storage)) {
4096 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
4097 } else {
4098 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
4099 }
4100 }
John Kessenichfad62972017-07-18 02:35:46 -06004101 };
4102
John Kessenich140f3df2015-06-26 16:58:36 -06004103 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4104 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004105 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004106 continue;
4107
4108 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004109 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004110 //
qining25262b32016-05-06 17:25:16 -04004111 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004112 // function. What it is an address of varies:
4113 //
John Kessenich4bf71552016-09-02 11:20:21 -06004114 // - "in" parameters not marked as "const" can be written to without modifying the calling
4115 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004116 //
4117 // - "const in" parameters can just be the r-value, as no writes need occur.
4118 //
John Kessenich4bf71552016-09-02 11:20:21 -06004119 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4120 // 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 -06004121
4122 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004123 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004124 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4125
John Kessenichfad62972017-07-18 02:35:46 -06004126 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4127 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06004128
John Kessenichfad62972017-07-18 02:35:46 -06004129 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004130 for (int p = 0; p < (int)parameters.size(); ++p) {
4131 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4132 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004133 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004134 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004135 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004136 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4137 else
John Kessenich4bf71552016-09-02 11:20:21 -06004138 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004139 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004140 paramTypes.push_back(typeId);
4141 }
4142
4143 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004144 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4145 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004146 glslFunction->getName().c_str(), paramTypes,
4147 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004148 if (implicitThis)
4149 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004150
4151 // Track function to emit/call later
4152 functionMap[glslFunction->getName().c_str()] = function;
4153
4154 // Set the parameter id's
4155 for (int p = 0; p < (int)parameters.size(); ++p) {
4156 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4157 // give a name too
4158 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004159
4160 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4161 if (paramType.containsBasicType(glslang::EbtInt8) ||
4162 paramType.containsBasicType(glslang::EbtUint8))
4163 builder.addCapability(spv::CapabilityInt8);
4164 if (paramType.containsBasicType(glslang::EbtInt16) ||
4165 paramType.containsBasicType(glslang::EbtUint16))
4166 builder.addCapability(spv::CapabilityInt16);
4167 if (paramType.containsBasicType(glslang::EbtFloat16))
4168 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004169 }
4170 }
4171}
4172
4173// Process all the initializers, while skipping the functions and link objects
4174void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4175{
4176 builder.setBuildPoint(shaderEntry->getLastBlock());
4177 for (int i = 0; i < (int)initializers.size(); ++i) {
4178 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
4179 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
4180
4181 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004182 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004183 initializer->traverse(this);
4184 }
4185 }
4186}
4187
4188// Process all the functions, while skipping initializers.
4189void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4190{
4191 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4192 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004193 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004194 node->traverse(this);
4195 }
4196}
4197
4198void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4199{
qining25262b32016-05-06 17:25:16 -04004200 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004201 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004202 currentFunction = functionMap[node->getName().c_str()];
4203 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004204 builder.setBuildPoint(functionBlock);
4205}
4206
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004207void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004208{
Rex Xufc618912015-09-09 16:42:49 +08004209 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004210
4211 glslang::TSampler sampler = {};
4212 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004213#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004214 bool f16ShadowCompare = false;
4215#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004216 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004217 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4218 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004219#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004220 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4221#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004222 }
4223
John Kessenich140f3df2015-06-26 16:58:36 -06004224 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4225 builder.clearAccessChain();
4226 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004227
John Kessenicha28f7a72019-08-06 07:00:58 -06004228#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004229 // Special case l-value operands
4230 bool lvalue = false;
4231 switch (node.getOp()) {
4232 case glslang::EOpImageAtomicAdd:
4233 case glslang::EOpImageAtomicMin:
4234 case glslang::EOpImageAtomicMax:
4235 case glslang::EOpImageAtomicAnd:
4236 case glslang::EOpImageAtomicOr:
4237 case glslang::EOpImageAtomicXor:
4238 case glslang::EOpImageAtomicExchange:
4239 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004240 case glslang::EOpImageAtomicLoad:
4241 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004242 if (i == 0)
4243 lvalue = true;
4244 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004245 case glslang::EOpSparseImageLoad:
4246 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4247 lvalue = true;
4248 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004249 case glslang::EOpSparseTexture:
4250 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4251 lvalue = true;
4252 break;
4253 case glslang::EOpSparseTextureClamp:
4254 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4255 lvalue = true;
4256 break;
4257 case glslang::EOpSparseTextureLod:
4258 case glslang::EOpSparseTextureOffset:
4259 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4260 lvalue = true;
4261 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004262 case glslang::EOpSparseTextureFetch:
4263 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4264 lvalue = true;
4265 break;
4266 case glslang::EOpSparseTextureFetchOffset:
4267 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4268 lvalue = true;
4269 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004270 case glslang::EOpSparseTextureLodOffset:
4271 case glslang::EOpSparseTextureGrad:
4272 case glslang::EOpSparseTextureOffsetClamp:
4273 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4274 lvalue = true;
4275 break;
4276 case glslang::EOpSparseTextureGradOffset:
4277 case glslang::EOpSparseTextureGradClamp:
4278 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4279 lvalue = true;
4280 break;
4281 case glslang::EOpSparseTextureGradOffsetClamp:
4282 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4283 lvalue = true;
4284 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004285 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004286 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4287 lvalue = true;
4288 break;
4289 case glslang::EOpSparseTextureGatherOffset:
4290 case glslang::EOpSparseTextureGatherOffsets:
4291 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4292 lvalue = true;
4293 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004294 case glslang::EOpSparseTextureGatherLod:
4295 if (i == 3)
4296 lvalue = true;
4297 break;
4298 case glslang::EOpSparseTextureGatherLodOffset:
4299 case glslang::EOpSparseTextureGatherLodOffsets:
4300 if (i == 4)
4301 lvalue = true;
4302 break;
Rex Xu129799a2017-07-05 17:23:28 +08004303 case glslang::EOpSparseImageLoadLod:
4304 if (i == 3)
4305 lvalue = true;
4306 break;
Chao Chen3a137962018-09-19 11:41:27 -07004307 case glslang::EOpImageSampleFootprintNV:
4308 if (i == 4)
4309 lvalue = true;
4310 break;
4311 case glslang::EOpImageSampleFootprintClampNV:
4312 case glslang::EOpImageSampleFootprintLodNV:
4313 if (i == 5)
4314 lvalue = true;
4315 break;
4316 case glslang::EOpImageSampleFootprintGradNV:
4317 if (i == 6)
4318 lvalue = true;
4319 break;
4320 case glslang::EOpImageSampleFootprintGradClampNV:
4321 if (i == 7)
4322 lvalue = true;
4323 break;
Rex Xufc618912015-09-09 16:42:49 +08004324 default:
4325 break;
4326 }
4327
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004328 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004329 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004330 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4331 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4332 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004333#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004334 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004335 }
4336}
4337
John Kessenichfc51d282015-08-19 13:34:18 -06004338void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004339{
John Kessenichfc51d282015-08-19 13:34:18 -06004340 builder.clearAccessChain();
4341 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004342 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004343}
John Kessenich140f3df2015-06-26 16:58:36 -06004344
John Kessenichfc51d282015-08-19 13:34:18 -06004345spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4346{
John Kesseniche485c7a2017-05-31 18:50:53 -06004347 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004348 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004349
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004350 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004351
John Kessenichfc51d282015-08-19 13:34:18 -06004352 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004353
John Kessenichf43c7392019-03-31 10:51:57 -06004354 const glslang::TType &imageType = node->getAsAggregate()
4355 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4356 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004357 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004358#ifdef GLSLANG_WEB
4359 const bool f16ShadowCompare = false;
4360#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004361 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004362 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4363 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004364#endif
4365
John Kessenichf43c7392019-03-31 10:51:57 -06004366 const auto signExtensionMask = [&]() {
4367 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4368 if (sampler.type == glslang::EbtUint)
4369 return spv::ImageOperandsZeroExtendMask;
4370 else if (sampler.type == glslang::EbtInt)
4371 return spv::ImageOperandsSignExtendMask;
4372 }
4373 return spv::ImageOperandsMaskNone;
4374 };
4375
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004376 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4377
John Kessenichfc51d282015-08-19 13:34:18 -06004378 std::vector<spv::Id> arguments;
4379 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004380 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004381 else
4382 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004383 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004384
4385 spv::Builder::TextureParameters params = { };
4386 params.sampler = arguments[0];
4387
Rex Xu04db3f52015-09-16 11:44:02 +08004388 glslang::TCrackedTextureOp cracked;
4389 node->crackTexture(sampler, cracked);
4390
amhagan05506bb2017-06-13 16:53:02 -04004391 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004392
John Kessenichfc51d282015-08-19 13:34:18 -06004393 // Check for queries
4394 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004395 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4396 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004397 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004398
John Kessenichfc51d282015-08-19 13:34:18 -06004399 switch (node->getOp()) {
4400 case glslang::EOpImageQuerySize:
4401 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004402 if (arguments.size() > 1) {
4403 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004404 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004405 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004406 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004407#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004408 case glslang::EOpImageQuerySamples:
4409 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004410 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004411 case glslang::EOpTextureQueryLod:
4412 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004413 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004414 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004415 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004416 case glslang::EOpSparseTexelsResident:
4417 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004418#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004419 default:
4420 assert(0);
4421 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004422 }
John Kessenich140f3df2015-06-26 16:58:36 -06004423 }
4424
LoopDawg4425f242018-02-18 11:40:01 -07004425 int components = node->getType().getVectorSize();
4426
4427 if (node->getOp() == glslang::EOpTextureFetch) {
4428 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4429 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4430 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4431 // here around e.g. which ones return scalars or other types.
4432 components = 4;
4433 }
4434
4435 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4436
4437 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4438
Rex Xufc618912015-09-09 16:42:49 +08004439 // Check for image functions other than queries
4440 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004441 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004442 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004443 spv::IdImmediate image = { true, *(opIt++) };
4444 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004445
4446 // Handle subpass operations
4447 // TODO: GLSL should change to have the "MS" only on the type rather than the
4448 // built-in function.
4449 if (cracked.subpass) {
4450 // add on the (0,0) coordinate
4451 spv::Id zero = builder.makeIntConstant(0);
4452 std::vector<spv::Id> comps;
4453 comps.push_back(zero);
4454 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004455 spv::IdImmediate coord = { true,
4456 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4457 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004458 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4459 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004460 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004461 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4462 }
4463 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004464 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004465 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004466 spv::IdImmediate imageOperand = { true, *(opIt++) };
4467 operands.push_back(imageOperand);
4468 }
John Kessenich6c292d32016-02-15 20:58:50 -07004469 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004470 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4471 builder.setPrecision(result, precision);
4472 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004473 }
4474
John Kessenich149afc32018-08-14 13:31:43 -06004475 spv::IdImmediate coord = { true, *(opIt++) };
4476 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004477 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004478 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004479 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004480 mask = mask | spv::ImageOperandsSampleMask;
4481 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004482 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004483 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4484 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004485 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004486 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004487 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4488 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004489 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004490 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004491 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4492 operands.push_back(imageOperands);
4493 }
4494 if (mask & spv::ImageOperandsSampleMask) {
4495 spv::IdImmediate imageOperand = { true, *opIt++ };
4496 operands.push_back(imageOperand);
4497 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004498 if (mask & spv::ImageOperandsLodMask) {
4499 spv::IdImmediate imageOperand = { true, *opIt++ };
4500 operands.push_back(imageOperand);
4501 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004502 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004503 spv::IdImmediate imageOperand = { true,
4504 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004505 operands.push_back(imageOperand);
4506 }
4507
John Kessenich149afc32018-08-14 13:31:43 -06004508 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004509 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004510
John Kessenich149afc32018-08-14 13:31:43 -06004511 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004512 builder.setPrecision(result[0], precision);
4513
4514 // If needed, add a conversion constructor to the proper size.
4515 if (components != node->getType().getVectorSize())
4516 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4517
4518 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004519 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004520
Jeff Bolz36831c92018-09-05 10:11:41 -05004521 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004522 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004523 spv::IdImmediate texel = { true, *(opIt + 1) };
4524 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004525 } else {
4526 spv::IdImmediate texel = { true, *opIt };
4527 operands.push_back(texel);
4528 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004529
4530 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004531 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004532 mask = mask | spv::ImageOperandsSampleMask;
4533 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004534 if (cracked.lod) {
4535 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4536 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4537 mask = mask | spv::ImageOperandsLodMask;
4538 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004539 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4540 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004541 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004542 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004543 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4544 operands.push_back(imageOperands);
4545 }
4546 if (mask & spv::ImageOperandsSampleMask) {
4547 spv::IdImmediate imageOperand = { true, *opIt++ };
4548 operands.push_back(imageOperand);
4549 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004550 if (mask & spv::ImageOperandsLodMask) {
4551 spv::IdImmediate imageOperand = { true, *opIt++ };
4552 operands.push_back(imageOperand);
4553 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004554 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004555 spv::IdImmediate imageOperand = { true,
4556 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004557 operands.push_back(imageOperand);
4558 }
4559
John Kessenich56bab042015-09-16 10:54:31 -06004560 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004561 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004562 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004563 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004564 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4565 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004566 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004567 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004568 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4569
Jeff Bolz36831c92018-09-05 10:11:41 -05004570 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004571 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004572 mask = mask | spv::ImageOperandsSampleMask;
4573 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004574 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004575 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4576 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4577
Jeff Bolz36831c92018-09-05 10:11:41 -05004578 mask = mask | spv::ImageOperandsLodMask;
4579 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004580 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4581 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004582 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004583 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004584 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004585 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004586 }
4587 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004588 spv::IdImmediate imageOperand = { true, *opIt++ };
4589 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004590 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004591 if (mask & spv::ImageOperandsLodMask) {
4592 spv::IdImmediate imageOperand = { true, *opIt++ };
4593 operands.push_back(imageOperand);
4594 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004595 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4596 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4597 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004598 }
4599
4600 // Create the return type that was a special structure
4601 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004602 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004603 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4604 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4605
4606 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4607
4608 // Decode the return type
4609 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4610 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004611 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004612 // Process image atomic operations
4613
4614 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4615 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004616 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004617 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004618 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004619
Jeff Bolz36831c92018-09-05 10:11:41 -05004620 spv::Id resultTypeId;
4621 // imageAtomicStore has a void return type so base the pointer type on
4622 // the type of the value operand.
4623 if (node->getOp() == glslang::EOpImageAtomicStore) {
4624 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4625 } else {
4626 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4627 }
John Kessenich56bab042015-09-16 10:54:31 -06004628 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004629
4630 std::vector<spv::Id> operands;
4631 operands.push_back(pointer);
4632 for (; opIt != arguments.end(); ++opIt)
4633 operands.push_back(*opIt);
4634
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004635 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004636 }
4637 }
4638
John Kessenicha28f7a72019-08-06 07:00:58 -06004639#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004640 // Check for fragment mask functions other than queries
4641 if (cracked.fragMask) {
4642 assert(sampler.ms);
4643
4644 auto opIt = arguments.begin();
4645 std::vector<spv::Id> operands;
4646
4647 // Extract the image if necessary
4648 if (builder.isSampledImage(params.sampler))
4649 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4650
4651 operands.push_back(params.sampler);
4652 ++opIt;
4653
4654 if (sampler.isSubpass()) {
4655 // add on the (0,0) coordinate
4656 spv::Id zero = builder.makeIntConstant(0);
4657 std::vector<spv::Id> comps;
4658 comps.push_back(zero);
4659 comps.push_back(zero);
4660 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4661 }
4662
4663 for (; opIt != arguments.end(); ++opIt)
4664 operands.push_back(*opIt);
4665
4666 spv::Op fragMaskOp = spv::OpNop;
4667 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4668 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4669 else if (node->getOp() == glslang::EOpFragmentFetch)
4670 fragMaskOp = spv::OpFragmentFetchAMD;
4671
4672 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4673 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4674 return builder.createOp(fragMaskOp, resultType(), operands);
4675 }
4676#endif
4677
Rex Xufc618912015-09-09 16:42:49 +08004678 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004679 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004680 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004681 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08004682
John Kessenichfc51d282015-08-19 13:34:18 -06004683 // check for bias argument
4684 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004685 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004686 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004687 if (cracked.gather)
4688 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004689
4690 if (f16ShadowCompare)
4691 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004692 if (cracked.offset)
4693 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004694 else if (cracked.offsets)
4695 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004696 if (cracked.grad)
4697 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004698 if (cracked.lodClamp)
4699 ++nonBiasArgCount;
4700 if (sparse)
4701 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004702 if (imageFootprint)
4703 //Following three extra arguments
4704 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4705 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06004706 if ((int)arguments.size() > nonBiasArgCount)
4707 bias = true;
4708 }
4709
John Kessenicha5c33d62016-06-02 23:45:21 -06004710 // See if the sampler param should really be just the SPV image part
4711 if (cracked.fetch) {
4712 // a fetch needs to have the image extracted first
4713 if (builder.isSampledImage(params.sampler))
4714 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4715 }
4716
John Kessenicha28f7a72019-08-06 07:00:58 -06004717#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08004718 if (cracked.gather) {
4719 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4720 if (bias || cracked.lod ||
4721 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4722 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004723 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004724 }
4725 }
4726#endif
4727
John Kessenichfc51d282015-08-19 13:34:18 -06004728 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004729
John Kessenichfc51d282015-08-19 13:34:18 -06004730 params.coords = arguments[1];
4731 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004732 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004733
4734 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004735 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004736 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004737 ++extraArgs;
4738 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004739 params.Dref = arguments[2];
4740 ++extraArgs;
4741 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004742 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004743 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004744 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004745 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004746 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004747 dRefComp = builder.getNumComponents(params.coords) - 1;
4748 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004749 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4750 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004751
4752 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004753 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004754 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004755 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004756 } else if (glslangIntermediate->getStage() != EShLangFragment
John Kessenicha28f7a72019-08-06 07:00:58 -06004757#ifndef GLSLANG_WEB
Chao Chenbeae2252018-09-19 11:40:45 -07004758 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4759 && !(glslangIntermediate->getStage() == EShLangCompute &&
4760 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4761#endif
4762 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004763 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4764 noImplicitLod = true;
4765 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004766
4767 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004768 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004769 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004770 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004771 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004772
4773 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004774 if (cracked.grad) {
4775 params.gradX = arguments[2 + extraArgs];
4776 params.gradY = arguments[3 + extraArgs];
4777 extraArgs += 2;
4778 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004779
4780 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004781 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004782 params.offset = arguments[2 + extraArgs];
4783 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004784 } else if (cracked.offsets) {
4785 params.offsets = arguments[2 + extraArgs];
4786 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004787 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004788
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004789#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06004790 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004791 if (cracked.lodClamp) {
4792 params.lodClamp = arguments[2 + extraArgs];
4793 ++extraArgs;
4794 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004795 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004796 if (sparse) {
4797 params.texelOut = arguments[2 + extraArgs];
4798 ++extraArgs;
4799 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004800 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004801 if (cracked.gather && ! sampler.shadow) {
4802 // default component is 0, if missing, otherwise an argument
4803 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004804 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004805 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004806 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004807 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004808 }
Chao Chen3a137962018-09-19 11:41:27 -07004809 spv::Id resultStruct = spv::NoResult;
4810 if (imageFootprint) {
4811 //Following three extra arguments
4812 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4813 params.granularity = arguments[2 + extraArgs];
4814 params.coarse = arguments[3 + extraArgs];
4815 resultStruct = arguments[4 + extraArgs];
4816 extraArgs += 3;
4817 }
4818#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004819 // bias
4820 if (bias) {
4821 params.bias = arguments[2 + extraArgs];
4822 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004823 }
John Kessenichfc51d282015-08-19 13:34:18 -06004824
John Kessenicha28f7a72019-08-06 07:00:58 -06004825#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07004826 if (imageFootprint) {
4827 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4828 builder.addCapability(spv::CapabilityImageFootprintNV);
4829
4830
4831 //resultStructType(OpenGL type) contains 5 elements:
4832 //struct gl_TextureFootprint2DNV {
4833 // uvec2 anchor;
4834 // uvec2 offset;
4835 // uvec2 mask;
4836 // uint lod;
4837 // uint granularity;
4838 //};
4839 //or
4840 //struct gl_TextureFootprint3DNV {
4841 // uvec3 anchor;
4842 // uvec3 offset;
4843 // uvec2 mask;
4844 // uint lod;
4845 // uint granularity;
4846 //};
4847 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4848 assert(builder.isStructType(resultStructType));
4849
4850 //resType (SPIR-V type) contains 6 elements:
4851 //Member 0 must be a Boolean type scalar(LOD),
4852 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4853 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4854 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4855 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4856 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4857 std::vector<spv::Id> members;
4858 members.push_back(resultType());
4859 for (int i = 0; i < 5; i++) {
4860 members.push_back(builder.getContainedTypeId(resultStructType, i));
4861 }
4862 spv::Id resType = builder.makeStructType(members, "ResType");
4863
4864 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06004865 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
4866 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07004867
4868 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4869 for (int i = 0; i < 5; i++) {
4870 builder.clearAccessChain();
4871 builder.setAccessChainLValue(resultStruct);
4872
4873 //Accessing to a struct we created, no coherent flag is set
4874 spv::Builder::AccessChain::CoherentFlags flags;
4875 flags.clear();
4876
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004877 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004878 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4879 }
4880 return builder.createCompositeExtract(res, resultType(), 0);
4881 }
4882#endif
4883
John Kessenich65336482016-06-16 14:06:26 -06004884 // projective component (might not to move)
4885 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4886 // are divided by the last component of P."
4887 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4888 // unused components will appear after all used components."
4889 if (cracked.proj) {
4890 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4891 int projTargetComp;
4892 switch (sampler.dim) {
4893 case glslang::Esd1D: projTargetComp = 1; break;
4894 case glslang::Esd2D: projTargetComp = 2; break;
4895 case glslang::EsdRect: projTargetComp = 2; break;
4896 default: projTargetComp = projSourceComp; break;
4897 }
4898 // copy the projective coordinate if we have to
4899 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004900 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004901 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4902 projSourceComp);
4903 params.coords = builder.createCompositeInsert(projComp, params.coords,
4904 builder.getTypeId(params.coords), projTargetComp);
4905 }
4906 }
4907
Jeff Bolz36831c92018-09-05 10:11:41 -05004908 // nonprivate
4909 if (imageType.getQualifier().nonprivate) {
4910 params.nonprivate = true;
4911 }
4912
4913 // volatile
4914 if (imageType.getQualifier().volatil) {
4915 params.volatil = true;
4916 }
4917
St0fFa1184dd2018-04-09 21:08:14 +02004918 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06004919 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
4920 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02004921 );
LoopDawg4425f242018-02-18 11:40:01 -07004922
4923 if (components != node->getType().getVectorSize())
4924 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4925
4926 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004927}
4928
4929spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4930{
4931 // Grab the function's pointer from the previously created function
4932 spv::Function* function = functionMap[node->getName().c_str()];
4933 if (! function)
4934 return 0;
4935
4936 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4937 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4938
4939 // See comments in makeFunctions() for details about the semantics for parameter passing.
4940 //
4941 // These imply we need a four step process:
4942 // 1. Evaluate the arguments
4943 // 2. Allocate and make copies of in, out, and inout arguments
4944 // 3. Make the call
4945 // 4. Copy back the results
4946
John Kessenichd3ed90b2018-05-04 11:43:03 -06004947 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004948 std::vector<spv::Builder::AccessChain> lValues;
4949 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004950 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004951 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004952 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004953 // build l-value
4954 builder.clearAccessChain();
4955 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004956 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004957 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004958 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004959 // save l-value
4960 lValues.push_back(builder.getAccessChain());
4961 } else {
4962 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004963 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004964 }
4965 }
4966
4967 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4968 // copy the original into that space.
4969 //
4970 // Also, build up the list of actual arguments to pass in for the call
4971 int lValueCount = 0;
4972 int rValueCount = 0;
4973 std::vector<spv::Id> spvArgs;
4974 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4975 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004976 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004977 builder.setAccessChain(lValues[lValueCount]);
4978 arg = builder.accessChainGetLValue();
4979 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004980 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004981 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004982 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004983 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4984 // need to copy the input into output space
4985 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004986 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004987 builder.clearAccessChain();
4988 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004989 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004990 }
4991 ++lValueCount;
4992 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004993 // process r-value, which involves a copy for a type mismatch
4994 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4995 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4996 builder.clearAccessChain();
4997 builder.setAccessChainLValue(argCopy);
4998 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4999 arg = builder.createLoad(argCopy);
5000 } else
5001 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005002 ++rValueCount;
5003 }
5004 spvArgs.push_back(arg);
5005 }
5006
5007 // 3. Make the call.
5008 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005009 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005010
5011 // 4. Copy back out an "out" arguments.
5012 lValueCount = 0;
5013 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005014 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005015 ++lValueCount;
5016 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005017 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5018 spv::Id copy = builder.createLoad(spvArgs[a]);
5019 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005020 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005021 }
5022 ++lValueCount;
5023 }
5024 }
5025
5026 return result;
5027}
5028
5029// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005030spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005031 spv::Id typeId, spv::Id left, spv::Id right,
5032 glslang::TBasicType typeProxy, bool reduceComparison)
5033{
John Kessenich66011cb2018-03-06 16:12:04 -07005034 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5035 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005036 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005037
5038 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005039 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005040 bool comparison = false;
5041
5042 switch (op) {
5043 case glslang::EOpAdd:
5044 case glslang::EOpAddAssign:
5045 if (isFloat)
5046 binOp = spv::OpFAdd;
5047 else
5048 binOp = spv::OpIAdd;
5049 break;
5050 case glslang::EOpSub:
5051 case glslang::EOpSubAssign:
5052 if (isFloat)
5053 binOp = spv::OpFSub;
5054 else
5055 binOp = spv::OpISub;
5056 break;
5057 case glslang::EOpMul:
5058 case glslang::EOpMulAssign:
5059 if (isFloat)
5060 binOp = spv::OpFMul;
5061 else
5062 binOp = spv::OpIMul;
5063 break;
5064 case glslang::EOpVectorTimesScalar:
5065 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005066 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005067 if (builder.isVector(right))
5068 std::swap(left, right);
5069 assert(builder.isScalar(right));
5070 needMatchingVectors = false;
5071 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005072 } else if (isFloat)
5073 binOp = spv::OpFMul;
5074 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005075 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005076 break;
5077 case glslang::EOpVectorTimesMatrix:
5078 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005079 binOp = spv::OpVectorTimesMatrix;
5080 break;
5081 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005082 binOp = spv::OpMatrixTimesVector;
5083 break;
5084 case glslang::EOpMatrixTimesScalar:
5085 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005086 binOp = spv::OpMatrixTimesScalar;
5087 break;
5088 case glslang::EOpMatrixTimesMatrix:
5089 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005090 binOp = spv::OpMatrixTimesMatrix;
5091 break;
5092 case glslang::EOpOuterProduct:
5093 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005094 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005095 break;
5096
5097 case glslang::EOpDiv:
5098 case glslang::EOpDivAssign:
5099 if (isFloat)
5100 binOp = spv::OpFDiv;
5101 else if (isUnsigned)
5102 binOp = spv::OpUDiv;
5103 else
5104 binOp = spv::OpSDiv;
5105 break;
5106 case glslang::EOpMod:
5107 case glslang::EOpModAssign:
5108 if (isFloat)
5109 binOp = spv::OpFMod;
5110 else if (isUnsigned)
5111 binOp = spv::OpUMod;
5112 else
5113 binOp = spv::OpSMod;
5114 break;
5115 case glslang::EOpRightShift:
5116 case glslang::EOpRightShiftAssign:
5117 if (isUnsigned)
5118 binOp = spv::OpShiftRightLogical;
5119 else
5120 binOp = spv::OpShiftRightArithmetic;
5121 break;
5122 case glslang::EOpLeftShift:
5123 case glslang::EOpLeftShiftAssign:
5124 binOp = spv::OpShiftLeftLogical;
5125 break;
5126 case glslang::EOpAnd:
5127 case glslang::EOpAndAssign:
5128 binOp = spv::OpBitwiseAnd;
5129 break;
5130 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005131 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005132 binOp = spv::OpLogicalAnd;
5133 break;
5134 case glslang::EOpInclusiveOr:
5135 case glslang::EOpInclusiveOrAssign:
5136 binOp = spv::OpBitwiseOr;
5137 break;
5138 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005139 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005140 binOp = spv::OpLogicalOr;
5141 break;
5142 case glslang::EOpExclusiveOr:
5143 case glslang::EOpExclusiveOrAssign:
5144 binOp = spv::OpBitwiseXor;
5145 break;
5146 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005147 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005148 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005149 break;
5150
5151 case glslang::EOpLessThan:
5152 case glslang::EOpGreaterThan:
5153 case glslang::EOpLessThanEqual:
5154 case glslang::EOpGreaterThanEqual:
5155 case glslang::EOpEqual:
5156 case glslang::EOpNotEqual:
5157 case glslang::EOpVectorEqual:
5158 case glslang::EOpVectorNotEqual:
5159 comparison = true;
5160 break;
5161 default:
5162 break;
5163 }
5164
John Kessenich7c1aa102015-10-15 13:29:11 -06005165 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005166 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005167 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005168 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5169 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005170 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005171
5172 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005173 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005174 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005175
qining25262b32016-05-06 17:25:16 -04005176 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005177 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005178 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005179 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005180 }
5181
5182 if (! comparison)
5183 return 0;
5184
John Kessenich7c1aa102015-10-15 13:29:11 -06005185 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005186
John Kessenich4583b612016-08-07 19:14:22 -06005187 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005188 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5189 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06005190 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005191 return result;
5192 }
John Kessenich140f3df2015-06-26 16:58:36 -06005193
5194 switch (op) {
5195 case glslang::EOpLessThan:
5196 if (isFloat)
5197 binOp = spv::OpFOrdLessThan;
5198 else if (isUnsigned)
5199 binOp = spv::OpULessThan;
5200 else
5201 binOp = spv::OpSLessThan;
5202 break;
5203 case glslang::EOpGreaterThan:
5204 if (isFloat)
5205 binOp = spv::OpFOrdGreaterThan;
5206 else if (isUnsigned)
5207 binOp = spv::OpUGreaterThan;
5208 else
5209 binOp = spv::OpSGreaterThan;
5210 break;
5211 case glslang::EOpLessThanEqual:
5212 if (isFloat)
5213 binOp = spv::OpFOrdLessThanEqual;
5214 else if (isUnsigned)
5215 binOp = spv::OpULessThanEqual;
5216 else
5217 binOp = spv::OpSLessThanEqual;
5218 break;
5219 case glslang::EOpGreaterThanEqual:
5220 if (isFloat)
5221 binOp = spv::OpFOrdGreaterThanEqual;
5222 else if (isUnsigned)
5223 binOp = spv::OpUGreaterThanEqual;
5224 else
5225 binOp = spv::OpSGreaterThanEqual;
5226 break;
5227 case glslang::EOpEqual:
5228 case glslang::EOpVectorEqual:
5229 if (isFloat)
5230 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005231 else if (isBool)
5232 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005233 else
5234 binOp = spv::OpIEqual;
5235 break;
5236 case glslang::EOpNotEqual:
5237 case glslang::EOpVectorNotEqual:
5238 if (isFloat)
5239 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005240 else if (isBool)
5241 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005242 else
5243 binOp = spv::OpINotEqual;
5244 break;
5245 default:
5246 break;
5247 }
5248
qining25262b32016-05-06 17:25:16 -04005249 if (binOp != spv::OpNop) {
5250 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005251 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005252 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005253 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005254 }
John Kessenich140f3df2015-06-26 16:58:36 -06005255
5256 return 0;
5257}
5258
John Kessenich04bb8a02015-12-12 12:28:14 -07005259//
5260// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5261// These can be any of:
5262//
5263// matrix * scalar
5264// scalar * matrix
5265// matrix * matrix linear algebraic
5266// matrix * vector
5267// vector * matrix
5268// matrix * matrix componentwise
5269// matrix op matrix op in {+, -, /}
5270// matrix op scalar op in {+, -, /}
5271// scalar op matrix op in {+, -, /}
5272//
John Kessenichead86222018-03-28 18:01:20 -06005273spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5274 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005275{
5276 bool firstClass = true;
5277
5278 // First, handle first-class matrix operations (* and matrix/scalar)
5279 switch (op) {
5280 case spv::OpFDiv:
5281 if (builder.isMatrix(left) && builder.isScalar(right)) {
5282 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005283 spv::Id resultType = builder.getTypeId(right);
5284 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005285 op = spv::OpMatrixTimesScalar;
5286 } else
5287 firstClass = false;
5288 break;
5289 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005290 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005291 std::swap(left, right);
5292 assert(builder.isScalar(right));
5293 break;
5294 case spv::OpVectorTimesMatrix:
5295 assert(builder.isVector(left));
5296 assert(builder.isMatrix(right));
5297 break;
5298 case spv::OpMatrixTimesVector:
5299 assert(builder.isMatrix(left));
5300 assert(builder.isVector(right));
5301 break;
5302 case spv::OpMatrixTimesMatrix:
5303 assert(builder.isMatrix(left));
5304 assert(builder.isMatrix(right));
5305 break;
5306 default:
5307 firstClass = false;
5308 break;
5309 }
5310
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005311 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5312 firstClass = true;
5313
qining25262b32016-05-06 17:25:16 -04005314 if (firstClass) {
5315 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005316 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005317 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005318 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005319 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005320
LoopDawg592860c2016-06-09 08:57:35 -06005321 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005322 // The result type of all of them is the same type as the (a) matrix operand.
5323 // The algorithm is to:
5324 // - break the matrix(es) into vectors
5325 // - smear any scalar to a vector
5326 // - do vector operations
5327 // - make a matrix out the vector results
5328 switch (op) {
5329 case spv::OpFAdd:
5330 case spv::OpFSub:
5331 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005332 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005333 case spv::OpFMul:
5334 {
5335 // one time set up...
5336 bool leftMat = builder.isMatrix(left);
5337 bool rightMat = builder.isMatrix(right);
5338 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5339 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5340 spv::Id scalarType = builder.getScalarTypeId(typeId);
5341 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5342 std::vector<spv::Id> results;
5343 spv::Id smearVec = spv::NoResult;
5344 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005345 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005346 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005347 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005348
5349 // do each vector op
5350 for (unsigned int c = 0; c < numCols; ++c) {
5351 std::vector<unsigned int> indexes;
5352 indexes.push_back(c);
5353 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5354 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005355 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005356 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005357 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005358 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005359 }
5360
5361 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005362 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005363 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005364 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005365 }
5366 default:
5367 assert(0);
5368 return spv::NoResult;
5369 }
5370}
5371
John Kessenichead86222018-03-28 18:01:20 -06005372spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005373 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005374{
5375 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005376 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005377 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005378 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5379 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005380
5381 switch (op) {
5382 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005383 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005384 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005385 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005386 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005387 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005388 unaryOp = spv::OpSNegate;
5389 break;
5390
5391 case glslang::EOpLogicalNot:
5392 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005393 unaryOp = spv::OpLogicalNot;
5394 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005395 case glslang::EOpBitwiseNot:
5396 unaryOp = spv::OpNot;
5397 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005398
John Kessenich140f3df2015-06-26 16:58:36 -06005399 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005400 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005401 break;
5402 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005403 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005404 break;
5405 case glslang::EOpTranspose:
5406 unaryOp = spv::OpTranspose;
5407 break;
5408
5409 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005410 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005411 break;
5412 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005413 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005414 break;
5415 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005416 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005417 break;
5418 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005419 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005420 break;
5421 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005422 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005423 break;
5424 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005425 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005426 break;
5427 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005428 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005429 break;
5430 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005431 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005432 break;
5433
5434 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005435 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005436 break;
5437 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005438 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005439 break;
5440 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005441 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005442 break;
5443 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005444 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005445 break;
5446 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005447 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005448 break;
5449 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005450 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005451 break;
5452
5453 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005454 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005455 break;
5456 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005457 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005458 break;
5459
5460 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005461 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005462 break;
5463 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005464 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005465 break;
5466 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005467 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005468 break;
5469 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005470 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005471 break;
5472 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005473 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005474 break;
5475 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005476 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005477 break;
5478
5479 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005480 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005481 break;
5482 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005483 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005484 break;
5485 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005486 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005487 break;
5488 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005489 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005490 break;
5491 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005492 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005493 break;
5494 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005495 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005496 break;
5497
5498 case glslang::EOpIsNan:
5499 unaryOp = spv::OpIsNan;
5500 break;
5501 case glslang::EOpIsInf:
5502 unaryOp = spv::OpIsInf;
5503 break;
LoopDawg592860c2016-06-09 08:57:35 -06005504 case glslang::EOpIsFinite:
5505 unaryOp = spv::OpIsFinite;
5506 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005507
Rex Xucbc426e2015-12-15 16:03:10 +08005508 case glslang::EOpFloatBitsToInt:
5509 case glslang::EOpFloatBitsToUint:
5510 case glslang::EOpIntBitsToFloat:
5511 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005512 case glslang::EOpDoubleBitsToInt64:
5513 case glslang::EOpDoubleBitsToUint64:
5514 case glslang::EOpInt64BitsToDouble:
5515 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005516 case glslang::EOpFloat16BitsToInt16:
5517 case glslang::EOpFloat16BitsToUint16:
5518 case glslang::EOpInt16BitsToFloat16:
5519 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005520 unaryOp = spv::OpBitcast;
5521 break;
5522
John Kessenich140f3df2015-06-26 16:58:36 -06005523 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005524 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005525 break;
5526 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005527 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005528 break;
5529 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005530 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005531 break;
5532 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005533 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005534 break;
5535 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005536 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005537 break;
5538 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005539 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005540 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005541 case glslang::EOpPackSnorm4x8:
5542 libCall = spv::GLSLstd450PackSnorm4x8;
5543 break;
5544 case glslang::EOpUnpackSnorm4x8:
5545 libCall = spv::GLSLstd450UnpackSnorm4x8;
5546 break;
5547 case glslang::EOpPackUnorm4x8:
5548 libCall = spv::GLSLstd450PackUnorm4x8;
5549 break;
5550 case glslang::EOpUnpackUnorm4x8:
5551 libCall = spv::GLSLstd450UnpackUnorm4x8;
5552 break;
5553 case glslang::EOpPackDouble2x32:
5554 libCall = spv::GLSLstd450PackDouble2x32;
5555 break;
5556 case glslang::EOpUnpackDouble2x32:
5557 libCall = spv::GLSLstd450UnpackDouble2x32;
5558 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005559
Rex Xu8ff43de2016-04-22 16:51:45 +08005560 case glslang::EOpPackInt2x32:
5561 case glslang::EOpUnpackInt2x32:
5562 case glslang::EOpPackUint2x32:
5563 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005564 case glslang::EOpPack16:
5565 case glslang::EOpPack32:
5566 case glslang::EOpPack64:
5567 case glslang::EOpUnpack32:
5568 case glslang::EOpUnpack16:
5569 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005570 case glslang::EOpPackInt2x16:
5571 case glslang::EOpUnpackInt2x16:
5572 case glslang::EOpPackUint2x16:
5573 case glslang::EOpUnpackUint2x16:
5574 case glslang::EOpPackInt4x16:
5575 case glslang::EOpUnpackInt4x16:
5576 case glslang::EOpPackUint4x16:
5577 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005578 case glslang::EOpPackFloat2x16:
5579 case glslang::EOpUnpackFloat2x16:
5580 unaryOp = spv::OpBitcast;
5581 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005582
John Kessenich140f3df2015-06-26 16:58:36 -06005583 case glslang::EOpDPdx:
5584 unaryOp = spv::OpDPdx;
5585 break;
5586 case glslang::EOpDPdy:
5587 unaryOp = spv::OpDPdy;
5588 break;
5589 case glslang::EOpFwidth:
5590 unaryOp = spv::OpFwidth;
5591 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005592
John Kessenich140f3df2015-06-26 16:58:36 -06005593 case glslang::EOpAny:
5594 unaryOp = spv::OpAny;
5595 break;
5596 case glslang::EOpAll:
5597 unaryOp = spv::OpAll;
5598 break;
5599
5600 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005601 if (isFloat)
5602 libCall = spv::GLSLstd450FAbs;
5603 else
5604 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005605 break;
5606 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005607 if (isFloat)
5608 libCall = spv::GLSLstd450FSign;
5609 else
5610 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005611 break;
5612
John Kessenicha28f7a72019-08-06 07:00:58 -06005613#ifndef GLSLANG_WEB
5614 case glslang::EOpDPdxFine:
5615 unaryOp = spv::OpDPdxFine;
5616 break;
5617 case glslang::EOpDPdyFine:
5618 unaryOp = spv::OpDPdyFine;
5619 break;
5620 case glslang::EOpFwidthFine:
5621 unaryOp = spv::OpFwidthFine;
5622 break;
5623 case glslang::EOpDPdxCoarse:
5624 unaryOp = spv::OpDPdxCoarse;
5625 break;
5626 case glslang::EOpDPdyCoarse:
5627 unaryOp = spv::OpDPdyCoarse;
5628 break;
5629 case glslang::EOpFwidthCoarse:
5630 unaryOp = spv::OpFwidthCoarse;
5631 break;
5632 case glslang::EOpInterpolateAtCentroid:
5633 if (typeProxy == glslang::EbtFloat16)
5634 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5635 libCall = spv::GLSLstd450InterpolateAtCentroid;
5636 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005637 case glslang::EOpAtomicCounterIncrement:
5638 case glslang::EOpAtomicCounterDecrement:
5639 case glslang::EOpAtomicCounter:
5640 {
5641 // Handle all of the atomics in one place, in createAtomicOperation()
5642 std::vector<spv::Id> operands;
5643 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005644 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005645 }
5646
John Kessenichfc51d282015-08-19 13:34:18 -06005647 case glslang::EOpBitFieldReverse:
5648 unaryOp = spv::OpBitReverse;
5649 break;
5650 case glslang::EOpBitCount:
5651 unaryOp = spv::OpBitCount;
5652 break;
5653 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005654 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005655 break;
5656 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005657 if (isUnsigned)
5658 libCall = spv::GLSLstd450FindUMsb;
5659 else
5660 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005661 break;
5662
Rex Xu574ab042016-04-14 16:53:07 +08005663 case glslang::EOpBallot:
5664 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005665 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005666 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005667 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005668 case glslang::EOpMinInvocations:
5669 case glslang::EOpMaxInvocations:
5670 case glslang::EOpAddInvocations:
5671 case glslang::EOpMinInvocationsNonUniform:
5672 case glslang::EOpMaxInvocationsNonUniform:
5673 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005674 case glslang::EOpMinInvocationsInclusiveScan:
5675 case glslang::EOpMaxInvocationsInclusiveScan:
5676 case glslang::EOpAddInvocationsInclusiveScan:
5677 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5678 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5679 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5680 case glslang::EOpMinInvocationsExclusiveScan:
5681 case glslang::EOpMaxInvocationsExclusiveScan:
5682 case glslang::EOpAddInvocationsExclusiveScan:
5683 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5684 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5685 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08005686 {
5687 std::vector<spv::Id> operands;
5688 operands.push_back(operand);
5689 return createInvocationsOperation(op, typeId, operands, typeProxy);
5690 }
John Kessenich66011cb2018-03-06 16:12:04 -07005691 case glslang::EOpSubgroupAll:
5692 case glslang::EOpSubgroupAny:
5693 case glslang::EOpSubgroupAllEqual:
5694 case glslang::EOpSubgroupBroadcastFirst:
5695 case glslang::EOpSubgroupBallot:
5696 case glslang::EOpSubgroupInverseBallot:
5697 case glslang::EOpSubgroupBallotBitCount:
5698 case glslang::EOpSubgroupBallotInclusiveBitCount:
5699 case glslang::EOpSubgroupBallotExclusiveBitCount:
5700 case glslang::EOpSubgroupBallotFindLSB:
5701 case glslang::EOpSubgroupBallotFindMSB:
5702 case glslang::EOpSubgroupAdd:
5703 case glslang::EOpSubgroupMul:
5704 case glslang::EOpSubgroupMin:
5705 case glslang::EOpSubgroupMax:
5706 case glslang::EOpSubgroupAnd:
5707 case glslang::EOpSubgroupOr:
5708 case glslang::EOpSubgroupXor:
5709 case glslang::EOpSubgroupInclusiveAdd:
5710 case glslang::EOpSubgroupInclusiveMul:
5711 case glslang::EOpSubgroupInclusiveMin:
5712 case glslang::EOpSubgroupInclusiveMax:
5713 case glslang::EOpSubgroupInclusiveAnd:
5714 case glslang::EOpSubgroupInclusiveOr:
5715 case glslang::EOpSubgroupInclusiveXor:
5716 case glslang::EOpSubgroupExclusiveAdd:
5717 case glslang::EOpSubgroupExclusiveMul:
5718 case glslang::EOpSubgroupExclusiveMin:
5719 case glslang::EOpSubgroupExclusiveMax:
5720 case glslang::EOpSubgroupExclusiveAnd:
5721 case glslang::EOpSubgroupExclusiveOr:
5722 case glslang::EOpSubgroupExclusiveXor:
5723 case glslang::EOpSubgroupQuadSwapHorizontal:
5724 case glslang::EOpSubgroupQuadSwapVertical:
5725 case glslang::EOpSubgroupQuadSwapDiagonal: {
5726 std::vector<spv::Id> operands;
5727 operands.push_back(operand);
5728 return createSubgroupOperation(op, typeId, operands, typeProxy);
5729 }
Rex Xu9d93a232016-05-05 12:30:44 +08005730 case glslang::EOpMbcnt:
5731 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5732 libCall = spv::MbcntAMD;
5733 break;
5734
5735 case glslang::EOpCubeFaceIndex:
5736 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5737 libCall = spv::CubeFaceIndexAMD;
5738 break;
5739
5740 case glslang::EOpCubeFaceCoord:
5741 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5742 libCall = spv::CubeFaceCoordAMD;
5743 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005744 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005745 unaryOp = spv::OpGroupNonUniformPartitionNV;
5746 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005747 case glslang::EOpConstructReference:
5748 unaryOp = spv::OpBitcast;
5749 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005750#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05005751
5752 case glslang::EOpCopyObject:
5753 unaryOp = spv::OpCopyObject;
5754 break;
5755
John Kessenich140f3df2015-06-26 16:58:36 -06005756 default:
5757 return 0;
5758 }
5759
5760 spv::Id id;
5761 if (libCall >= 0) {
5762 std::vector<spv::Id> args;
5763 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005764 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005765 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005766 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005767 }
John Kessenich140f3df2015-06-26 16:58:36 -06005768
John Kessenichead86222018-03-28 18:01:20 -06005769 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005770 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005771 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005772}
5773
John Kessenich7a53f762016-01-20 11:19:27 -07005774// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005775spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5776 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005777{
5778 // Handle unary operations vector by vector.
5779 // The result type is the same type as the original type.
5780 // The algorithm is to:
5781 // - break the matrix into vectors
5782 // - apply the operation to each vector
5783 // - make a matrix out the vector results
5784
5785 // get the types sorted out
5786 int numCols = builder.getNumColumns(operand);
5787 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005788 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5789 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005790 std::vector<spv::Id> results;
5791
5792 // do each vector op
5793 for (int c = 0; c < numCols; ++c) {
5794 std::vector<unsigned int> indexes;
5795 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005796 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5797 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005798 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005799 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005800 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005801 }
5802
5803 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005804 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005805 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005806 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005807}
5808
John Kessenichad7645f2018-06-04 19:11:25 -06005809// For converting integers where both the bitwidth and the signedness could
5810// change, but only do the width change here. The caller is still responsible
5811// for the signedness conversion.
5812spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005813{
John Kessenichad7645f2018-06-04 19:11:25 -06005814 // Get the result type width, based on the type to convert to.
5815 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005816 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005817 case glslang::EOpConvInt16ToUint8:
5818 case glslang::EOpConvIntToUint8:
5819 case glslang::EOpConvInt64ToUint8:
5820 case glslang::EOpConvUint16ToInt8:
5821 case glslang::EOpConvUintToInt8:
5822 case glslang::EOpConvUint64ToInt8:
5823 width = 8;
5824 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005825 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005826 case glslang::EOpConvIntToUint16:
5827 case glslang::EOpConvInt64ToUint16:
5828 case glslang::EOpConvUint8ToInt16:
5829 case glslang::EOpConvUintToInt16:
5830 case glslang::EOpConvUint64ToInt16:
5831 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005832 break;
5833 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005834 case glslang::EOpConvInt16ToUint:
5835 case glslang::EOpConvInt64ToUint:
5836 case glslang::EOpConvUint8ToInt:
5837 case glslang::EOpConvUint16ToInt:
5838 case glslang::EOpConvUint64ToInt:
5839 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005840 break;
5841 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005842 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005843 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005844 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005845 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005846 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005847 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005848 break;
5849
5850 default:
5851 assert(false && "Default missing");
5852 break;
5853 }
5854
John Kessenichad7645f2018-06-04 19:11:25 -06005855 // Get the conversion operation and result type,
5856 // based on the target width, but the source type.
5857 spv::Id type = spv::NoType;
5858 spv::Op convOp = spv::OpNop;
5859 switch(op) {
5860 case glslang::EOpConvInt8ToUint16:
5861 case glslang::EOpConvInt8ToUint:
5862 case glslang::EOpConvInt8ToUint64:
5863 case glslang::EOpConvInt16ToUint8:
5864 case glslang::EOpConvInt16ToUint:
5865 case glslang::EOpConvInt16ToUint64:
5866 case glslang::EOpConvIntToUint8:
5867 case glslang::EOpConvIntToUint16:
5868 case glslang::EOpConvIntToUint64:
5869 case glslang::EOpConvInt64ToUint8:
5870 case glslang::EOpConvInt64ToUint16:
5871 case glslang::EOpConvInt64ToUint:
5872 convOp = spv::OpSConvert;
5873 type = builder.makeIntType(width);
5874 break;
5875 default:
5876 convOp = spv::OpUConvert;
5877 type = builder.makeUintType(width);
5878 break;
5879 }
5880
John Kessenich66011cb2018-03-06 16:12:04 -07005881 if (vectorSize > 0)
5882 type = builder.makeVectorType(type, vectorSize);
5883
John Kessenichad7645f2018-06-04 19:11:25 -06005884 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005885}
5886
John Kessenichead86222018-03-28 18:01:20 -06005887spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5888 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005889{
5890 spv::Op convOp = spv::OpNop;
5891 spv::Id zero = 0;
5892 spv::Id one = 0;
5893
5894 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5895
5896 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005897 case glslang::EOpConvIntToBool:
5898 case glslang::EOpConvUintToBool:
5899 zero = builder.makeUintConstant(0);
5900 zero = makeSmearedConstant(zero, vectorSize);
5901 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06005902 case glslang::EOpConvFloatToBool:
5903 zero = builder.makeFloatConstant(0.0F);
5904 zero = makeSmearedConstant(zero, vectorSize);
5905 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06005906 case glslang::EOpConvBoolToFloat:
5907 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005908 zero = builder.makeFloatConstant(0.0F);
5909 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005910 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005911
John Kessenich140f3df2015-06-26 16:58:36 -06005912 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005913 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005914 if (op == glslang::EOpConvBoolToInt64)
5915 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005916 else
5917 zero = builder.makeIntConstant(0);
5918
5919 if (op == glslang::EOpConvBoolToInt64)
5920 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005921 else
5922 one = builder.makeIntConstant(1);
5923
John Kessenich140f3df2015-06-26 16:58:36 -06005924 convOp = spv::OpSelect;
5925 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005926
John Kessenich140f3df2015-06-26 16:58:36 -06005927 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005928 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005929 if (op == glslang::EOpConvBoolToUint64)
5930 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005931 else
5932 zero = builder.makeUintConstant(0);
5933
5934 if (op == glslang::EOpConvBoolToUint64)
5935 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005936 else
5937 one = builder.makeUintConstant(1);
5938
John Kessenich140f3df2015-06-26 16:58:36 -06005939 convOp = spv::OpSelect;
5940 break;
5941
John Kessenich66011cb2018-03-06 16:12:04 -07005942 case glslang::EOpConvInt8ToFloat16:
5943 case glslang::EOpConvInt8ToFloat:
5944 case glslang::EOpConvInt8ToDouble:
5945 case glslang::EOpConvInt16ToFloat16:
5946 case glslang::EOpConvInt16ToFloat:
5947 case glslang::EOpConvInt16ToDouble:
5948 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005949 case glslang::EOpConvIntToFloat:
5950 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005951 case glslang::EOpConvInt64ToFloat:
5952 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005953 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005954 convOp = spv::OpConvertSToF;
5955 break;
5956
John Kessenich66011cb2018-03-06 16:12:04 -07005957 case glslang::EOpConvUint8ToFloat16:
5958 case glslang::EOpConvUint8ToFloat:
5959 case glslang::EOpConvUint8ToDouble:
5960 case glslang::EOpConvUint16ToFloat16:
5961 case glslang::EOpConvUint16ToFloat:
5962 case glslang::EOpConvUint16ToDouble:
5963 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005964 case glslang::EOpConvUintToFloat:
5965 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005966 case glslang::EOpConvUint64ToFloat:
5967 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005968 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005969 convOp = spv::OpConvertUToF;
5970 break;
5971
John Kessenich66011cb2018-03-06 16:12:04 -07005972 case glslang::EOpConvFloat16ToInt8:
5973 case glslang::EOpConvFloatToInt8:
5974 case glslang::EOpConvDoubleToInt8:
5975 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005976 case glslang::EOpConvFloatToInt16:
5977 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005978 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005979 case glslang::EOpConvFloatToInt:
5980 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005981 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005982 case glslang::EOpConvFloatToInt64:
5983 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005984 convOp = spv::OpConvertFToS;
5985 break;
5986
John Kessenich66011cb2018-03-06 16:12:04 -07005987 case glslang::EOpConvUint8ToInt8:
5988 case glslang::EOpConvInt8ToUint8:
5989 case glslang::EOpConvUint16ToInt16:
5990 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005991 case glslang::EOpConvUintToInt:
5992 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005993 case glslang::EOpConvUint64ToInt64:
5994 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005995 if (builder.isInSpecConstCodeGenMode()) {
5996 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06005997#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07005998 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5999 zero = builder.makeUint8Constant(0);
6000 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006001 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006002 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6003 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006004 } else
6005#endif
6006 {
Rex Xucabbb782017-03-24 13:41:14 +08006007 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006008 }
qining189b2032016-04-12 23:16:20 -04006009 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006010 // Use OpIAdd, instead of OpBitcast to do the conversion when
6011 // generating for OpSpecConstantOp instruction.
6012 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6013 }
6014 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006015 convOp = spv::OpBitcast;
6016 break;
6017
John Kessenich66011cb2018-03-06 16:12:04 -07006018 case glslang::EOpConvFloat16ToUint8:
6019 case glslang::EOpConvFloatToUint8:
6020 case glslang::EOpConvDoubleToUint8:
6021 case glslang::EOpConvFloat16ToUint16:
6022 case glslang::EOpConvFloatToUint16:
6023 case glslang::EOpConvDoubleToUint16:
6024 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006025 case glslang::EOpConvFloatToUint:
6026 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006027 case glslang::EOpConvFloatToUint64:
6028 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006029 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006030 convOp = spv::OpConvertFToU;
6031 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006032
John Kessenich39697cd2019-08-08 10:35:51 -06006033#ifndef GLSLANG_WEB
6034 case glslang::EOpConvInt8ToBool:
6035 case glslang::EOpConvUint8ToBool:
6036 zero = builder.makeUint8Constant(0);
6037 zero = makeSmearedConstant(zero, vectorSize);
6038 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6039 case glslang::EOpConvInt16ToBool:
6040 case glslang::EOpConvUint16ToBool:
6041 zero = builder.makeUint16Constant(0);
6042 zero = makeSmearedConstant(zero, vectorSize);
6043 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6044 case glslang::EOpConvInt64ToBool:
6045 case glslang::EOpConvUint64ToBool:
6046 zero = builder.makeUint64Constant(0);
6047 zero = makeSmearedConstant(zero, vectorSize);
6048 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6049 case glslang::EOpConvDoubleToBool:
6050 zero = builder.makeDoubleConstant(0.0);
6051 zero = makeSmearedConstant(zero, vectorSize);
6052 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6053 case glslang::EOpConvFloat16ToBool:
6054 zero = builder.makeFloat16Constant(0.0F);
6055 zero = makeSmearedConstant(zero, vectorSize);
6056 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6057 case glslang::EOpConvBoolToDouble:
6058 convOp = spv::OpSelect;
6059 zero = builder.makeDoubleConstant(0.0);
6060 one = builder.makeDoubleConstant(1.0);
6061 break;
6062 case glslang::EOpConvBoolToFloat16:
6063 convOp = spv::OpSelect;
6064 zero = builder.makeFloat16Constant(0.0F);
6065 one = builder.makeFloat16Constant(1.0F);
6066 break;
6067 case glslang::EOpConvBoolToInt8:
6068 zero = builder.makeInt8Constant(0);
6069 one = builder.makeInt8Constant(1);
6070 convOp = spv::OpSelect;
6071 break;
6072 case glslang::EOpConvBoolToUint8:
6073 zero = builder.makeUint8Constant(0);
6074 one = builder.makeUint8Constant(1);
6075 convOp = spv::OpSelect;
6076 break;
6077 case glslang::EOpConvBoolToInt16:
6078 zero = builder.makeInt16Constant(0);
6079 one = builder.makeInt16Constant(1);
6080 convOp = spv::OpSelect;
6081 break;
6082 case glslang::EOpConvBoolToUint16:
6083 zero = builder.makeUint16Constant(0);
6084 one = builder.makeUint16Constant(1);
6085 convOp = spv::OpSelect;
6086 break;
6087 case glslang::EOpConvDoubleToFloat:
6088 case glslang::EOpConvFloatToDouble:
6089 case glslang::EOpConvDoubleToFloat16:
6090 case glslang::EOpConvFloat16ToDouble:
6091 case glslang::EOpConvFloatToFloat16:
6092 case glslang::EOpConvFloat16ToFloat:
6093 convOp = spv::OpFConvert;
6094 if (builder.isMatrixType(destType))
6095 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6096 break;
6097
John Kessenich66011cb2018-03-06 16:12:04 -07006098 case glslang::EOpConvInt8ToInt16:
6099 case glslang::EOpConvInt8ToInt:
6100 case glslang::EOpConvInt8ToInt64:
6101 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006102 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006103 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006104 case glslang::EOpConvIntToInt8:
6105 case glslang::EOpConvIntToInt16:
6106 case glslang::EOpConvIntToInt64:
6107 case glslang::EOpConvInt64ToInt8:
6108 case glslang::EOpConvInt64ToInt16:
6109 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006110 convOp = spv::OpSConvert;
6111 break;
6112
John Kessenich66011cb2018-03-06 16:12:04 -07006113 case glslang::EOpConvUint8ToUint16:
6114 case glslang::EOpConvUint8ToUint:
6115 case glslang::EOpConvUint8ToUint64:
6116 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006117 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006118 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006119 case glslang::EOpConvUintToUint8:
6120 case glslang::EOpConvUintToUint16:
6121 case glslang::EOpConvUintToUint64:
6122 case glslang::EOpConvUint64ToUint8:
6123 case glslang::EOpConvUint64ToUint16:
6124 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006125 convOp = spv::OpUConvert;
6126 break;
6127
John Kessenich66011cb2018-03-06 16:12:04 -07006128 case glslang::EOpConvInt8ToUint16:
6129 case glslang::EOpConvInt8ToUint:
6130 case glslang::EOpConvInt8ToUint64:
6131 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006132 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006133 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006134 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006135 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006136 case glslang::EOpConvIntToUint64:
6137 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006138 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006139 case glslang::EOpConvInt64ToUint:
6140 case glslang::EOpConvUint8ToInt16:
6141 case glslang::EOpConvUint8ToInt:
6142 case glslang::EOpConvUint8ToInt64:
6143 case glslang::EOpConvUint16ToInt8:
6144 case glslang::EOpConvUint16ToInt:
6145 case glslang::EOpConvUint16ToInt64:
6146 case glslang::EOpConvUintToInt8:
6147 case glslang::EOpConvUintToInt16:
6148 case glslang::EOpConvUintToInt64:
6149 case glslang::EOpConvUint64ToInt8:
6150 case glslang::EOpConvUint64ToInt16:
6151 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006152 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006153 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006154
6155 if (builder.isInSpecConstCodeGenMode()) {
6156 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006157 switch(op) {
6158 case glslang::EOpConvInt16ToUint8:
6159 case glslang::EOpConvIntToUint8:
6160 case glslang::EOpConvInt64ToUint8:
6161 case glslang::EOpConvUint16ToInt8:
6162 case glslang::EOpConvUintToInt8:
6163 case glslang::EOpConvUint64ToInt8:
6164 zero = builder.makeUint8Constant(0);
6165 break;
6166 case glslang::EOpConvInt8ToUint16:
6167 case glslang::EOpConvIntToUint16:
6168 case glslang::EOpConvInt64ToUint16:
6169 case glslang::EOpConvUint8ToInt16:
6170 case glslang::EOpConvUintToInt16:
6171 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006172 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006173 break;
6174 case glslang::EOpConvInt8ToUint:
6175 case glslang::EOpConvInt16ToUint:
6176 case glslang::EOpConvInt64ToUint:
6177 case glslang::EOpConvUint8ToInt:
6178 case glslang::EOpConvUint16ToInt:
6179 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006180 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006181 break;
6182 case glslang::EOpConvInt8ToUint64:
6183 case glslang::EOpConvInt16ToUint64:
6184 case glslang::EOpConvIntToUint64:
6185 case glslang::EOpConvUint8ToInt64:
6186 case glslang::EOpConvUint16ToInt64:
6187 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006188 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006189 break;
6190 default:
6191 assert(false && "Default missing");
6192 break;
6193 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006194 zero = makeSmearedConstant(zero, vectorSize);
6195 // Use OpIAdd, instead of OpBitcast to do the conversion when
6196 // generating for OpSpecConstantOp instruction.
6197 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6198 }
6199 // For normal run-time conversion instruction, use OpBitcast.
6200 convOp = spv::OpBitcast;
6201 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006202 case glslang::EOpConvUint64ToPtr:
6203 convOp = spv::OpConvertUToPtr;
6204 break;
6205 case glslang::EOpConvPtrToUint64:
6206 convOp = spv::OpConvertPtrToU;
6207 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006208#endif
6209
John Kessenich140f3df2015-06-26 16:58:36 -06006210 default:
6211 break;
6212 }
6213
6214 spv::Id result = 0;
6215 if (convOp == spv::OpNop)
6216 return result;
6217
6218 if (convOp == spv::OpSelect) {
6219 zero = makeSmearedConstant(zero, vectorSize);
6220 one = makeSmearedConstant(one, vectorSize);
6221 result = builder.createTriOp(convOp, destType, operand, one, zero);
6222 } else
6223 result = builder.createUnaryOp(convOp, destType, operand);
6224
John Kessenichead86222018-03-28 18:01:20 -06006225 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006226 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006227 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006228}
6229
6230spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6231{
6232 if (vectorSize == 0)
6233 return constant;
6234
6235 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6236 std::vector<spv::Id> components;
6237 for (int c = 0; c < vectorSize; ++c)
6238 components.push_back(constant);
6239 return builder.makeCompositeConstant(vectorTypeId, components);
6240}
6241
John Kessenich426394d2015-07-23 10:22:48 -06006242// For glslang ops that map to SPV atomic opCodes
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006243spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006244{
6245 spv::Op opCode = spv::OpNop;
6246
6247 switch (op) {
6248 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006249 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006250 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006251 opCode = spv::OpAtomicIAdd;
6252 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006253 case glslang::EOpAtomicCounterSubtract:
6254 opCode = spv::OpAtomicISub;
6255 break;
John Kessenich426394d2015-07-23 10:22:48 -06006256 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006257 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006258 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006259 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006260 break;
6261 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006262 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006263 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006264 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006265 break;
6266 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006267 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006268 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006269 opCode = spv::OpAtomicAnd;
6270 break;
6271 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006272 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006273 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006274 opCode = spv::OpAtomicOr;
6275 break;
6276 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006277 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006278 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006279 opCode = spv::OpAtomicXor;
6280 break;
6281 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006282 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006283 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006284 opCode = spv::OpAtomicExchange;
6285 break;
6286 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006287 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006288 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006289 opCode = spv::OpAtomicCompareExchange;
6290 break;
6291 case glslang::EOpAtomicCounterIncrement:
6292 opCode = spv::OpAtomicIIncrement;
6293 break;
6294 case glslang::EOpAtomicCounterDecrement:
6295 opCode = spv::OpAtomicIDecrement;
6296 break;
6297 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006298 case glslang::EOpImageAtomicLoad:
6299 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006300 opCode = spv::OpAtomicLoad;
6301 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006302 case glslang::EOpAtomicStore:
6303 case glslang::EOpImageAtomicStore:
6304 opCode = spv::OpAtomicStore;
6305 break;
John Kessenich426394d2015-07-23 10:22:48 -06006306 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006307 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006308 break;
6309 }
6310
Rex Xue8fe8b02017-09-26 15:42:56 +08006311 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6312 builder.addCapability(spv::CapabilityInt64Atomics);
6313
John Kessenich426394d2015-07-23 10:22:48 -06006314 // Sort out the operands
6315 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006316 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006317 // - compare-exchange swaps the value and comparator
6318 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006319 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006320 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6321 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6322 spv::Id scopeId;
6323 if (glslangIntermediate->usingVulkanMemoryModel()) {
6324 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6325 } else {
6326 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6327 }
6328 // semantics default to relaxed
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006329 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.volatil ? spv::MemorySemanticsVolatileMask : spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006330 spv::Id semanticsId2 = semanticsId;
6331
6332 pointerId = operands[0];
6333 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6334 // no additional operands
6335 } else if (opCode == spv::OpAtomicCompareExchange) {
6336 compareId = operands[1];
6337 valueId = operands[2];
6338 if (operands.size() > 3) {
6339 scopeId = operands[3];
6340 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6341 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6342 }
6343 } else if (opCode == spv::OpAtomicLoad) {
6344 if (operands.size() > 1) {
6345 scopeId = operands[1];
6346 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6347 }
6348 } else {
6349 // atomic store or RMW
6350 valueId = operands[1];
6351 if (operands.size() > 2) {
6352 scopeId = operands[2];
6353 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6354 }
Rex Xu04db3f52015-09-16 11:44:02 +08006355 }
John Kessenich426394d2015-07-23 10:22:48 -06006356
Jeff Bolz36831c92018-09-05 10:11:41 -05006357 // Check for capabilities
6358 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006359 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6360 spv::MemorySemanticsMakeVisibleKHRMask |
6361 spv::MemorySemanticsOutputMemoryKHRMask |
6362 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006363 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6364 }
John Kessenich426394d2015-07-23 10:22:48 -06006365
Jeff Bolz36831c92018-09-05 10:11:41 -05006366 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6367 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6368 }
John Kessenich48d6e792017-10-06 21:21:48 -06006369
Jeff Bolz36831c92018-09-05 10:11:41 -05006370 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6371 spvAtomicOperands.push_back(pointerId);
6372 spvAtomicOperands.push_back(scopeId);
6373 spvAtomicOperands.push_back(semanticsId);
6374 if (opCode == spv::OpAtomicCompareExchange) {
6375 spvAtomicOperands.push_back(semanticsId2);
6376 spvAtomicOperands.push_back(valueId);
6377 spvAtomicOperands.push_back(compareId);
6378 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6379 spvAtomicOperands.push_back(valueId);
6380 }
John Kessenich48d6e792017-10-06 21:21:48 -06006381
Jeff Bolz36831c92018-09-05 10:11:41 -05006382 if (opCode == spv::OpAtomicStore) {
6383 builder.createNoResultOp(opCode, spvAtomicOperands);
6384 return 0;
6385 } else {
6386 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6387
6388 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6389 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6390 if (op == glslang::EOpAtomicCounterDecrement)
6391 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6392
6393 return resultId;
6394 }
John Kessenich426394d2015-07-23 10:22:48 -06006395}
6396
John Kessenich91cef522016-05-05 16:45:40 -06006397// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006398spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006399{
John Kessenich66011cb2018-03-06 16:12:04 -07006400 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6401 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006402
Rex Xu51596642016-09-21 18:56:12 +08006403 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006404 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006405 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6406
chaocf200da82016-12-20 12:44:35 -08006407 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6408 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006409 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6410 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006411 } else if (op == glslang::EOpAnyInvocation ||
6412 op == glslang::EOpAllInvocations ||
6413 op == glslang::EOpAllInvocationsEqual) {
6414 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6415 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006416 } else {
6417 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006418 if (op == glslang::EOpMinInvocationsNonUniform ||
6419 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006420 op == glslang::EOpAddInvocationsNonUniform ||
6421 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6422 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6423 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6424 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6425 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6426 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006427 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006428
Rex Xu430ef402016-10-14 17:22:23 +08006429 switch (op) {
6430 case glslang::EOpMinInvocations:
6431 case glslang::EOpMaxInvocations:
6432 case glslang::EOpAddInvocations:
6433 case glslang::EOpMinInvocationsNonUniform:
6434 case glslang::EOpMaxInvocationsNonUniform:
6435 case glslang::EOpAddInvocationsNonUniform:
6436 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006437 break;
6438 case glslang::EOpMinInvocationsInclusiveScan:
6439 case glslang::EOpMaxInvocationsInclusiveScan:
6440 case glslang::EOpAddInvocationsInclusiveScan:
6441 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6442 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6443 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6444 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006445 break;
6446 case glslang::EOpMinInvocationsExclusiveScan:
6447 case glslang::EOpMaxInvocationsExclusiveScan:
6448 case glslang::EOpAddInvocationsExclusiveScan:
6449 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6450 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6451 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6452 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006453 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006454 default:
6455 break;
Rex Xu430ef402016-10-14 17:22:23 +08006456 }
John Kessenich149afc32018-08-14 13:31:43 -06006457 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6458 spvGroupOperands.push_back(scope);
6459 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006460 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006461 spvGroupOperands.push_back(groupOp);
6462 }
Rex Xu51596642016-09-21 18:56:12 +08006463 }
6464
John Kessenich149afc32018-08-14 13:31:43 -06006465 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6466 spv::IdImmediate op = { true, *opIt };
6467 spvGroupOperands.push_back(op);
6468 }
John Kessenich91cef522016-05-05 16:45:40 -06006469
6470 switch (op) {
6471 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006472 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006473 break;
John Kessenich91cef522016-05-05 16:45:40 -06006474 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006475 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006476 break;
John Kessenich91cef522016-05-05 16:45:40 -06006477 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006478 opCode = spv::OpSubgroupAllEqualKHR;
6479 break;
Rex Xu51596642016-09-21 18:56:12 +08006480 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006481 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006482 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006483 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006484 break;
6485 case glslang::EOpReadFirstInvocation:
6486 opCode = spv::OpSubgroupFirstInvocationKHR;
6487 break;
6488 case glslang::EOpBallot:
6489 {
6490 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6491 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6492 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6493 //
6494 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6495 //
6496 spv::Id uintType = builder.makeUintType(32);
6497 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6498 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6499
6500 std::vector<spv::Id> components;
6501 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6502 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6503
6504 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6505 return builder.createUnaryOp(spv::OpBitcast, typeId,
6506 builder.createCompositeConstruct(uvec2Type, components));
6507 }
6508
Rex Xu9d93a232016-05-05 12:30:44 +08006509 case glslang::EOpMinInvocations:
6510 case glslang::EOpMaxInvocations:
6511 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006512 case glslang::EOpMinInvocationsInclusiveScan:
6513 case glslang::EOpMaxInvocationsInclusiveScan:
6514 case glslang::EOpAddInvocationsInclusiveScan:
6515 case glslang::EOpMinInvocationsExclusiveScan:
6516 case glslang::EOpMaxInvocationsExclusiveScan:
6517 case glslang::EOpAddInvocationsExclusiveScan:
6518 if (op == glslang::EOpMinInvocations ||
6519 op == glslang::EOpMinInvocationsInclusiveScan ||
6520 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006521 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006522 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006523 else {
6524 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006525 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006526 else
Rex Xu51596642016-09-21 18:56:12 +08006527 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006528 }
Rex Xu430ef402016-10-14 17:22:23 +08006529 } else if (op == glslang::EOpMaxInvocations ||
6530 op == glslang::EOpMaxInvocationsInclusiveScan ||
6531 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006532 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006533 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006534 else {
6535 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006536 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006537 else
Rex Xu51596642016-09-21 18:56:12 +08006538 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006539 }
6540 } else {
6541 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006542 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006543 else
Rex Xu51596642016-09-21 18:56:12 +08006544 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006545 }
6546
Rex Xu2bbbe062016-08-23 15:41:05 +08006547 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006548 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006549
6550 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006551 case glslang::EOpMinInvocationsNonUniform:
6552 case glslang::EOpMaxInvocationsNonUniform:
6553 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006554 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6555 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6556 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6557 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6558 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6559 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6560 if (op == glslang::EOpMinInvocationsNonUniform ||
6561 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6562 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006563 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006564 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006565 else {
6566 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006567 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006568 else
Rex Xu51596642016-09-21 18:56:12 +08006569 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006570 }
6571 }
Rex Xu430ef402016-10-14 17:22:23 +08006572 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6573 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6574 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006575 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006576 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006577 else {
6578 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006579 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006580 else
Rex Xu51596642016-09-21 18:56:12 +08006581 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006582 }
6583 }
6584 else {
6585 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006586 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006587 else
Rex Xu51596642016-09-21 18:56:12 +08006588 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006589 }
6590
Rex Xu2bbbe062016-08-23 15:41:05 +08006591 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006592 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006593
6594 break;
John Kessenich91cef522016-05-05 16:45:40 -06006595 default:
6596 logger->missingFunctionality("invocation operation");
6597 return spv::NoResult;
6598 }
Rex Xu51596642016-09-21 18:56:12 +08006599
6600 assert(opCode != spv::OpNop);
6601 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006602}
6603
Rex Xu2bbbe062016-08-23 15:41:05 +08006604// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006605spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6606 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006607{
6608 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6609 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006610 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006611 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006612 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6613 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6614 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
6615
6616 // Handle group invocation operations scalar by scalar.
6617 // The result type is the same type as the original type.
6618 // The algorithm is to:
6619 // - break the vector into scalars
6620 // - apply the operation to each scalar
6621 // - make a vector out the scalar results
6622
6623 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006624 int numComponents = builder.getNumComponents(operands[0]);
6625 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006626 std::vector<spv::Id> results;
6627
6628 // do each scalar op
6629 for (int comp = 0; comp < numComponents; ++comp) {
6630 std::vector<unsigned int> indexes;
6631 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006632 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6633 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006634 if (op == spv::OpSubgroupReadInvocationKHR) {
6635 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006636 spv::IdImmediate operand = { true, operands[1] };
6637 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006638 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006639 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6640 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006641 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006642 spv::IdImmediate operand = { true, operands[1] };
6643 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006644 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006645 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6646 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006647 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006648 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006649 spvGroupOperands.push_back(scalar);
6650 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006651
Rex Xub7072052016-09-26 15:53:40 +08006652 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006653 }
6654
6655 // put the pieces together
6656 return builder.createCompositeConstruct(typeId, results);
6657}
Rex Xu2bbbe062016-08-23 15:41:05 +08006658
John Kessenich66011cb2018-03-06 16:12:04 -07006659// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006660spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6661 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006662{
6663 // Add the required capabilities.
6664 switch (op) {
6665 case glslang::EOpSubgroupElect:
6666 builder.addCapability(spv::CapabilityGroupNonUniform);
6667 break;
6668 case glslang::EOpSubgroupAll:
6669 case glslang::EOpSubgroupAny:
6670 case glslang::EOpSubgroupAllEqual:
6671 builder.addCapability(spv::CapabilityGroupNonUniform);
6672 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6673 break;
6674 case glslang::EOpSubgroupBroadcast:
6675 case glslang::EOpSubgroupBroadcastFirst:
6676 case glslang::EOpSubgroupBallot:
6677 case glslang::EOpSubgroupInverseBallot:
6678 case glslang::EOpSubgroupBallotBitExtract:
6679 case glslang::EOpSubgroupBallotBitCount:
6680 case glslang::EOpSubgroupBallotInclusiveBitCount:
6681 case glslang::EOpSubgroupBallotExclusiveBitCount:
6682 case glslang::EOpSubgroupBallotFindLSB:
6683 case glslang::EOpSubgroupBallotFindMSB:
6684 builder.addCapability(spv::CapabilityGroupNonUniform);
6685 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6686 break;
6687 case glslang::EOpSubgroupShuffle:
6688 case glslang::EOpSubgroupShuffleXor:
6689 builder.addCapability(spv::CapabilityGroupNonUniform);
6690 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6691 break;
6692 case glslang::EOpSubgroupShuffleUp:
6693 case glslang::EOpSubgroupShuffleDown:
6694 builder.addCapability(spv::CapabilityGroupNonUniform);
6695 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6696 break;
6697 case glslang::EOpSubgroupAdd:
6698 case glslang::EOpSubgroupMul:
6699 case glslang::EOpSubgroupMin:
6700 case glslang::EOpSubgroupMax:
6701 case glslang::EOpSubgroupAnd:
6702 case glslang::EOpSubgroupOr:
6703 case glslang::EOpSubgroupXor:
6704 case glslang::EOpSubgroupInclusiveAdd:
6705 case glslang::EOpSubgroupInclusiveMul:
6706 case glslang::EOpSubgroupInclusiveMin:
6707 case glslang::EOpSubgroupInclusiveMax:
6708 case glslang::EOpSubgroupInclusiveAnd:
6709 case glslang::EOpSubgroupInclusiveOr:
6710 case glslang::EOpSubgroupInclusiveXor:
6711 case glslang::EOpSubgroupExclusiveAdd:
6712 case glslang::EOpSubgroupExclusiveMul:
6713 case glslang::EOpSubgroupExclusiveMin:
6714 case glslang::EOpSubgroupExclusiveMax:
6715 case glslang::EOpSubgroupExclusiveAnd:
6716 case glslang::EOpSubgroupExclusiveOr:
6717 case glslang::EOpSubgroupExclusiveXor:
6718 builder.addCapability(spv::CapabilityGroupNonUniform);
6719 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6720 break;
6721 case glslang::EOpSubgroupClusteredAdd:
6722 case glslang::EOpSubgroupClusteredMul:
6723 case glslang::EOpSubgroupClusteredMin:
6724 case glslang::EOpSubgroupClusteredMax:
6725 case glslang::EOpSubgroupClusteredAnd:
6726 case glslang::EOpSubgroupClusteredOr:
6727 case glslang::EOpSubgroupClusteredXor:
6728 builder.addCapability(spv::CapabilityGroupNonUniform);
6729 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6730 break;
6731 case glslang::EOpSubgroupQuadBroadcast:
6732 case glslang::EOpSubgroupQuadSwapHorizontal:
6733 case glslang::EOpSubgroupQuadSwapVertical:
6734 case glslang::EOpSubgroupQuadSwapDiagonal:
6735 builder.addCapability(spv::CapabilityGroupNonUniform);
6736 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6737 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006738 case glslang::EOpSubgroupPartitionedAdd:
6739 case glslang::EOpSubgroupPartitionedMul:
6740 case glslang::EOpSubgroupPartitionedMin:
6741 case glslang::EOpSubgroupPartitionedMax:
6742 case glslang::EOpSubgroupPartitionedAnd:
6743 case glslang::EOpSubgroupPartitionedOr:
6744 case glslang::EOpSubgroupPartitionedXor:
6745 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6746 case glslang::EOpSubgroupPartitionedInclusiveMul:
6747 case glslang::EOpSubgroupPartitionedInclusiveMin:
6748 case glslang::EOpSubgroupPartitionedInclusiveMax:
6749 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6750 case glslang::EOpSubgroupPartitionedInclusiveOr:
6751 case glslang::EOpSubgroupPartitionedInclusiveXor:
6752 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6753 case glslang::EOpSubgroupPartitionedExclusiveMul:
6754 case glslang::EOpSubgroupPartitionedExclusiveMin:
6755 case glslang::EOpSubgroupPartitionedExclusiveMax:
6756 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6757 case glslang::EOpSubgroupPartitionedExclusiveOr:
6758 case glslang::EOpSubgroupPartitionedExclusiveXor:
6759 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6760 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6761 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006762 default: assert(0 && "Unhandled subgroup operation!");
6763 }
6764
6765 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6766 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6767 const bool isBool = typeProxy == glslang::EbtBool;
6768
6769 spv::Op opCode = spv::OpNop;
6770
6771 // Figure out which opcode to use.
6772 switch (op) {
6773 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6774 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6775 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6776 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6777 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6778 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6779 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6780 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6781 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6782 case glslang::EOpSubgroupBallotBitCount:
6783 case glslang::EOpSubgroupBallotInclusiveBitCount:
6784 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6785 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6786 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6787 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6788 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6789 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6790 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6791 case glslang::EOpSubgroupAdd:
6792 case glslang::EOpSubgroupInclusiveAdd:
6793 case glslang::EOpSubgroupExclusiveAdd:
6794 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006795 case glslang::EOpSubgroupPartitionedAdd:
6796 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6797 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07006798 if (isFloat) {
6799 opCode = spv::OpGroupNonUniformFAdd;
6800 } else {
6801 opCode = spv::OpGroupNonUniformIAdd;
6802 }
6803 break;
6804 case glslang::EOpSubgroupMul:
6805 case glslang::EOpSubgroupInclusiveMul:
6806 case glslang::EOpSubgroupExclusiveMul:
6807 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006808 case glslang::EOpSubgroupPartitionedMul:
6809 case glslang::EOpSubgroupPartitionedInclusiveMul:
6810 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07006811 if (isFloat) {
6812 opCode = spv::OpGroupNonUniformFMul;
6813 } else {
6814 opCode = spv::OpGroupNonUniformIMul;
6815 }
6816 break;
6817 case glslang::EOpSubgroupMin:
6818 case glslang::EOpSubgroupInclusiveMin:
6819 case glslang::EOpSubgroupExclusiveMin:
6820 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006821 case glslang::EOpSubgroupPartitionedMin:
6822 case glslang::EOpSubgroupPartitionedInclusiveMin:
6823 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07006824 if (isFloat) {
6825 opCode = spv::OpGroupNonUniformFMin;
6826 } else if (isUnsigned) {
6827 opCode = spv::OpGroupNonUniformUMin;
6828 } else {
6829 opCode = spv::OpGroupNonUniformSMin;
6830 }
6831 break;
6832 case glslang::EOpSubgroupMax:
6833 case glslang::EOpSubgroupInclusiveMax:
6834 case glslang::EOpSubgroupExclusiveMax:
6835 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006836 case glslang::EOpSubgroupPartitionedMax:
6837 case glslang::EOpSubgroupPartitionedInclusiveMax:
6838 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07006839 if (isFloat) {
6840 opCode = spv::OpGroupNonUniformFMax;
6841 } else if (isUnsigned) {
6842 opCode = spv::OpGroupNonUniformUMax;
6843 } else {
6844 opCode = spv::OpGroupNonUniformSMax;
6845 }
6846 break;
6847 case glslang::EOpSubgroupAnd:
6848 case glslang::EOpSubgroupInclusiveAnd:
6849 case glslang::EOpSubgroupExclusiveAnd:
6850 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006851 case glslang::EOpSubgroupPartitionedAnd:
6852 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6853 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07006854 if (isBool) {
6855 opCode = spv::OpGroupNonUniformLogicalAnd;
6856 } else {
6857 opCode = spv::OpGroupNonUniformBitwiseAnd;
6858 }
6859 break;
6860 case glslang::EOpSubgroupOr:
6861 case glslang::EOpSubgroupInclusiveOr:
6862 case glslang::EOpSubgroupExclusiveOr:
6863 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006864 case glslang::EOpSubgroupPartitionedOr:
6865 case glslang::EOpSubgroupPartitionedInclusiveOr:
6866 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07006867 if (isBool) {
6868 opCode = spv::OpGroupNonUniformLogicalOr;
6869 } else {
6870 opCode = spv::OpGroupNonUniformBitwiseOr;
6871 }
6872 break;
6873 case glslang::EOpSubgroupXor:
6874 case glslang::EOpSubgroupInclusiveXor:
6875 case glslang::EOpSubgroupExclusiveXor:
6876 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006877 case glslang::EOpSubgroupPartitionedXor:
6878 case glslang::EOpSubgroupPartitionedInclusiveXor:
6879 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07006880 if (isBool) {
6881 opCode = spv::OpGroupNonUniformLogicalXor;
6882 } else {
6883 opCode = spv::OpGroupNonUniformBitwiseXor;
6884 }
6885 break;
6886 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6887 case glslang::EOpSubgroupQuadSwapHorizontal:
6888 case glslang::EOpSubgroupQuadSwapVertical:
6889 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6890 default: assert(0 && "Unhandled subgroup operation!");
6891 }
6892
John Kessenich149afc32018-08-14 13:31:43 -06006893 // get the right Group Operation
6894 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006895 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006896 default:
6897 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006898 case glslang::EOpSubgroupBallotBitCount:
6899 case glslang::EOpSubgroupAdd:
6900 case glslang::EOpSubgroupMul:
6901 case glslang::EOpSubgroupMin:
6902 case glslang::EOpSubgroupMax:
6903 case glslang::EOpSubgroupAnd:
6904 case glslang::EOpSubgroupOr:
6905 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006906 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006907 break;
6908 case glslang::EOpSubgroupBallotInclusiveBitCount:
6909 case glslang::EOpSubgroupInclusiveAdd:
6910 case glslang::EOpSubgroupInclusiveMul:
6911 case glslang::EOpSubgroupInclusiveMin:
6912 case glslang::EOpSubgroupInclusiveMax:
6913 case glslang::EOpSubgroupInclusiveAnd:
6914 case glslang::EOpSubgroupInclusiveOr:
6915 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006916 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006917 break;
6918 case glslang::EOpSubgroupBallotExclusiveBitCount:
6919 case glslang::EOpSubgroupExclusiveAdd:
6920 case glslang::EOpSubgroupExclusiveMul:
6921 case glslang::EOpSubgroupExclusiveMin:
6922 case glslang::EOpSubgroupExclusiveMax:
6923 case glslang::EOpSubgroupExclusiveAnd:
6924 case glslang::EOpSubgroupExclusiveOr:
6925 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006926 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006927 break;
6928 case glslang::EOpSubgroupClusteredAdd:
6929 case glslang::EOpSubgroupClusteredMul:
6930 case glslang::EOpSubgroupClusteredMin:
6931 case glslang::EOpSubgroupClusteredMax:
6932 case glslang::EOpSubgroupClusteredAnd:
6933 case glslang::EOpSubgroupClusteredOr:
6934 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006935 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006936 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006937 case glslang::EOpSubgroupPartitionedAdd:
6938 case glslang::EOpSubgroupPartitionedMul:
6939 case glslang::EOpSubgroupPartitionedMin:
6940 case glslang::EOpSubgroupPartitionedMax:
6941 case glslang::EOpSubgroupPartitionedAnd:
6942 case glslang::EOpSubgroupPartitionedOr:
6943 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006944 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006945 break;
6946 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6947 case glslang::EOpSubgroupPartitionedInclusiveMul:
6948 case glslang::EOpSubgroupPartitionedInclusiveMin:
6949 case glslang::EOpSubgroupPartitionedInclusiveMax:
6950 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6951 case glslang::EOpSubgroupPartitionedInclusiveOr:
6952 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006953 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006954 break;
6955 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6956 case glslang::EOpSubgroupPartitionedExclusiveMul:
6957 case glslang::EOpSubgroupPartitionedExclusiveMin:
6958 case glslang::EOpSubgroupPartitionedExclusiveMax:
6959 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6960 case glslang::EOpSubgroupPartitionedExclusiveOr:
6961 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006962 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006963 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006964 }
6965
John Kessenich149afc32018-08-14 13:31:43 -06006966 // build the instruction
6967 std::vector<spv::IdImmediate> spvGroupOperands;
6968
6969 // Every operation begins with the Execution Scope operand.
6970 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6971 spvGroupOperands.push_back(executionScope);
6972
6973 // Next, for all operations that use a Group Operation, push that as an operand.
6974 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006975 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006976 spvGroupOperands.push_back(groupOperand);
6977 }
6978
John Kessenich66011cb2018-03-06 16:12:04 -07006979 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006980 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6981 spv::IdImmediate operand = { true, *opIt };
6982 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006983 }
6984
6985 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006986 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006987 switch (op) {
6988 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006989 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6990 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6991 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6992 }
6993 if (directionId != spv::NoResult) {
6994 spv::IdImmediate direction = { true, directionId };
6995 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006996 }
6997
6998 return builder.createOp(opCode, typeId, spvGroupOperands);
6999}
7000
John Kessenich5e4b1242015-08-06 22:53:06 -06007001spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007002{
John Kessenich66011cb2018-03-06 16:12:04 -07007003 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7004 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007005
John Kessenich140f3df2015-06-26 16:58:36 -06007006 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007007 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007008 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007009 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007010 spv::Id typeId0 = 0;
7011 if (consumedOperands > 0)
7012 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007013 spv::Id typeId1 = 0;
7014 if (consumedOperands > 1)
7015 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007016 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007017
7018 switch (op) {
7019 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007020 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007021 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007022 else if (isUnsigned)
7023 libCall = spv::GLSLstd450UMin;
7024 else
7025 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007026 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007027 break;
7028 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007029 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007030 break;
7031 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007032 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007033 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007034 else if (isUnsigned)
7035 libCall = spv::GLSLstd450UMax;
7036 else
7037 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007038 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007039 break;
7040 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007041 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007042 break;
7043 case glslang::EOpDot:
7044 opCode = spv::OpDot;
7045 break;
7046 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007047 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007048 break;
7049
7050 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007051 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007052 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007053 else if (isUnsigned)
7054 libCall = spv::GLSLstd450UClamp;
7055 else
7056 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007057 builder.promoteScalar(precision, operands.front(), operands[1]);
7058 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007059 break;
7060 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007061 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7062 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007063 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007064 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007065 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007066 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007067 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007068 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007069 break;
7070 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007071 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007072 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007073 break;
7074 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007075 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007076 builder.promoteScalar(precision, operands[0], operands[2]);
7077 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007078 break;
7079
7080 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007081 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007082 break;
7083 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007084 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007085 break;
7086 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007087 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007088 break;
7089 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007090 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007091 break;
7092 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007093 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007094 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007095#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007096 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007097 if (typeProxy == glslang::EbtFloat16)
7098 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007099 libCall = spv::GLSLstd450InterpolateAtSample;
7100 break;
7101 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007102 if (typeProxy == glslang::EbtFloat16)
7103 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007104 libCall = spv::GLSLstd450InterpolateAtOffset;
7105 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007106 case glslang::EOpAddCarry:
7107 opCode = spv::OpIAddCarry;
7108 typeId = builder.makeStructResultType(typeId0, typeId0);
7109 consumedOperands = 2;
7110 break;
7111 case glslang::EOpSubBorrow:
7112 opCode = spv::OpISubBorrow;
7113 typeId = builder.makeStructResultType(typeId0, typeId0);
7114 consumedOperands = 2;
7115 break;
7116 case glslang::EOpUMulExtended:
7117 opCode = spv::OpUMulExtended;
7118 typeId = builder.makeStructResultType(typeId0, typeId0);
7119 consumedOperands = 2;
7120 break;
7121 case glslang::EOpIMulExtended:
7122 opCode = spv::OpSMulExtended;
7123 typeId = builder.makeStructResultType(typeId0, typeId0);
7124 consumedOperands = 2;
7125 break;
7126 case glslang::EOpBitfieldExtract:
7127 if (isUnsigned)
7128 opCode = spv::OpBitFieldUExtract;
7129 else
7130 opCode = spv::OpBitFieldSExtract;
7131 break;
7132 case glslang::EOpBitfieldInsert:
7133 opCode = spv::OpBitFieldInsert;
7134 break;
7135
7136 case glslang::EOpFma:
7137 libCall = spv::GLSLstd450Fma;
7138 break;
7139 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007140 {
7141 libCall = spv::GLSLstd450FrexpStruct;
7142 assert(builder.isPointerType(typeId1));
7143 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007144 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007145 if (width == 16)
7146 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7147 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007148 if (builder.getNumComponents(operands[0]) == 1)
7149 frexpIntType = builder.makeIntegerType(width, true);
7150 else
7151 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7152 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7153 consumedOperands = 1;
7154 }
John Kessenich55e7d112015-11-15 21:33:39 -07007155 break;
7156 case glslang::EOpLdexp:
7157 libCall = spv::GLSLstd450Ldexp;
7158 break;
7159
Rex Xu574ab042016-04-14 16:53:07 +08007160 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007161 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007162
John Kessenich66011cb2018-03-06 16:12:04 -07007163 case glslang::EOpSubgroupBroadcast:
7164 case glslang::EOpSubgroupBallotBitExtract:
7165 case glslang::EOpSubgroupShuffle:
7166 case glslang::EOpSubgroupShuffleXor:
7167 case glslang::EOpSubgroupShuffleUp:
7168 case glslang::EOpSubgroupShuffleDown:
7169 case glslang::EOpSubgroupClusteredAdd:
7170 case glslang::EOpSubgroupClusteredMul:
7171 case glslang::EOpSubgroupClusteredMin:
7172 case glslang::EOpSubgroupClusteredMax:
7173 case glslang::EOpSubgroupClusteredAnd:
7174 case glslang::EOpSubgroupClusteredOr:
7175 case glslang::EOpSubgroupClusteredXor:
7176 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007177 case glslang::EOpSubgroupPartitionedAdd:
7178 case glslang::EOpSubgroupPartitionedMul:
7179 case glslang::EOpSubgroupPartitionedMin:
7180 case glslang::EOpSubgroupPartitionedMax:
7181 case glslang::EOpSubgroupPartitionedAnd:
7182 case glslang::EOpSubgroupPartitionedOr:
7183 case glslang::EOpSubgroupPartitionedXor:
7184 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7185 case glslang::EOpSubgroupPartitionedInclusiveMul:
7186 case glslang::EOpSubgroupPartitionedInclusiveMin:
7187 case glslang::EOpSubgroupPartitionedInclusiveMax:
7188 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7189 case glslang::EOpSubgroupPartitionedInclusiveOr:
7190 case glslang::EOpSubgroupPartitionedInclusiveXor:
7191 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7192 case glslang::EOpSubgroupPartitionedExclusiveMul:
7193 case glslang::EOpSubgroupPartitionedExclusiveMin:
7194 case glslang::EOpSubgroupPartitionedExclusiveMax:
7195 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7196 case glslang::EOpSubgroupPartitionedExclusiveOr:
7197 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007198 return createSubgroupOperation(op, typeId, operands, typeProxy);
7199
Rex Xu9d93a232016-05-05 12:30:44 +08007200 case glslang::EOpSwizzleInvocations:
7201 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7202 libCall = spv::SwizzleInvocationsAMD;
7203 break;
7204 case glslang::EOpSwizzleInvocationsMasked:
7205 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7206 libCall = spv::SwizzleInvocationsMaskedAMD;
7207 break;
7208 case glslang::EOpWriteInvocation:
7209 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7210 libCall = spv::WriteInvocationAMD;
7211 break;
7212
7213 case glslang::EOpMin3:
7214 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7215 if (isFloat)
7216 libCall = spv::FMin3AMD;
7217 else {
7218 if (isUnsigned)
7219 libCall = spv::UMin3AMD;
7220 else
7221 libCall = spv::SMin3AMD;
7222 }
7223 break;
7224 case glslang::EOpMax3:
7225 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7226 if (isFloat)
7227 libCall = spv::FMax3AMD;
7228 else {
7229 if (isUnsigned)
7230 libCall = spv::UMax3AMD;
7231 else
7232 libCall = spv::SMax3AMD;
7233 }
7234 break;
7235 case glslang::EOpMid3:
7236 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7237 if (isFloat)
7238 libCall = spv::FMid3AMD;
7239 else {
7240 if (isUnsigned)
7241 libCall = spv::UMid3AMD;
7242 else
7243 libCall = spv::SMid3AMD;
7244 }
7245 break;
7246
7247 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007248 if (typeProxy == glslang::EbtFloat16)
7249 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007250 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7251 libCall = spv::InterpolateAtVertexAMD;
7252 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05007253 case glslang::EOpBarrier:
7254 {
7255 // This is for the extended controlBarrier function, with four operands.
7256 // The unextended barrier() goes through createNoArgOperation.
7257 assert(operands.size() == 4);
7258 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7259 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7260 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7261 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007262 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7263 spv::MemorySemanticsMakeVisibleKHRMask |
7264 spv::MemorySemanticsOutputMemoryKHRMask |
7265 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007266 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7267 }
7268 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7269 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7270 }
7271 return 0;
7272 }
7273 break;
7274 case glslang::EOpMemoryBarrier:
7275 {
7276 // This is for the extended memoryBarrier function, with three operands.
7277 // The unextended memoryBarrier() goes through createNoArgOperation.
7278 assert(operands.size() == 3);
7279 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7280 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7281 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007282 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7283 spv::MemorySemanticsMakeVisibleKHRMask |
7284 spv::MemorySemanticsOutputMemoryKHRMask |
7285 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007286 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7287 }
7288 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7289 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7290 }
7291 return 0;
7292 }
7293 break;
Chao Chen3c366992018-09-19 11:41:59 -07007294
Chao Chenb50c02e2018-09-19 11:42:24 -07007295 case glslang::EOpReportIntersectionNV:
7296 {
7297 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007298 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007299 }
7300 break;
7301 case glslang::EOpTraceNV:
7302 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007303 builder.createNoResultOp(spv::OpTraceNV, operands);
7304 return 0;
7305 }
7306 break;
7307 case glslang::EOpExecuteCallableNV:
7308 {
7309 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007310 return 0;
7311 }
7312 break;
Chao Chen3c366992018-09-19 11:41:59 -07007313 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7314 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7315 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007316 case glslang::EOpCooperativeMatrixMulAdd:
7317 opCode = spv::OpCooperativeMatrixMulAddNV;
7318 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007319#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007320 default:
7321 return 0;
7322 }
7323
7324 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007325 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007326 // Use an extended instruction from the standard library.
7327 // Construct the call arguments, without modifying the original operands vector.
7328 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7329 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007330 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007331 } else if (opCode == spv::OpDot && !isFloat) {
7332 // int dot(int, int)
7333 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7334 const int componentCount = builder.getNumComponents(operands[0]);
7335 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7336 builder.setPrecision(mulOp, precision);
7337 id = builder.createCompositeExtract(mulOp, typeId, 0);
7338 for (int i = 1; i < componentCount; ++i) {
7339 builder.setPrecision(id, precision);
7340 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7341 }
John Kessenich2359bd02015-12-06 19:29:11 -07007342 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007343 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007344 case 0:
7345 // should all be handled by visitAggregate and createNoArgOperation
7346 assert(0);
7347 return 0;
7348 case 1:
7349 // should all be handled by createUnaryOperation
7350 assert(0);
7351 return 0;
7352 case 2:
7353 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7354 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007355 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007356 // anything 3 or over doesn't have l-value operands, so all should be consumed
7357 assert(consumedOperands == operands.size());
7358 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007359 break;
7360 }
7361 }
7362
John Kessenich55e7d112015-11-15 21:33:39 -07007363 // Decode the return types that were structures
7364 switch (op) {
7365 case glslang::EOpAddCarry:
7366 case glslang::EOpSubBorrow:
7367 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7368 id = builder.createCompositeExtract(id, typeId0, 0);
7369 break;
7370 case glslang::EOpUMulExtended:
7371 case glslang::EOpIMulExtended:
7372 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7373 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7374 break;
7375 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007376 {
7377 assert(operands.size() == 2);
7378 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7379 // "exp" is floating-point type (from HLSL intrinsic)
7380 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7381 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7382 builder.createStore(member1, operands[1]);
7383 } else
7384 // "exp" is integer type (from GLSL built-in function)
7385 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7386 id = builder.createCompositeExtract(id, typeId0, 0);
7387 }
John Kessenich55e7d112015-11-15 21:33:39 -07007388 break;
7389 default:
7390 break;
7391 }
7392
John Kessenich32cfd492016-02-02 12:37:46 -07007393 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007394}
7395
Rex Xu9d93a232016-05-05 12:30:44 +08007396// Intrinsics with no arguments (or no return value, and no precision).
7397spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007398{
Jeff Bolz36831c92018-09-05 10:11:41 -05007399 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7400 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007401
7402 switch (op) {
John Kessenicha28f7a72019-08-06 07:00:58 -06007403#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007404 case glslang::EOpEmitVertex:
7405 builder.createNoResultOp(spv::OpEmitVertex);
7406 return 0;
7407 case glslang::EOpEndPrimitive:
7408 builder.createNoResultOp(spv::OpEndPrimitive);
7409 return 0;
7410 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007411 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007412 if (glslangIntermediate->usingVulkanMemoryModel()) {
7413 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7414 spv::MemorySemanticsOutputMemoryKHRMask |
7415 spv::MemorySemanticsAcquireReleaseMask);
7416 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7417 } else {
7418 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7419 }
John Kessenich82979362017-12-11 04:02:24 -07007420 } else {
7421 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7422 spv::MemorySemanticsWorkgroupMemoryMask |
7423 spv::MemorySemanticsAcquireReleaseMask);
7424 }
John Kessenich140f3df2015-06-26 16:58:36 -06007425 return 0;
7426 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007427 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7428 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007429 return 0;
7430 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007431 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7432 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007433 return 0;
7434 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007435 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7436 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007437 return 0;
7438 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007439 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7440 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007441 return 0;
7442 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007443 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7444 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007445 return 0;
7446 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007447 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7448 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007449 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007450 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007451 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007452 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007453 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007454 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007455 case glslang::EOpDeviceMemoryBarrier:
7456 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7457 spv::MemorySemanticsImageMemoryMask |
7458 spv::MemorySemanticsAcquireReleaseMask);
7459 return 0;
7460 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7461 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7462 spv::MemorySemanticsImageMemoryMask |
7463 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007464 return 0;
7465 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007466 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7467 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007468 return 0;
7469 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007470 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7471 spv::MemorySemanticsWorkgroupMemoryMask |
7472 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007473 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007474 case glslang::EOpSubgroupBarrier:
7475 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7476 spv::MemorySemanticsAcquireReleaseMask);
7477 return spv::NoResult;
7478 case glslang::EOpSubgroupMemoryBarrier:
7479 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7480 spv::MemorySemanticsAcquireReleaseMask);
7481 return spv::NoResult;
7482 case glslang::EOpSubgroupMemoryBarrierBuffer:
7483 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7484 spv::MemorySemanticsAcquireReleaseMask);
7485 return spv::NoResult;
7486 case glslang::EOpSubgroupMemoryBarrierImage:
7487 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7488 spv::MemorySemanticsAcquireReleaseMask);
7489 return spv::NoResult;
7490 case glslang::EOpSubgroupMemoryBarrierShared:
7491 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7492 spv::MemorySemanticsAcquireReleaseMask);
7493 return spv::NoResult;
7494 case glslang::EOpSubgroupElect: {
7495 std::vector<spv::Id> operands;
7496 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7497 }
Rex Xu9d93a232016-05-05 12:30:44 +08007498 case glslang::EOpTime:
7499 {
7500 std::vector<spv::Id> args; // Dummy arguments
7501 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7502 return builder.setPrecision(id, precision);
7503 }
Chao Chenb50c02e2018-09-19 11:42:24 -07007504 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007505 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007506 return 0;
7507 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007508 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007509 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007510
7511 case glslang::EOpBeginInvocationInterlock:
7512 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7513 return 0;
7514 case glslang::EOpEndInvocationInterlock:
7515 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7516 return 0;
7517
Jeff Bolzba6170b2019-07-01 09:23:23 -05007518 case glslang::EOpIsHelperInvocation:
7519 {
7520 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08007521 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
7522 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
7523 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05007524 }
7525
amhagan91fb0092019-07-10 21:14:38 -04007526 case glslang::EOpReadClockSubgroupKHR: {
7527 std::vector<spv::Id> args;
7528 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
7529 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7530 builder.addCapability(spv::CapabilityShaderClockKHR);
7531 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7532 }
7533
7534 case glslang::EOpReadClockDeviceKHR: {
7535 std::vector<spv::Id> args;
7536 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
7537 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7538 builder.addCapability(spv::CapabilityShaderClockKHR);
7539 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7540 }
John Kessenicha28f7a72019-08-06 07:00:58 -06007541#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007542 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007543 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007544 return 0;
7545 }
7546}
7547
7548spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7549{
John Kessenich2f273362015-07-18 22:34:27 -06007550 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007551 spv::Id id;
7552 if (symbolValues.end() != iter) {
7553 id = iter->second;
7554 return id;
7555 }
7556
7557 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06007558 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
7559 auto forcedType = getForcedType(builtIn, symbol->getType());
7560 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06007561 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06007562 if (forcedType.second != spv::NoType)
7563 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06007564
Rex Xuc884b4a2016-06-29 15:03:44 +08007565 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007566 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7567 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7568 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06007569#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007570 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7571#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007572 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007573 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007574 if (symbol->getQualifier().hasIndex())
7575 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7576 if (symbol->getQualifier().hasComponent())
7577 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007578 // atomic counters use this:
7579 if (symbol->getQualifier().hasOffset())
7580 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007581 }
7582
scygan2c864272016-05-18 18:09:17 +02007583 if (symbol->getQualifier().hasLocation())
7584 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007585 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007586 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007587 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007588 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007589 }
John Kessenich140f3df2015-06-26 16:58:36 -06007590 if (symbol->getQualifier().hasSet())
7591 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007592 else if (IsDescriptorResource(symbol->getType())) {
7593 // default to 0
7594 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7595 }
John Kessenich140f3df2015-06-26 16:58:36 -06007596 if (symbol->getQualifier().hasBinding())
7597 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007598 else if (IsDescriptorResource(symbol->getType())) {
7599 // default to 0
7600 builder.addDecoration(id, spv::DecorationBinding, 0);
7601 }
John Kessenich6c292d32016-02-15 20:58:50 -07007602 if (symbol->getQualifier().hasAttachment())
7603 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich7015bd62019-08-01 03:28:08 -06007604#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007605 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007606 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007607 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007608 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007609 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7610 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7611 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7612 }
7613 if (symbol->getQualifier().hasXfbOffset())
7614 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007615 }
John Kessenich7015bd62019-08-01 03:28:08 -06007616#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007617
Rex Xu1da878f2016-02-21 20:59:01 +08007618 if (symbol->getType().isImage()) {
7619 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007620 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007621 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007622 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007623 }
7624
John Kessenich9c14f772019-06-17 08:38:35 -06007625 // add built-in variable decoration
7626 if (builtIn != spv::BuiltInMax) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007627 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich9c14f772019-06-17 08:38:35 -06007628 }
John Kessenich140f3df2015-06-26 16:58:36 -06007629
John Kessenich5611c6d2018-04-05 11:25:02 -06007630 // nonuniform
7631 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7632
John Kessenicha28f7a72019-08-06 07:00:58 -06007633#ifndef GLSLANG_WEB
chaoc0ad6a4e2016-12-19 16:29:34 -08007634 if (builtIn == spv::BuiltInSampleMask) {
7635 spv::Decoration decoration;
7636 // GL_NV_sample_mask_override_coverage extension
7637 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007638 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007639 else
7640 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007641 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007642 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07007643 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08007644 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7645 }
7646 }
chaoc771d89f2017-01-13 01:10:53 -08007647 else if (builtIn == spv::BuiltInLayer) {
7648 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007649 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007650 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007651 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7652 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7653 }
John Kessenichb41bff62017-08-11 13:07:17 -06007654 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007655 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7656 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007657 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7658 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7659 }
7660 }
7661
chaoc6e5acae2016-12-20 13:28:52 -08007662 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007663 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007664 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007665 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7666 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007667 if (symbol->getQualifier().pervertexNV) {
7668 builder.addDecoration(id, spv::DecorationPerVertexNV);
7669 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7670 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7671 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007672#endif
7673
John Kessenich5d610ee2018-03-07 18:05:55 -07007674 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7675 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7676 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7677 symbol->getType().getQualifier().semanticName);
7678 }
7679
John Kessenich7015bd62019-08-01 03:28:08 -06007680 if (symbol->isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007681 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7682 }
7683
John Kessenich140f3df2015-06-26 16:58:36 -06007684 return id;
7685}
7686
John Kessenicha28f7a72019-08-06 07:00:58 -06007687#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007688// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7689void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7690{
7691 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007692 if (qualifier.perPrimitiveNV) {
7693 // Need to add capability/extension for fragment shader.
7694 // Mesh shader already adds this by default.
7695 if (glslangIntermediate->getStage() == EShLangFragment) {
7696 builder.addCapability(spv::CapabilityMeshShadingNV);
7697 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7698 }
Chao Chen3c366992018-09-19 11:41:59 -07007699 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007700 }
Chao Chen3c366992018-09-19 11:41:59 -07007701 if (qualifier.perViewNV)
7702 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7703 if (qualifier.perTaskNV)
7704 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7705 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007706 if (qualifier.perPrimitiveNV) {
7707 // Need to add capability/extension for fragment shader.
7708 // Mesh shader already adds this by default.
7709 if (glslangIntermediate->getStage() == EShLangFragment) {
7710 builder.addCapability(spv::CapabilityMeshShadingNV);
7711 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7712 }
Chao Chen3c366992018-09-19 11:41:59 -07007713 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007714 }
Chao Chen3c366992018-09-19 11:41:59 -07007715 if (qualifier.perViewNV)
7716 builder.addDecoration(id, spv::DecorationPerViewNV);
7717 if (qualifier.perTaskNV)
7718 builder.addDecoration(id, spv::DecorationPerTaskNV);
7719 }
7720}
7721#endif
7722
John Kessenich55e7d112015-11-15 21:33:39 -07007723// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007724// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007725//
7726// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7727//
7728// Recursively walk the nodes. The nodes form a tree whose leaves are
7729// regular constants, which themselves are trees that createSpvConstant()
7730// recursively walks. So, this function walks the "top" of the tree:
7731// - emit specialization constant-building instructions for specConstant
7732// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007733spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007734{
John Kessenich7cc0e282016-03-20 00:46:02 -06007735 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007736
qining4f4bb812016-04-03 23:55:17 -04007737 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007738 if (! node.getQualifier().specConstant) {
7739 // hand off to the non-spec-constant path
7740 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7741 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007742 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007743 nextConst, false);
7744 }
7745
7746 // We now know we have a specialization constant to build
7747
John Kessenichd94c0032016-05-30 19:29:40 -06007748 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007749 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7750 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7751 std::vector<spv::Id> dimConstId;
7752 for (int dim = 0; dim < 3; ++dim) {
7753 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7754 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007755 if (specConst) {
7756 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7757 glslangIntermediate->getLocalSizeSpecId(dim));
7758 }
qining4f4bb812016-04-03 23:55:17 -04007759 }
7760 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7761 }
7762
7763 // An AST node labelled as specialization constant should be a symbol node.
7764 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7765 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007766 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007767 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007768 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7769 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7770 // will set the builder into spec constant op instruction generating mode.
7771 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007772 result = accessChainLoad(sub_tree->getType());
7773 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007774 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007775 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007776 } else {
7777 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007778 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007779 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007780 builder.addName(result, sn->getName().c_str());
7781 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007782 }
qining4f4bb812016-04-03 23:55:17 -04007783
7784 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7785 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007786 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007787 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007788}
7789
John Kessenich140f3df2015-06-26 16:58:36 -06007790// Use 'consts' as the flattened glslang source of scalar constants to recursively
7791// build the aggregate SPIR-V constant.
7792//
7793// If there are not enough elements present in 'consts', 0 will be substituted;
7794// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7795//
qining08408382016-03-21 09:51:37 -04007796spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007797{
7798 // vector of constants for SPIR-V
7799 std::vector<spv::Id> spvConsts;
7800
7801 // Type is used for struct and array constants
7802 spv::Id typeId = convertGlslangToSpvType(glslangType);
7803
7804 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007805 glslang::TType elementType(glslangType, 0);
7806 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007807 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007808 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007809 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007810 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007811 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007812 } else if (glslangType.isCoopMat()) {
7813 glslang::TType componentType(glslangType.getBasicType());
7814 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007815 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007816 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7817 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007818 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007819 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007820 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7821 bool zero = nextConst >= consts.size();
7822 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06007823 case glslang::EbtInt:
7824 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7825 break;
7826 case glslang::EbtUint:
7827 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7828 break;
7829 case glslang::EbtFloat:
7830 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7831 break;
7832 case glslang::EbtBool:
7833 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7834 break;
7835#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07007836 case glslang::EbtInt8:
7837 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7838 break;
7839 case glslang::EbtUint8:
7840 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7841 break;
7842 case glslang::EbtInt16:
7843 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7844 break;
7845 case glslang::EbtUint16:
7846 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7847 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007848 case glslang::EbtInt64:
7849 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7850 break;
7851 case glslang::EbtUint64:
7852 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7853 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007854 case glslang::EbtDouble:
7855 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7856 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007857 case glslang::EbtFloat16:
7858 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7859 break;
John Kessenich39697cd2019-08-08 10:35:51 -06007860#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007861 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007862 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007863 break;
7864 }
7865 ++nextConst;
7866 }
7867 } else {
7868 // we have a non-aggregate (scalar) constant
7869 bool zero = nextConst >= consts.size();
7870 spv::Id scalar = 0;
7871 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06007872 case glslang::EbtInt:
7873 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
7874 break;
7875 case glslang::EbtUint:
7876 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
7877 break;
7878 case glslang::EbtFloat:
7879 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7880 break;
7881 case glslang::EbtBool:
7882 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
7883 break;
7884#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07007885 case glslang::EbtInt8:
7886 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7887 break;
7888 case glslang::EbtUint8:
7889 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7890 break;
7891 case glslang::EbtInt16:
7892 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7893 break;
7894 case glslang::EbtUint16:
7895 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7896 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007897 case glslang::EbtInt64:
7898 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7899 break;
7900 case glslang::EbtUint64:
7901 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7902 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007903 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007904 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007905 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007906 case glslang::EbtFloat16:
7907 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7908 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06007909 case glslang::EbtReference:
7910 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7911 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
7912 break;
John Kessenich39697cd2019-08-08 10:35:51 -06007913#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007914 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007915 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007916 break;
7917 }
7918 ++nextConst;
7919 return scalar;
7920 }
7921
7922 return builder.makeCompositeConstant(typeId, spvConsts);
7923}
7924
John Kessenich7c1aa102015-10-15 13:29:11 -06007925// Return true if the node is a constant or symbol whose reading has no
7926// non-trivial observable cost or effect.
7927bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7928{
7929 // don't know what this is
7930 if (node == nullptr)
7931 return false;
7932
7933 // a constant is safe
7934 if (node->getAsConstantUnion() != nullptr)
7935 return true;
7936
7937 // not a symbol means non-trivial
7938 if (node->getAsSymbolNode() == nullptr)
7939 return false;
7940
7941 // a symbol, depends on what's being read
7942 switch (node->getType().getQualifier().storage) {
7943 case glslang::EvqTemporary:
7944 case glslang::EvqGlobal:
7945 case glslang::EvqIn:
7946 case glslang::EvqInOut:
7947 case glslang::EvqConst:
7948 case glslang::EvqConstReadOnly:
7949 case glslang::EvqUniform:
7950 return true;
7951 default:
7952 return false;
7953 }
qining25262b32016-05-06 17:25:16 -04007954}
John Kessenich7c1aa102015-10-15 13:29:11 -06007955
7956// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007957// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007958// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007959// Return true if trivial.
7960bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7961{
7962 if (node == nullptr)
7963 return false;
7964
John Kessenich84cc15f2017-05-24 16:44:47 -06007965 // count non scalars as trivial, as well as anything coming from HLSL
7966 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007967 return true;
7968
John Kessenich7c1aa102015-10-15 13:29:11 -06007969 // symbols and constants are trivial
7970 if (isTrivialLeaf(node))
7971 return true;
7972
7973 // otherwise, it needs to be a simple operation or one or two leaf nodes
7974
7975 // not a simple operation
7976 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7977 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7978 if (binaryNode == nullptr && unaryNode == nullptr)
7979 return false;
7980
7981 // not on leaf nodes
7982 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7983 return false;
7984
7985 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7986 return false;
7987 }
7988
7989 switch (node->getAsOperator()->getOp()) {
7990 case glslang::EOpLogicalNot:
7991 case glslang::EOpConvIntToBool:
7992 case glslang::EOpConvUintToBool:
7993 case glslang::EOpConvFloatToBool:
7994 case glslang::EOpConvDoubleToBool:
7995 case glslang::EOpEqual:
7996 case glslang::EOpNotEqual:
7997 case glslang::EOpLessThan:
7998 case glslang::EOpGreaterThan:
7999 case glslang::EOpLessThanEqual:
8000 case glslang::EOpGreaterThanEqual:
8001 case glslang::EOpIndexDirect:
8002 case glslang::EOpIndexDirectStruct:
8003 case glslang::EOpLogicalXor:
8004 case glslang::EOpAny:
8005 case glslang::EOpAll:
8006 return true;
8007 default:
8008 return false;
8009 }
8010}
8011
8012// Emit short-circuiting code, where 'right' is never evaluated unless
8013// the left side is true (for &&) or false (for ||).
8014spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
8015{
8016 spv::Id boolTypeId = builder.makeBoolType();
8017
8018 // emit left operand
8019 builder.clearAccessChain();
8020 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008021 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008022
8023 // Operands to accumulate OpPhi operands
8024 std::vector<spv::Id> phiOperands;
8025 // accumulate left operand's phi information
8026 phiOperands.push_back(leftId);
8027 phiOperands.push_back(builder.getBuildPoint()->getId());
8028
8029 // Make the two kinds of operation symmetric with a "!"
8030 // || => emit "if (! left) result = right"
8031 // && => emit "if ( left) result = right"
8032 //
8033 // TODO: this runtime "not" for || could be avoided by adding functionality
8034 // to 'builder' to have an "else" without an "then"
8035 if (op == glslang::EOpLogicalOr)
8036 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8037
8038 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008039 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008040
8041 // emit right operand as the "then" part of the "if"
8042 builder.clearAccessChain();
8043 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008044 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008045
8046 // accumulate left operand's phi information
8047 phiOperands.push_back(rightId);
8048 phiOperands.push_back(builder.getBuildPoint()->getId());
8049
8050 // finish the "if"
8051 ifBuilder.makeEndIf();
8052
8053 // phi together the two results
8054 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8055}
8056
John Kessenicha28f7a72019-08-06 07:00:58 -06008057#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008058// Return type Id of the imported set of extended instructions corresponds to the name.
8059// Import this set if it has not been imported yet.
8060spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8061{
8062 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8063 return extBuiltinMap[name];
8064 else {
Rex Xu51596642016-09-21 18:56:12 +08008065 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008066 spv::Id extBuiltins = builder.import(name);
8067 extBuiltinMap[name] = extBuiltins;
8068 return extBuiltins;
8069 }
8070}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008071#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008072
John Kessenich140f3df2015-06-26 16:58:36 -06008073}; // end anonymous namespace
8074
8075namespace glslang {
8076
John Kessenich68d78fd2015-07-12 19:28:10 -06008077void GetSpirvVersion(std::string& version)
8078{
John Kessenich9e55f632015-07-15 10:03:39 -06008079 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008080 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008081 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008082 version = buf;
8083}
8084
John Kessenicha372a3e2017-11-02 22:32:14 -06008085// For low-order part of the generator's magic number. Bump up
8086// when there is a change in the style (e.g., if SSA form changes,
8087// or a different instruction sequence to do something gets used).
8088int GetSpirvGeneratorVersion()
8089{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008090 // return 1; // start
8091 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008092 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008093 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008094 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008095 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8096 // versions 4 and 6 each generate OpArrayLength as it has long been done
8097 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06008098}
8099
John Kessenich140f3df2015-06-26 16:58:36 -06008100// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008101void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008102{
8103 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008104 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008105 if (out.fail())
8106 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008107 for (int i = 0; i < (int)spirv.size(); ++i) {
8108 unsigned int word = spirv[i];
8109 out.write((const char*)&word, 4);
8110 }
8111 out.close();
8112}
8113
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008114// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008115void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008116{
8117 std::ofstream out;
8118 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008119 if (out.fail())
8120 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008121 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008122 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008123 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008124 if (varName != nullptr) {
8125 out << "\t #pragma once" << std::endl;
8126 out << "const uint32_t " << varName << "[] = {" << std::endl;
8127 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008128 const int WORDS_PER_LINE = 8;
8129 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8130 out << "\t";
8131 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8132 const unsigned int word = spirv[i + j];
8133 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8134 if (i + j + 1 < (int)spirv.size()) {
8135 out << ",";
8136 }
8137 }
8138 out << std::endl;
8139 }
Flavio15017db2017-02-15 14:29:33 -08008140 if (varName != nullptr) {
8141 out << "};";
8142 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008143 out.close();
8144}
8145
John Kessenich140f3df2015-06-26 16:58:36 -06008146//
8147// Set up the glslang traversal
8148//
John Kessenich4e11b612018-08-30 16:56:59 -06008149void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008150{
Lei Zhang17535f72016-05-04 15:55:59 -04008151 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008152 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008153}
8154
John Kessenich4e11b612018-08-30 16:56:59 -06008155void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008156 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008157{
John Kessenich140f3df2015-06-26 16:58:36 -06008158 TIntermNode* root = intermediate.getTreeRoot();
8159
8160 if (root == 0)
8161 return;
8162
John Kessenich4e11b612018-08-30 16:56:59 -06008163 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008164 if (options == nullptr)
8165 options = &defaultOptions;
8166
John Kessenich4e11b612018-08-30 16:56:59 -06008167 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008168
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008169 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008170 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008171 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008172 it.dumpSpv(spirv);
8173
GregFfb03a552018-03-29 11:49:14 -06008174#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008175 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8176 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008177 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8178 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008179 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008180 prelegalization = false;
8181 }
John Kessenich717c80a2018-08-23 15:17:10 -06008182
John Kessenich4e11b612018-08-30 16:56:59 -06008183 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008184 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008185
John Kessenich717c80a2018-08-23 15:17:10 -06008186 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008187 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008188
GregFcd1f1692017-09-21 18:40:22 -06008189#endif
8190
John Kessenich4e11b612018-08-30 16:56:59 -06008191 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008192}
8193
8194}; // end namespace glslang