blob: 4643c748134688dabe3fd235b8241e3bc3a1e761 [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);
Rex Xuce31aea2016-07-29 16:13:04 +08002115 else if (node->getBasicType() == glslang::EbtDouble)
2116 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002117 else if (node->getBasicType() == glslang::EbtFloat16)
2118 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002119 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2120 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002121 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2122 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002123 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2124 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08002125 else
2126 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002127 glslang::TOperator op;
2128 if (node->getOp() == glslang::EOpPreIncrement ||
2129 node->getOp() == glslang::EOpPostIncrement)
2130 op = glslang::EOpAdd;
2131 else
2132 op = glslang::EOpSub;
2133
John Kessenichead86222018-03-28 18:01:20 -06002134 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002135 convertGlslangToSpvType(node->getType()), operand, one,
2136 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002137 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002138
2139 // The result of operation is always stored, but conditionally the
2140 // consumed result. The consumed result is always an r-value.
2141 builder.accessChainStore(result);
2142 builder.clearAccessChain();
2143 if (node->getOp() == glslang::EOpPreIncrement ||
2144 node->getOp() == glslang::EOpPreDecrement)
2145 builder.setAccessChainRValue(result);
2146 else
2147 builder.setAccessChainRValue(operand);
2148 }
2149
2150 return false;
2151
2152 case glslang::EOpEmitStreamVertex:
2153 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2154 return false;
2155 case glslang::EOpEndStreamPrimitive:
2156 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2157 return false;
2158
2159 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002160 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002161 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002162 }
John Kessenich140f3df2015-06-26 16:58:36 -06002163}
2164
Jeff Bolz53134492019-06-25 13:31:10 -05002165// Construct a composite object, recursively copying members if their types don't match
2166spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2167{
2168 for (int c = 0; c < (int)constituents.size(); ++c) {
2169 spv::Id& constituent = constituents[c];
2170 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2171 spv::Id rType = builder.getTypeId(constituent);
2172 if (lType != rType) {
2173 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2174 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2175 } else if (builder.isStructType(rType)) {
2176 std::vector<spv::Id> rTypeConstituents;
2177 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2178 for (int i = 0; i < numrTypeConstituents; ++i) {
2179 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, builder.getContainedTypeId(rType, i), i));
2180 }
2181 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2182 } else {
2183 assert(builder.isArrayType(rType));
2184 std::vector<spv::Id> rTypeConstituents;
2185 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2186
2187 spv::Id elementRType = builder.getContainedTypeId(rType);
2188 for (int i = 0; i < numrTypeConstituents; ++i) {
2189 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2190 }
2191 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2192 }
2193 }
2194 }
2195 return builder.createCompositeConstruct(resultTypeId, constituents);
2196}
2197
John Kessenich140f3df2015-06-26 16:58:36 -06002198bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2199{
qining27e04a02016-04-14 16:40:20 -04002200 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2201 if (node->getType().getQualifier().isSpecConstant())
2202 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2203
John Kessenichfc51d282015-08-19 13:34:18 -06002204 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002205 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2206 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002207
2208 // try texturing
2209 result = createImageTextureFunctionCall(node);
2210 if (result != spv::NoResult) {
2211 builder.clearAccessChain();
2212 builder.setAccessChainRValue(result);
2213
2214 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002215 }
2216#ifndef GLSLANG_WEB
2217 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002218 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002219 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002220 // "imageStore" is a special case, which has no result
2221 return false;
2222 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002223#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002224
John Kessenich140f3df2015-06-26 16:58:36 -06002225 glslang::TOperator binOp = glslang::EOpNull;
2226 bool reduceComparison = true;
2227 bool isMatrix = false;
2228 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002229 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002230
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002231 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2232
John Kessenich140f3df2015-06-26 16:58:36 -06002233 assert(node->getOp());
2234
John Kessenichf6640762016-08-01 19:44:00 -06002235 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002236
2237 switch (node->getOp()) {
2238 case glslang::EOpSequence:
2239 {
2240 if (preVisit)
2241 ++sequenceDepth;
2242 else
2243 --sequenceDepth;
2244
2245 if (sequenceDepth == 1) {
2246 // If this is the parent node of all the functions, we want to see them
2247 // early, so all call points have actual SPIR-V functions to reference.
2248 // In all cases, still let the traverser visit the children for us.
2249 makeFunctions(node->getAsAggregate()->getSequence());
2250
John Kessenich6fccb3c2016-09-19 16:01:41 -06002251 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002252 // anything else gets there, so visit out of order, doing them all now.
2253 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2254
John Kessenich6a60c2f2016-12-08 21:01:59 -07002255 // 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 -06002256 // so do them manually.
2257 visitFunctions(node->getAsAggregate()->getSequence());
2258
2259 return false;
2260 }
2261
2262 return true;
2263 }
2264 case glslang::EOpLinkerObjects:
2265 {
2266 if (visit == glslang::EvPreVisit)
2267 linkageOnly = true;
2268 else
2269 linkageOnly = false;
2270
2271 return true;
2272 }
2273 case glslang::EOpComma:
2274 {
2275 // processing from left to right naturally leaves the right-most
2276 // lying around in the access chain
2277 glslang::TIntermSequence& glslangOperands = node->getSequence();
2278 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2279 glslangOperands[i]->traverse(this);
2280
2281 return false;
2282 }
2283 case glslang::EOpFunction:
2284 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002285 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002286 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002287 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002288 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002289 } else {
2290 handleFunctionEntry(node);
2291 }
2292 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002293 if (inEntryPoint)
2294 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002295 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002296 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002297 }
2298
2299 return true;
2300 case glslang::EOpParameters:
2301 // Parameters will have been consumed by EOpFunction processing, but not
2302 // the body, so we still visited the function node's children, making this
2303 // child redundant.
2304 return false;
2305 case glslang::EOpFunctionCall:
2306 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002307 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002308 if (node->isUserDefined())
2309 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002310 // 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 -07002311 if (result) {
2312 builder.clearAccessChain();
2313 builder.setAccessChainRValue(result);
2314 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002315 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002316
2317 return false;
2318 }
2319 case glslang::EOpConstructMat2x2:
2320 case glslang::EOpConstructMat2x3:
2321 case glslang::EOpConstructMat2x4:
2322 case glslang::EOpConstructMat3x2:
2323 case glslang::EOpConstructMat3x3:
2324 case glslang::EOpConstructMat3x4:
2325 case glslang::EOpConstructMat4x2:
2326 case glslang::EOpConstructMat4x3:
2327 case glslang::EOpConstructMat4x4:
2328 case glslang::EOpConstructDMat2x2:
2329 case glslang::EOpConstructDMat2x3:
2330 case glslang::EOpConstructDMat2x4:
2331 case glslang::EOpConstructDMat3x2:
2332 case glslang::EOpConstructDMat3x3:
2333 case glslang::EOpConstructDMat3x4:
2334 case glslang::EOpConstructDMat4x2:
2335 case glslang::EOpConstructDMat4x3:
2336 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002337 case glslang::EOpConstructIMat2x2:
2338 case glslang::EOpConstructIMat2x3:
2339 case glslang::EOpConstructIMat2x4:
2340 case glslang::EOpConstructIMat3x2:
2341 case glslang::EOpConstructIMat3x3:
2342 case glslang::EOpConstructIMat3x4:
2343 case glslang::EOpConstructIMat4x2:
2344 case glslang::EOpConstructIMat4x3:
2345 case glslang::EOpConstructIMat4x4:
2346 case glslang::EOpConstructUMat2x2:
2347 case glslang::EOpConstructUMat2x3:
2348 case glslang::EOpConstructUMat2x4:
2349 case glslang::EOpConstructUMat3x2:
2350 case glslang::EOpConstructUMat3x3:
2351 case glslang::EOpConstructUMat3x4:
2352 case glslang::EOpConstructUMat4x2:
2353 case glslang::EOpConstructUMat4x3:
2354 case glslang::EOpConstructUMat4x4:
2355 case glslang::EOpConstructBMat2x2:
2356 case glslang::EOpConstructBMat2x3:
2357 case glslang::EOpConstructBMat2x4:
2358 case glslang::EOpConstructBMat3x2:
2359 case glslang::EOpConstructBMat3x3:
2360 case glslang::EOpConstructBMat3x4:
2361 case glslang::EOpConstructBMat4x2:
2362 case glslang::EOpConstructBMat4x3:
2363 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002364 case glslang::EOpConstructF16Mat2x2:
2365 case glslang::EOpConstructF16Mat2x3:
2366 case glslang::EOpConstructF16Mat2x4:
2367 case glslang::EOpConstructF16Mat3x2:
2368 case glslang::EOpConstructF16Mat3x3:
2369 case glslang::EOpConstructF16Mat3x4:
2370 case glslang::EOpConstructF16Mat4x2:
2371 case glslang::EOpConstructF16Mat4x3:
2372 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002373 isMatrix = true;
2374 // fall through
2375 case glslang::EOpConstructFloat:
2376 case glslang::EOpConstructVec2:
2377 case glslang::EOpConstructVec3:
2378 case glslang::EOpConstructVec4:
2379 case glslang::EOpConstructDouble:
2380 case glslang::EOpConstructDVec2:
2381 case glslang::EOpConstructDVec3:
2382 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002383 case glslang::EOpConstructFloat16:
2384 case glslang::EOpConstructF16Vec2:
2385 case glslang::EOpConstructF16Vec3:
2386 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002387 case glslang::EOpConstructBool:
2388 case glslang::EOpConstructBVec2:
2389 case glslang::EOpConstructBVec3:
2390 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002391 case glslang::EOpConstructInt8:
2392 case glslang::EOpConstructI8Vec2:
2393 case glslang::EOpConstructI8Vec3:
2394 case glslang::EOpConstructI8Vec4:
2395 case glslang::EOpConstructUint8:
2396 case glslang::EOpConstructU8Vec2:
2397 case glslang::EOpConstructU8Vec3:
2398 case glslang::EOpConstructU8Vec4:
2399 case glslang::EOpConstructInt16:
2400 case glslang::EOpConstructI16Vec2:
2401 case glslang::EOpConstructI16Vec3:
2402 case glslang::EOpConstructI16Vec4:
2403 case glslang::EOpConstructUint16:
2404 case glslang::EOpConstructU16Vec2:
2405 case glslang::EOpConstructU16Vec3:
2406 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002407 case glslang::EOpConstructInt:
2408 case glslang::EOpConstructIVec2:
2409 case glslang::EOpConstructIVec3:
2410 case glslang::EOpConstructIVec4:
2411 case glslang::EOpConstructUint:
2412 case glslang::EOpConstructUVec2:
2413 case glslang::EOpConstructUVec3:
2414 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002415 case glslang::EOpConstructInt64:
2416 case glslang::EOpConstructI64Vec2:
2417 case glslang::EOpConstructI64Vec3:
2418 case glslang::EOpConstructI64Vec4:
2419 case glslang::EOpConstructUint64:
2420 case glslang::EOpConstructU64Vec2:
2421 case glslang::EOpConstructU64Vec3:
2422 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002423 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002424 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002425 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002426 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002427 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002428 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002429 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002430 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002431 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002432 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002433 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002434 else if (node->getOp() == glslang::EOpConstructStruct ||
2435 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2436 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002437 std::vector<spv::Id> constituents;
2438 for (int c = 0; c < (int)arguments.size(); ++c)
2439 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002440 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002441 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002442 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002443 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002444 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002445
2446 builder.clearAccessChain();
2447 builder.setAccessChainRValue(constructed);
2448
2449 return false;
2450 }
2451
2452 // These six are component-wise compares with component-wise results.
2453 // Forward on to createBinaryOperation(), requesting a vector result.
2454 case glslang::EOpLessThan:
2455 case glslang::EOpGreaterThan:
2456 case glslang::EOpLessThanEqual:
2457 case glslang::EOpGreaterThanEqual:
2458 case glslang::EOpVectorEqual:
2459 case glslang::EOpVectorNotEqual:
2460 {
2461 // Map the operation to a binary
2462 binOp = node->getOp();
2463 reduceComparison = false;
2464 switch (node->getOp()) {
2465 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2466 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2467 default: binOp = node->getOp(); break;
2468 }
2469
2470 break;
2471 }
2472 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002473 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002474 binOp = glslang::EOpMul;
2475 break;
2476 case glslang::EOpOuterProduct:
2477 // two vectors multiplied to make a matrix
2478 binOp = glslang::EOpOuterProduct;
2479 break;
2480 case glslang::EOpDot:
2481 {
qining25262b32016-05-06 17:25:16 -04002482 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002483 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002484 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002485 binOp = glslang::EOpMul;
2486 break;
2487 }
2488 case glslang::EOpMod:
2489 // when an aggregate, this is the floating-point mod built-in function,
2490 // which can be emitted by the one in createBinaryOperation()
2491 binOp = glslang::EOpMod;
2492 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002493
2494#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002495 case glslang::EOpEmitVertex:
2496 case glslang::EOpEndPrimitive:
2497 case glslang::EOpBarrier:
2498 case glslang::EOpMemoryBarrier:
2499 case glslang::EOpMemoryBarrierAtomicCounter:
2500 case glslang::EOpMemoryBarrierBuffer:
2501 case glslang::EOpMemoryBarrierImage:
2502 case glslang::EOpMemoryBarrierShared:
2503 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002504 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002505 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002506 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002507 case glslang::EOpWorkgroupMemoryBarrier:
2508 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002509 case glslang::EOpSubgroupBarrier:
2510 case glslang::EOpSubgroupMemoryBarrier:
2511 case glslang::EOpSubgroupMemoryBarrierBuffer:
2512 case glslang::EOpSubgroupMemoryBarrierImage:
2513 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002514 noReturnValue = true;
2515 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2516 break;
2517
Jeff Bolz36831c92018-09-05 10:11:41 -05002518 case glslang::EOpAtomicStore:
2519 noReturnValue = true;
2520 // fallthrough
2521 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002522 case glslang::EOpAtomicAdd:
2523 case glslang::EOpAtomicMin:
2524 case glslang::EOpAtomicMax:
2525 case glslang::EOpAtomicAnd:
2526 case glslang::EOpAtomicOr:
2527 case glslang::EOpAtomicXor:
2528 case glslang::EOpAtomicExchange:
2529 case glslang::EOpAtomicCompSwap:
2530 atomic = true;
2531 break;
2532
John Kessenich0d0c6d32017-07-23 16:08:26 -06002533 case glslang::EOpAtomicCounterAdd:
2534 case glslang::EOpAtomicCounterSubtract:
2535 case glslang::EOpAtomicCounterMin:
2536 case glslang::EOpAtomicCounterMax:
2537 case glslang::EOpAtomicCounterAnd:
2538 case glslang::EOpAtomicCounterOr:
2539 case glslang::EOpAtomicCounterXor:
2540 case glslang::EOpAtomicCounterExchange:
2541 case glslang::EOpAtomicCounterCompSwap:
2542 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2543 builder.addCapability(spv::CapabilityAtomicStorageOps);
2544 atomic = true;
2545 break;
2546
Chao Chenb50c02e2018-09-19 11:42:24 -07002547 case glslang::EOpIgnoreIntersectionNV:
2548 case glslang::EOpTerminateRayNV:
2549 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002550 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002551 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2552 noReturnValue = true;
2553 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002554 case glslang::EOpCooperativeMatrixLoad:
2555 case glslang::EOpCooperativeMatrixStore:
2556 noReturnValue = true;
2557 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002558 case glslang::EOpBeginInvocationInterlock:
2559 case glslang::EOpEndInvocationInterlock:
2560 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2561 noReturnValue = true;
2562 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002563#endif
Chao Chen3c366992018-09-19 11:41:59 -07002564
John Kessenich140f3df2015-06-26 16:58:36 -06002565 default:
2566 break;
2567 }
2568
2569 //
2570 // See if it maps to a regular operation.
2571 //
John Kessenich140f3df2015-06-26 16:58:36 -06002572 if (binOp != glslang::EOpNull) {
2573 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2574 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2575 assert(left && right);
2576
2577 builder.clearAccessChain();
2578 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002579 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002580
2581 builder.clearAccessChain();
2582 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002583 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002584
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002585 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002586 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002587 TranslateNoContractionDecoration(node->getType().getQualifier()),
2588 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002589 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002590 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002591 left->getType().getBasicType(), reduceComparison);
2592
2593 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002594 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002595 builder.clearAccessChain();
2596 builder.setAccessChainRValue(result);
2597
2598 return false;
2599 }
2600
John Kessenich426394d2015-07-23 10:22:48 -06002601 //
2602 // Create the list of operands.
2603 //
John Kessenich140f3df2015-06-26 16:58:36 -06002604 glslang::TIntermSequence& glslangOperands = node->getSequence();
2605 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002606 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002607 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002608 // special case l-value operands; there are just a few
2609 bool lvalue = false;
2610 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002611 case glslang::EOpModf:
2612 if (arg == 1)
2613 lvalue = true;
2614 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002615#ifndef GLSLANG_WEB
2616 case glslang::EOpFrexp:
2617 if (arg == 1)
2618 lvalue = true;
2619 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002620 case glslang::EOpInterpolateAtSample:
2621 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002622 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002623 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002624 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002625
2626 // Does it need a swizzle inversion? If so, evaluation is inverted;
2627 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002628 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002629 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2630 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2631 }
Rex Xu7a26c172015-12-08 17:12:09 +08002632 break;
Rex Xud4782c12015-09-06 16:30:11 +08002633 case glslang::EOpAtomicAdd:
2634 case glslang::EOpAtomicMin:
2635 case glslang::EOpAtomicMax:
2636 case glslang::EOpAtomicAnd:
2637 case glslang::EOpAtomicOr:
2638 case glslang::EOpAtomicXor:
2639 case glslang::EOpAtomicExchange:
2640 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002641 case glslang::EOpAtomicLoad:
2642 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002643 case glslang::EOpAtomicCounterAdd:
2644 case glslang::EOpAtomicCounterSubtract:
2645 case glslang::EOpAtomicCounterMin:
2646 case glslang::EOpAtomicCounterMax:
2647 case glslang::EOpAtomicCounterAnd:
2648 case glslang::EOpAtomicCounterOr:
2649 case glslang::EOpAtomicCounterXor:
2650 case glslang::EOpAtomicCounterExchange:
2651 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002652 if (arg == 0)
2653 lvalue = true;
2654 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002655 case glslang::EOpAddCarry:
2656 case glslang::EOpSubBorrow:
2657 if (arg == 2)
2658 lvalue = true;
2659 break;
2660 case glslang::EOpUMulExtended:
2661 case glslang::EOpIMulExtended:
2662 if (arg >= 2)
2663 lvalue = true;
2664 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002665 case glslang::EOpCooperativeMatrixLoad:
2666 if (arg == 0 || arg == 1)
2667 lvalue = true;
2668 break;
2669 case glslang::EOpCooperativeMatrixStore:
2670 if (arg == 1)
2671 lvalue = true;
2672 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002673#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002674 default:
2675 break;
2676 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002677 builder.clearAccessChain();
2678 if (invertedType != spv::NoType && arg == 0)
2679 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2680 else
2681 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002682
2683 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2684 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2685
2686 if (arg == 1) {
2687 // fold "element" parameter into the access chain
2688 spv::Builder::AccessChain save = builder.getAccessChain();
2689 builder.clearAccessChain();
2690 glslangOperands[2]->traverse(this);
2691
2692 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2693
2694 builder.setAccessChain(save);
2695
2696 // Point to the first element of the array.
2697 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002698 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002699
2700 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2701 unsigned int alignment = builder.getAccessChain().alignment;
2702
2703 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2704 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2705 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2706 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2707 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2708 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2709 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2710 }
2711
2712 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2713
2714 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2715 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2716 }
2717
2718 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2719 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2720 }
2721 } else if (arg == 2) {
2722 continue;
2723 }
2724 }
2725
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002726 if (lvalue) {
John Kessenich140f3df2015-06-26 16:58:36 -06002727 operands.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002728 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2729 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2730 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002731 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002732 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002733 }
John Kessenich140f3df2015-06-26 16:58:36 -06002734 }
John Kessenich426394d2015-07-23 10:22:48 -06002735
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002736 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002737 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2738 std::vector<spv::IdImmediate> idImmOps;
2739
2740 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2741 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2742 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2743 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2744 // get the pointee type
2745 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2746 assert(builder.isCooperativeMatrixType(typeId));
2747 // do the op
2748 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2749 // store the result to the pointer (out param 'm')
2750 builder.createStore(result, operands[0]);
2751 result = 0;
2752 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2753 std::vector<spv::IdImmediate> idImmOps;
2754
2755 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2756 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2757 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2758 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2759 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2760
2761 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2762 result = 0;
2763 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002764 // Handle all atomics
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002765 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
John Kessenich426394d2015-07-23 10:22:48 -06002766 } else {
2767 // Pass through to generic operations.
2768 switch (glslangOperands.size()) {
2769 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002770 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002771 break;
2772 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002773 {
2774 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002775 TranslateNoContractionDecoration(node->getType().getQualifier()),
2776 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002777 result = createUnaryOperation(
2778 node->getOp(), decorations,
2779 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002780 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06002781 }
John Kessenich426394d2015-07-23 10:22:48 -06002782 break;
2783 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002784 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002785 break;
2786 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002787 if (invertedType)
2788 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002789 }
2790
2791 if (noReturnValue)
2792 return false;
2793
2794 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002795 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002796 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002797 } else {
2798 builder.clearAccessChain();
2799 builder.setAccessChainRValue(result);
2800 return false;
2801 }
2802}
2803
John Kessenich433e9ff2017-01-26 20:31:11 -07002804// This path handles both if-then-else and ?:
2805// The if-then-else has a node type of void, while
2806// ?: has either a void or a non-void node type
2807//
2808// Leaving the result, when not void:
2809// GLSL only has r-values as the result of a :?, but
2810// if we have an l-value, that can be more efficient if it will
2811// become the base of a complex r-value expression, because the
2812// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002813bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2814{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002815 // see if OpSelect can handle it
2816 const auto isOpSelectable = [&]() {
2817 if (node->getBasicType() == glslang::EbtVoid)
2818 return false;
2819 // OpSelect can do all other types starting with SPV 1.4
2820 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2821 // pre-1.4, only scalars and vectors can be handled
2822 if ((!node->getType().isScalar() && !node->getType().isVector()))
2823 return false;
2824 }
2825 return true;
2826 };
2827
John Kessenich4bee5312018-02-20 21:29:05 -07002828 // See if it simple and safe, or required, to execute both sides.
2829 // Crucially, side effects must be either semantically required or avoided,
2830 // and there are performance trade-offs.
2831 // Return true if required or a good idea (and safe) to execute both sides,
2832 // false otherwise.
2833 const auto bothSidesPolicy = [&]() -> bool {
2834 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002835 if (node->getTrueBlock() == nullptr ||
2836 node->getFalseBlock() == nullptr)
2837 return false;
2838
John Kessenich4bee5312018-02-20 21:29:05 -07002839 // required? (unless we write additional code to look for side effects
2840 // and make performance trade-offs if none are present)
2841 if (!node->getShortCircuit())
2842 return true;
2843
2844 // if not required to execute both, decide based on performance/practicality...
2845
John Kessenich0c1e71a2019-01-10 18:23:06 +07002846 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002847 return false;
2848
John Kessenich433e9ff2017-01-26 20:31:11 -07002849 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2850 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2851
2852 // return true if a single operand to ? : is okay for OpSelect
2853 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002854 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002855 };
2856
2857 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2858 operandOkay(node->getFalseBlock()->getAsTyped());
2859 };
2860
John Kessenich4bee5312018-02-20 21:29:05 -07002861 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2862 // emit the condition before doing anything with selection
2863 node->getCondition()->traverse(this);
2864 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2865
2866 // Find a way of executing both sides and selecting the right result.
2867 const auto executeBothSides = [&]() -> void {
2868 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002869 node->getTrueBlock()->traverse(this);
2870 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2871 node->getFalseBlock()->traverse(this);
2872 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2873
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002874 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002875
John Kessenich4bee5312018-02-20 21:29:05 -07002876 // done if void
2877 if (node->getBasicType() == glslang::EbtVoid)
2878 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002879
John Kessenich4bee5312018-02-20 21:29:05 -07002880 // emit code to select between trueValue and falseValue
2881
2882 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002883 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002884 // Emit OpSelect for this selection.
2885
2886 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002887 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2888 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002889 condition = builder.smearScalar(spv::NoPrecision, condition,
2890 builder.makeVectorType(builder.makeBoolType(),
2891 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002892 }
John Kessenich4bee5312018-02-20 21:29:05 -07002893
2894 // OpSelect
2895 result = builder.createTriOp(spv::OpSelect,
2896 convertGlslangToSpvType(node->getType()), condition,
2897 trueValue, falseValue);
2898
2899 builder.clearAccessChain();
2900 builder.setAccessChainRValue(result);
2901 } else {
2902 // We need control flow to select the result.
2903 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2904 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2905
2906 // Selection control:
2907 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2908
2909 // make an "if" based on the value created by the condition
2910 spv::Builder::If ifBuilder(condition, control, builder);
2911
2912 // emit the "then" statement
2913 builder.createStore(trueValue, result);
2914 ifBuilder.makeBeginElse();
2915 // emit the "else" statement
2916 builder.createStore(falseValue, result);
2917
2918 // finish off the control flow
2919 ifBuilder.makeEndIf();
2920
2921 builder.clearAccessChain();
2922 builder.setAccessChainLValue(result);
2923 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002924 };
2925
John Kessenich4bee5312018-02-20 21:29:05 -07002926 // Execute the one side needed, as per the condition
2927 const auto executeOneSide = [&]() {
2928 // Always emit control flow.
2929 if (node->getBasicType() != glslang::EbtVoid)
2930 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002931
John Kessenich4bee5312018-02-20 21:29:05 -07002932 // Selection control:
2933 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2934
2935 // make an "if" based on the value created by the condition
2936 spv::Builder::If ifBuilder(condition, control, builder);
2937
2938 // emit the "then" statement
2939 if (node->getTrueBlock() != nullptr) {
2940 node->getTrueBlock()->traverse(this);
2941 if (result != spv::NoResult)
2942 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2943 }
2944
2945 if (node->getFalseBlock() != nullptr) {
2946 ifBuilder.makeBeginElse();
2947 // emit the "else" statement
2948 node->getFalseBlock()->traverse(this);
2949 if (result != spv::NoResult)
2950 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2951 }
2952
2953 // finish off the control flow
2954 ifBuilder.makeEndIf();
2955
2956 if (result != spv::NoResult) {
2957 builder.clearAccessChain();
2958 builder.setAccessChainLValue(result);
2959 }
2960 };
2961
2962 // Try for OpSelect (or a requirement to execute both sides)
2963 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002964 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2965 if (node->getType().getQualifier().isSpecConstant())
2966 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002967 executeBothSides();
2968 } else
2969 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002970
2971 return false;
2972}
2973
2974bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2975{
2976 // emit and get the condition before doing anything with switch
2977 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002978 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002979
Rex Xu57e65922017-07-04 23:23:40 +08002980 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002981 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002982
John Kessenich140f3df2015-06-26 16:58:36 -06002983 // browse the children to sort out code segments
2984 int defaultSegment = -1;
2985 std::vector<TIntermNode*> codeSegments;
2986 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2987 std::vector<int> caseValues;
2988 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2989 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2990 TIntermNode* child = *c;
2991 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002992 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002993 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002994 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002995 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2996 } else
2997 codeSegments.push_back(child);
2998 }
2999
qining25262b32016-05-06 17:25:16 -04003000 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003001 // statements between the last case and the end of the switch statement
3002 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3003 (int)codeSegments.size() == defaultSegment)
3004 codeSegments.push_back(nullptr);
3005
3006 // make the switch statement
3007 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08003008 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003009
3010 // emit all the code in the segments
3011 breakForLoop.push(false);
3012 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3013 builder.nextSwitchSegment(segmentBlocks, s);
3014 if (codeSegments[s])
3015 codeSegments[s]->traverse(this);
3016 else
3017 builder.addSwitchBreak();
3018 }
3019 breakForLoop.pop();
3020
3021 builder.endSwitch(segmentBlocks);
3022
3023 return false;
3024}
3025
3026void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3027{
3028 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003029 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003030
3031 builder.clearAccessChain();
3032 builder.setAccessChainRValue(constant);
3033}
3034
3035bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3036{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003037 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003038 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003039
3040 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003041 std::vector<unsigned int> operands;
3042 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003043
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003044 // Spec requires back edges to target header blocks, and every header block
3045 // must dominate its merge block. Make a header block first to ensure these
3046 // conditions are met. By definition, it will contain OpLoopMerge, followed
3047 // by a block-ending branch. But we don't want to put any other body/test
3048 // instructions in it, since the body/test may have arbitrary instructions,
3049 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003050 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003051 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003052 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003053 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003054 spv::Block& test = builder.makeNewBlock();
3055 builder.createBranch(&test);
3056
3057 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003058 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003059 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003060 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3061
3062 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003063 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003064 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003065 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003066 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003067 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003068
3069 builder.setBuildPoint(&blocks.continue_target);
3070 if (node->getTerminal())
3071 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003072 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003073 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003074 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003075 builder.createBranch(&blocks.body);
3076
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003077 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003078 builder.setBuildPoint(&blocks.body);
3079 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003080 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003081 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003082 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003083
3084 builder.setBuildPoint(&blocks.continue_target);
3085 if (node->getTerminal())
3086 node->getTerminal()->traverse(this);
3087 if (node->getTest()) {
3088 node->getTest()->traverse(this);
3089 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003090 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003091 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003092 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003093 // TODO: unless there was a break/return/discard instruction
3094 // somewhere in the body, this is an infinite loop, so we should
3095 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003096 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003097 }
John Kessenich140f3df2015-06-26 16:58:36 -06003098 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003099 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003100 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003101 return false;
3102}
3103
3104bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3105{
3106 if (node->getExpression())
3107 node->getExpression()->traverse(this);
3108
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003109 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003110
John Kessenich140f3df2015-06-26 16:58:36 -06003111 switch (node->getFlowOp()) {
3112 case glslang::EOpKill:
3113 builder.makeDiscard();
3114 break;
3115 case glslang::EOpBreak:
3116 if (breakForLoop.top())
3117 builder.createLoopExit();
3118 else
3119 builder.addSwitchBreak();
3120 break;
3121 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003122 builder.createLoopContinue();
3123 break;
3124 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003125 if (node->getExpression()) {
3126 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3127 spv::Id returnId = accessChainLoad(glslangReturnType);
3128 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3129 builder.clearAccessChain();
3130 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3131 builder.setAccessChainLValue(copyId);
3132 multiTypeStore(glslangReturnType, returnId);
3133 returnId = builder.createLoad(copyId);
3134 }
3135 builder.makeReturn(false, returnId);
3136 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003137 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003138
3139 builder.clearAccessChain();
3140 break;
3141
Jeff Bolzba6170b2019-07-01 09:23:23 -05003142 case glslang::EOpDemote:
3143 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3144 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3145 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3146 break;
3147
John Kessenich140f3df2015-06-26 16:58:36 -06003148 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003149 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003150 break;
3151 }
3152
3153 return false;
3154}
3155
John Kessenich9c14f772019-06-17 08:38:35 -06003156spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003157{
qining25262b32016-05-06 17:25:16 -04003158 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003159 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003160 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003161 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003162 spv::Id result = createSpvConstant(*node);
3163 if (result != spv::NoResult)
3164 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003165 }
3166
3167 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003168 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003169 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3170 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003171
Rex Xucabbb782017-03-24 13:41:14 +08003172 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
3173 node->getType().containsBasicType(glslang::EbtInt16) ||
3174 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08003175 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003176 switch (storageClass) {
3177 case spv::StorageClassInput:
3178 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07003179 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003180 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003181 break;
3182 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07003183 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003184 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06003185 break;
3186 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07003187 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003188 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3189 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003190 else
3191 builder.addCapability(spv::CapabilityStorageUniform16);
3192 break;
3193 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003194 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06003195 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
3196 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3197 break;
3198 default:
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003199 if (node->getType().containsBasicType(glslang::EbtFloat16))
3200 builder.addCapability(spv::CapabilityFloat16);
3201 if (node->getType().containsBasicType(glslang::EbtInt16) ||
3202 node->getType().containsBasicType(glslang::EbtUint16))
3203 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003204 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003205 }
3206 }
Rex Xuf89ad982017-04-07 23:22:33 +08003207
John Kessenich312dcfb2018-07-03 13:19:51 -06003208 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
3209 node->getType().containsBasicType(glslang::EbtUint8);
3210 if (contains8BitType) {
3211 if (storageClass == spv::StorageClassPushConstant) {
3212 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3213 builder.addCapability(spv::CapabilityStoragePushConstant8);
3214 } else if (storageClass == spv::StorageClassUniform) {
3215 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3216 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003217 } else if (storageClass == spv::StorageClassStorageBuffer) {
3218 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3219 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003220 } else {
3221 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003222 }
3223 }
3224
John Kessenich140f3df2015-06-26 16:58:36 -06003225 const char* name = node->getName().c_str();
3226 if (glslang::IsAnonymous(name))
3227 name = "";
3228
3229 return builder.createVariable(storageClass, spvType, name);
3230}
3231
3232// Return type Id of the sampled type.
3233spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3234{
3235 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003236 case glslang::EbtInt: return builder.makeIntType(32);
3237 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003238 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003239#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003240 case glslang::EbtFloat16:
3241 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3242 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3243 return builder.makeFloatType(16);
3244#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003245 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003246 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003247 return builder.makeFloatType(32);
3248 }
3249}
3250
John Kessenich8c8505c2016-07-26 12:50:38 -06003251// If node is a swizzle operation, return the type that should be used if
3252// the swizzle base is first consumed by another operation, before the swizzle
3253// is applied.
3254spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3255{
John Kessenichecba76f2017-01-06 00:34:48 -07003256 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003257 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3258 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3259 else
3260 return spv::NoType;
3261}
3262
3263// When inverting a swizzle with a parent op, this function
3264// will apply the swizzle operation to a completed parent operation.
3265spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3266{
3267 std::vector<unsigned> swizzle;
3268 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3269 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3270}
3271
John Kessenich8c8505c2016-07-26 12:50:38 -06003272// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3273void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3274{
3275 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3276 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3277 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3278}
3279
John Kessenich3ac051e2015-12-20 11:29:16 -07003280// Convert from a glslang type to an SPV type, by calling into a
3281// recursive version of this function. This establishes the inherited
3282// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003283spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003284{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003285 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003286}
3287
3288// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003289// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003290// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003291spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003292 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3293 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003294{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003295 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003296
3297 switch (type.getBasicType()) {
3298 case glslang::EbtVoid:
3299 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003300 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003301 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003302 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003303 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3304 // a 32-bit int where non-0 means true.
3305 if (explicitLayout != glslang::ElpNone)
3306 spvType = builder.makeUintType(32);
3307 else
3308 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003309 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003310 case glslang::EbtInt:
3311 spvType = builder.makeIntType(32);
3312 break;
3313 case glslang::EbtUint:
3314 spvType = builder.makeUintType(32);
3315 break;
3316 case glslang::EbtFloat:
3317 spvType = builder.makeFloatType(32);
3318 break;
3319#ifndef GLSLANG_WEB
3320 case glslang::EbtDouble:
3321 spvType = builder.makeFloatType(64);
3322 break;
3323 case glslang::EbtFloat16:
3324 spvType = builder.makeFloatType(16);
3325 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003326 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003327 spvType = builder.makeIntType(8);
3328 break;
3329 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003330 spvType = builder.makeUintType(8);
3331 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003332 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003333 spvType = builder.makeIntType(16);
3334 break;
3335 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003336 spvType = builder.makeUintType(16);
3337 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003338 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003339 spvType = builder.makeIntType(64);
3340 break;
3341 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003342 spvType = builder.makeUintType(64);
3343 break;
John Kessenich426394d2015-07-23 10:22:48 -06003344 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003345 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003346 spvType = builder.makeUintType(32);
3347 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003348 case glslang::EbtAccStructNV:
3349 spvType = builder.makeAccelerationStructureNVType();
3350 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003351 case glslang::EbtReference:
3352 {
3353 // Make the forward pointer, then recurse to convert the structure type, then
3354 // patch up the forward pointer with a real pointer type.
3355 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3356 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3357 forwardPointers[type.getReferentType()] = forwardId;
3358 }
3359 spvType = forwardPointers[type.getReferentType()];
3360 if (!forwardReferenceOnly) {
3361 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3362 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3363 forwardPointers[type.getReferentType()],
3364 referentType);
3365 }
3366 }
3367 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003368#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003369 case glslang::EbtSampler:
3370 {
3371 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003372 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003373 spvType = builder.makeSamplerType();
3374 } else {
3375 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003376 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3377 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3378 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3379 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003380 // already has both image and sampler, make the combined type
3381 spvType = builder.makeSampledImageType(spvType);
3382 }
John Kessenich55e7d112015-11-15 21:33:39 -07003383 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003384 }
John Kessenich140f3df2015-06-26 16:58:36 -06003385 break;
3386 case glslang::EbtStruct:
3387 case glslang::EbtBlock:
3388 {
3389 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003390 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003391
3392 // Try to share structs for different layouts, but not yet for other
3393 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003394 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003395 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003396 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003397 break;
3398
3399 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003400 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003401 memberRemapper[glslangMembers].resize(glslangMembers->size());
3402 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003403 }
3404 break;
3405 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003406 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003407 break;
3408 }
3409
3410 if (type.isMatrix())
3411 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3412 else {
3413 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3414 if (type.getVectorSize() > 1)
3415 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3416 }
3417
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003418 if (type.isCoopMat()) {
3419 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3420 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3421 if (type.getBasicType() == glslang::EbtFloat16)
3422 builder.addCapability(spv::CapabilityFloat16);
3423
3424 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3425 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3426 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3427
3428 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3429 }
3430
John Kessenich140f3df2015-06-26 16:58:36 -06003431 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003432 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3433
John Kessenichc9a80832015-09-12 12:17:44 -06003434 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003435 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003436 // We need to decorate array strides for types needing explicit layout, except blocks.
3437 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003438 // Use a dummy glslang type for querying internal strides of
3439 // arrays of arrays, but using just a one-dimensional array.
3440 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003441 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3442 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003443
3444 // Will compute the higher-order strides here, rather than making a whole
3445 // pile of types and doing repetitive recursion on their contents.
3446 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3447 }
John Kessenichf8842e52016-01-04 19:22:56 -07003448
3449 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003450 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003451 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003452 if (stride > 0)
3453 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003454 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003455 }
3456 } else {
3457 // single-dimensional array, and don't yet have stride
3458
John Kessenichf8842e52016-01-04 19:22:56 -07003459 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003460 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3461 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003462 }
John Kessenich31ed4832015-09-09 17:51:38 -06003463
John Kessenichead86222018-03-28 18:01:20 -06003464 // Do the outer dimension, which might not be known for a runtime-sized array.
3465 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3466 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003467 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003468 else {
3469 if (!lastBufferBlockMember) {
3470 builder.addExtension("SPV_EXT_descriptor_indexing");
3471 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3472 }
John Kessenichead86222018-03-28 18:01:20 -06003473 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003474 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003475 if (stride > 0)
3476 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003477 }
3478
3479 return spvType;
3480}
3481
John Kessenich0e737842017-03-24 18:38:16 -06003482// TODO: this functionality should exist at a higher level, in creating the AST
3483//
3484// Identify interface members that don't have their required extension turned on.
3485//
3486bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3487{
John Kessenicha28f7a72019-08-06 07:00:58 -06003488#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003489 auto& extensions = glslangIntermediate->getRequestedExtensions();
3490
Rex Xubcf291a2017-03-29 23:01:36 +08003491 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3492 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3493 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003494 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3495 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3496 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003497
3498 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3499 if (member.getFieldName() == "gl_ViewportMask" &&
3500 extensions.find("GL_NV_viewport_array2") == extensions.end())
3501 return true;
3502 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3503 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3504 return true;
3505 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3506 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3507 return true;
3508 }
3509#endif
John Kessenich0e737842017-03-24 18:38:16 -06003510
3511 return false;
3512};
3513
John Kessenich6090df02016-06-30 21:18:02 -06003514// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3515// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3516// Mutually recursive with convertGlslangToSpvType().
3517spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3518 const glslang::TTypeList* glslangMembers,
3519 glslang::TLayoutPacking explicitLayout,
3520 const glslang::TQualifier& qualifier)
3521{
3522 // Create a vector of struct types for SPIR-V to consume
3523 std::vector<spv::Id> spvMembers;
3524 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 -06003525 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003526 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3527 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3528 if (glslangMember.hiddenMember()) {
3529 ++memberDelta;
3530 if (type.getBasicType() == glslang::EbtBlock)
3531 memberRemapper[glslangMembers][i] = -1;
3532 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003533 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003534 if (filterMember(glslangMember)) {
3535 memberDelta++;
3536 memberRemapper[glslangMembers][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003537 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003538 }
3539 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003540 }
John Kessenich6090df02016-06-30 21:18:02 -06003541 // modify just this child's view of the qualifier
3542 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3543 InheritQualifiers(memberQualifier, qualifier);
3544
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003545 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003546 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003547 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003548
3549 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003550 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3551 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003552
3553 // Make forward pointers for any pointer members, and create a list of members to
3554 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003555 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003556 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3557 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3558 }
3559 spvMembers.push_back(
3560 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3561 } else {
3562 spvMembers.push_back(
3563 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3564 }
John Kessenich6090df02016-06-30 21:18:02 -06003565 }
3566 }
3567
3568 // Make the SPIR-V type
3569 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003570 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003571 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3572
3573 // Decorate it
3574 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3575
John Kessenichd72f4882019-01-16 14:55:37 +07003576 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003577 auto it = deferredForwardPointers[i];
3578 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3579 }
3580
John Kessenich6090df02016-06-30 21:18:02 -06003581 return spvType;
3582}
3583
3584void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3585 const glslang::TTypeList* glslangMembers,
3586 glslang::TLayoutPacking explicitLayout,
3587 const glslang::TQualifier& qualifier,
3588 spv::Id spvType)
3589{
3590 // Name and decorate the non-hidden members
3591 int offset = -1;
3592 int locationOffset = 0; // for use within the members of this struct
3593 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3594 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3595 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003596 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003597 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003598 if (filterMember(glslangMember))
3599 continue;
3600 }
John Kessenich6090df02016-06-30 21:18:02 -06003601
3602 // modify just this child's view of the qualifier
3603 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3604 InheritQualifiers(memberQualifier, qualifier);
3605
3606 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003607 if (member < 0)
3608 continue;
3609
3610 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3611 builder.addMemberDecoration(spvType, member,
3612 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3613 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3614 // Add interpolation and auxiliary storage decorations only to
3615 // top-level members of Input and Output storage classes
3616 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3617 type.getQualifier().storage == glslang::EvqVaryingOut) {
3618 if (type.getBasicType() == glslang::EbtBlock ||
3619 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3620 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3621 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003622#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003623 addMeshNVDecoration(spvType, member, memberQualifier);
3624#endif
John Kessenich6090df02016-06-30 21:18:02 -06003625 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003626 }
3627 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003628
John Kessenich5d610ee2018-03-07 18:05:55 -07003629 if (type.getBasicType() == glslang::EbtBlock &&
3630 qualifier.storage == glslang::EvqBuffer) {
3631 // Add memory decorations only to top-level members of shader storage block
3632 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003633 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003634 for (unsigned int i = 0; i < memory.size(); ++i)
3635 builder.addMemberDecoration(spvType, member, memory[i]);
3636 }
John Kessenich6090df02016-06-30 21:18:02 -06003637
John Kessenich5d610ee2018-03-07 18:05:55 -07003638 // Location assignment was already completed correctly by the front end,
3639 // just track whether a member needs to be decorated.
3640 // Ignore member locations if the container is an array, as that's
3641 // ill-specified and decisions have been made to not allow this.
3642 if (! type.isArray() && memberQualifier.hasLocation())
3643 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003644
John Kessenich5d610ee2018-03-07 18:05:55 -07003645 if (qualifier.hasLocation()) // track for upcoming inheritance
3646 locationOffset += glslangIntermediate->computeTypeLocationSize(
3647 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003648
John Kessenich5d610ee2018-03-07 18:05:55 -07003649 // component, XFB, others
3650 if (glslangMember.getQualifier().hasComponent())
3651 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3652 glslangMember.getQualifier().layoutComponent);
3653 if (glslangMember.getQualifier().hasXfbOffset())
3654 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3655 glslangMember.getQualifier().layoutXfbOffset);
3656 else if (explicitLayout != glslang::ElpNone) {
3657 // figure out what to do with offset, which is accumulating
3658 int nextOffset;
3659 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3660 if (offset >= 0)
3661 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3662 offset = nextOffset;
3663 }
John Kessenich6090df02016-06-30 21:18:02 -06003664
John Kessenich5d610ee2018-03-07 18:05:55 -07003665 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3666 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3667 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003668
John Kessenich5d610ee2018-03-07 18:05:55 -07003669 // built-in variable decorations
3670 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3671 if (builtIn != spv::BuiltInMax)
3672 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003673
John Kessenich5611c6d2018-04-05 11:25:02 -06003674 // nonuniform
3675 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3676
John Kessenichead86222018-03-28 18:01:20 -06003677 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3678 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3679 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3680 memberQualifier.semanticName);
3681 }
3682
John Kessenicha28f7a72019-08-06 07:00:58 -06003683#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003684 if (builtIn == spv::BuiltInLayer) {
3685 // SPV_NV_viewport_array2 extension
3686 if (glslangMember.getQualifier().layoutViewportRelative){
3687 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3688 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3689 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003690 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003691 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3692 builder.addMemberDecoration(spvType, member,
3693 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3694 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3695 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3696 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003697 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003698 }
3699 if (glslangMember.getQualifier().layoutPassthrough) {
3700 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3701 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3702 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3703 }
chaoc771d89f2017-01-13 01:10:53 -08003704#endif
John Kessenich6090df02016-06-30 21:18:02 -06003705 }
3706
3707 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003708 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3709 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003710}
3711
John Kessenich6c292d32016-02-15 20:58:50 -07003712// Turn the expression forming the array size into an id.
3713// This is not quite trivial, because of specialization constants.
3714// Sometimes, a raw constant is turned into an Id, and sometimes
3715// a specialization constant expression is.
3716spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3717{
3718 // First, see if this is sized with a node, meaning a specialization constant:
3719 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3720 if (specNode != nullptr) {
3721 builder.clearAccessChain();
3722 specNode->traverse(this);
3723 return accessChainLoad(specNode->getAsTyped()->getType());
3724 }
qining25262b32016-05-06 17:25:16 -04003725
John Kessenich6c292d32016-02-15 20:58:50 -07003726 // Otherwise, need a compile-time (front end) size, get it:
3727 int size = arraySizes.getDimSize(dim);
3728 assert(size > 0);
3729 return builder.makeUintConstant(size);
3730}
3731
John Kessenich103bef92016-02-08 21:38:15 -07003732// Wrap the builder's accessChainLoad to:
3733// - localize handling of RelaxedPrecision
3734// - use the SPIR-V inferred type instead of another conversion of the glslang type
3735// (avoids unnecessary work and possible type punning for structures)
3736// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003737spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3738{
John Kessenich103bef92016-02-08 21:38:15 -07003739 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003740
3741 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3742 coherentFlags |= TranslateCoherent(type);
3743
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003744 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003745 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003746
John Kessenich5611c6d2018-04-05 11:25:02 -06003747 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003748 TranslateNonUniformDecoration(type.getQualifier()),
3749 nominalTypeId,
3750 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003751 TranslateMemoryScope(coherentFlags),
3752 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003753
3754 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003755 if (type.getBasicType() == glslang::EbtBool) {
3756 if (builder.isScalarType(nominalTypeId)) {
3757 // Conversion for bool
3758 spv::Id boolType = builder.makeBoolType();
3759 if (nominalTypeId != boolType)
3760 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3761 } else if (builder.isVectorType(nominalTypeId)) {
3762 // Conversion for bvec
3763 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3764 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3765 if (nominalTypeId != bvecType)
3766 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3767 }
3768 }
John Kessenich103bef92016-02-08 21:38:15 -07003769
3770 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003771}
3772
Rex Xu27253232016-02-23 17:51:09 +08003773// Wrap the builder's accessChainStore to:
3774// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003775//
3776// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003777void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3778{
3779 // Need to convert to abstract types when necessary
3780 if (type.getBasicType() == glslang::EbtBool) {
3781 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3782
3783 if (builder.isScalarType(nominalTypeId)) {
3784 // Conversion for bool
3785 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003786 if (nominalTypeId != boolType) {
3787 // keep these outside arguments, for determinant order-of-evaluation
3788 spv::Id one = builder.makeUintConstant(1);
3789 spv::Id zero = builder.makeUintConstant(0);
3790 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3791 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003792 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003793 } else if (builder.isVectorType(nominalTypeId)) {
3794 // Conversion for bvec
3795 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3796 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003797 if (nominalTypeId != bvecType) {
3798 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003799 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3800 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3801 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003802 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003803 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3804 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003805 }
3806 }
3807
Jeff Bolz36831c92018-09-05 10:11:41 -05003808 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3809 coherentFlags |= TranslateCoherent(type);
3810
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003811 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003812 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003813
Jeff Bolz36831c92018-09-05 10:11:41 -05003814 builder.accessChainStore(rvalue,
3815 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003816 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003817}
3818
John Kessenich4bf71552016-09-02 11:20:21 -06003819// For storing when types match at the glslang level, but not might match at the
3820// SPIR-V level.
3821//
3822// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003823// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003824// as in a member-decorated way.
3825//
3826// NOTE: This function can handle any store request; if it's not special it
3827// simplifies to a simple OpStore.
3828//
3829// Implicitly uses the existing builder.accessChain as the storage target.
3830void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3831{
John Kessenichb3e24e42016-09-11 12:33:43 -06003832 // we only do the complex path here if it's an aggregate
3833 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003834 accessChainStore(type, rValue);
3835 return;
3836 }
3837
John Kessenichb3e24e42016-09-11 12:33:43 -06003838 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003839 spv::Id rType = builder.getTypeId(rValue);
3840 spv::Id lValue = builder.accessChainGetLValue();
3841 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3842 if (lType == rType) {
3843 accessChainStore(type, rValue);
3844 return;
3845 }
3846
John Kessenichb3e24e42016-09-11 12:33:43 -06003847 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003848 // where the two types were the same type in GLSL. This requires member
3849 // by member copy, recursively.
3850
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003851 // SPIR-V 1.4 added an instruction to do help do this.
3852 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3853 // However, bool in uniform space is changed to int, so
3854 // OpCopyLogical does not work for that.
3855 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3856 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3857 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3858 if (lBool == rBool) {
3859 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3860 accessChainStore(type, logicalCopy);
3861 return;
3862 }
3863 }
3864
John Kessenichb3e24e42016-09-11 12:33:43 -06003865 // If an array, copy element by element.
3866 if (type.isArray()) {
3867 glslang::TType glslangElementType(type, 0);
3868 spv::Id elementRType = builder.getContainedTypeId(rType);
3869 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3870 // get the source member
3871 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003872
John Kessenichb3e24e42016-09-11 12:33:43 -06003873 // set up the target storage
3874 builder.clearAccessChain();
3875 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003876 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003877
John Kessenichb3e24e42016-09-11 12:33:43 -06003878 // store the member
3879 multiTypeStore(glslangElementType, elementRValue);
3880 }
3881 } else {
3882 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003883
John Kessenichb3e24e42016-09-11 12:33:43 -06003884 // loop over structure members
3885 const glslang::TTypeList& members = *type.getStruct();
3886 for (int m = 0; m < (int)members.size(); ++m) {
3887 const glslang::TType& glslangMemberType = *members[m].type;
3888
3889 // get the source member
3890 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3891 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3892
3893 // set up the target storage
3894 builder.clearAccessChain();
3895 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003896 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003897
3898 // store the member
3899 multiTypeStore(glslangMemberType, memberRValue);
3900 }
John Kessenich4bf71552016-09-02 11:20:21 -06003901 }
3902}
3903
John Kessenichf85e8062015-12-19 13:57:10 -07003904// Decide whether or not this type should be
3905// decorated with offsets and strides, and if so
3906// whether std140 or std430 rules should be applied.
3907glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003908{
John Kessenichf85e8062015-12-19 13:57:10 -07003909 // has to be a block
3910 if (type.getBasicType() != glslang::EbtBlock)
3911 return glslang::ElpNone;
3912
Chao Chen3c366992018-09-19 11:41:59 -07003913 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003914 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003915 type.getQualifier().storage != glslang::EvqBuffer &&
3916 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003917 return glslang::ElpNone;
3918
3919 // return the layout to use
3920 switch (type.getQualifier().layoutPacking) {
3921 case glslang::ElpStd140:
3922 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003923 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003924 return type.getQualifier().layoutPacking;
3925 default:
3926 return glslang::ElpNone;
3927 }
John Kessenich31ed4832015-09-09 17:51:38 -06003928}
3929
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003930// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003931int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003932{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003933 int size;
John Kessenich49987892015-12-29 17:11:44 -07003934 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003935 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003936
3937 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003938}
3939
John Kessenich49987892015-12-29 17:11:44 -07003940// 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 -07003941// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003942int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003943{
John Kessenich49987892015-12-29 17:11:44 -07003944 glslang::TType elementType;
3945 elementType.shallowCopy(matrixType);
3946 elementType.clearArraySizes();
3947
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003948 int size;
John Kessenich49987892015-12-29 17:11:44 -07003949 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003950 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003951
3952 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003953}
3954
John Kessenich5e4b1242015-08-06 22:53:06 -06003955// Given a member type of a struct, realign the current offset for it, and compute
3956// the next (not yet aligned) offset for the next member, which will get aligned
3957// on the next call.
3958// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3959// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3960// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003961void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003962 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003963{
3964 // this will get a positive value when deemed necessary
3965 nextOffset = -1;
3966
John Kessenich5e4b1242015-08-06 22:53:06 -06003967 // override anything in currentOffset with user-set offset
3968 if (memberType.getQualifier().hasOffset())
3969 currentOffset = memberType.getQualifier().layoutOffset;
3970
3971 // It could be that current linker usage in glslang updated all the layoutOffset,
3972 // in which case the following code does not matter. But, that's not quite right
3973 // once cross-compilation unit GLSL validation is done, as the original user
3974 // settings are needed in layoutOffset, and then the following will come into play.
3975
John Kessenichf85e8062015-12-19 13:57:10 -07003976 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003977 if (! memberType.getQualifier().hasOffset())
3978 currentOffset = -1;
3979
3980 return;
3981 }
3982
John Kessenichf85e8062015-12-19 13:57:10 -07003983 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003984 if (currentOffset < 0)
3985 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003986
John Kessenich5e4b1242015-08-06 22:53:06 -06003987 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3988 // but possibly not yet correctly aligned.
3989
3990 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003991 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003992 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003993
3994 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003995 // TODO: make this consistent in early phases of code:
3996 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3997 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3998 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003999 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004000 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004001 int dummySize;
4002 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4003 if (componentAlignment <= 4)
4004 memberAlignment = componentAlignment;
4005 }
4006
4007 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004008 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004009
4010 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004011 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004012 glslang::RoundToPow2(currentOffset, 16);
4013
John Kessenich5e4b1242015-08-06 22:53:06 -06004014 nextOffset = currentOffset + memberSize;
4015}
4016
David Netoa901ffe2016-06-08 14:11:40 +01004017void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004018{
David Netoa901ffe2016-06-08 14:11:40 +01004019 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4020 switch (glslangBuiltIn)
4021 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004022 case glslang::EbvPointSize:
4023#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004024 case glslang::EbvClipDistance:
4025 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004026 case glslang::EbvViewportMaskNV:
4027 case glslang::EbvSecondaryPositionNV:
4028 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004029 case glslang::EbvPositionPerViewNV:
4030 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004031 case glslang::EbvTaskCountNV:
4032 case glslang::EbvPrimitiveCountNV:
4033 case glslang::EbvPrimitiveIndicesNV:
4034 case glslang::EbvClipDistancePerViewNV:
4035 case glslang::EbvCullDistancePerViewNV:
4036 case glslang::EbvLayerPerViewNV:
4037 case glslang::EbvMeshViewCountNV:
4038 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004039#endif
David Netoa901ffe2016-06-08 14:11:40 +01004040 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4041 // Alternately, we could just call this for any glslang built-in, since the
4042 // capability already guards against duplicates.
4043 TranslateBuiltInDecoration(glslangBuiltIn, false);
4044 break;
4045 default:
4046 // Capabilities were already generated when the struct was declared.
4047 break;
4048 }
John Kessenichebb50532016-05-16 19:22:05 -06004049}
4050
John Kessenich6fccb3c2016-09-19 16:01:41 -06004051bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004052{
John Kessenicheee9d532016-09-19 18:09:30 -06004053 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004054}
4055
John Kessenichd41993d2017-09-10 15:21:05 -06004056// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004057// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4058// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004059bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004060{
John Kessenich6a14f782017-12-04 02:48:10 -07004061 assert(qualifier == glslang::EvqIn ||
4062 qualifier == glslang::EvqOut ||
4063 qualifier == glslang::EvqInOut ||
4064 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004065 return qualifier != glslang::EvqConstReadOnly;
4066}
4067
4068// Is parameter pass-by-original?
4069bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4070 bool implicitThisParam)
4071{
4072 if (implicitThisParam) // implicit this
4073 return true;
4074 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004075 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004076 return paramType.containsOpaque() || // sampler, etc.
4077 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4078}
4079
John Kessenich140f3df2015-06-26 16:58:36 -06004080// Make all the functions, skeletally, without actually visiting their bodies.
4081void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4082{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004083 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004084 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4085 if (paramPrecision != spv::NoPrecision)
4086 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004087 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004088 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004089 // Original and non-writable params pass the pointer directly and
4090 // use restrict/aliased, others are stored to a pointer in Function
4091 // memory and use RestrictPointer/AliasedPointer.
4092 if (originalParam(type.getQualifier().storage, type, false) ||
4093 !writableParam(type.getQualifier().storage)) {
4094 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
4095 } else {
4096 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
4097 }
4098 }
John Kessenichfad62972017-07-18 02:35:46 -06004099 };
4100
John Kessenich140f3df2015-06-26 16:58:36 -06004101 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4102 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004103 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004104 continue;
4105
4106 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004107 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004108 //
qining25262b32016-05-06 17:25:16 -04004109 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004110 // function. What it is an address of varies:
4111 //
John Kessenich4bf71552016-09-02 11:20:21 -06004112 // - "in" parameters not marked as "const" can be written to without modifying the calling
4113 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004114 //
4115 // - "const in" parameters can just be the r-value, as no writes need occur.
4116 //
John Kessenich4bf71552016-09-02 11:20:21 -06004117 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4118 // 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 -06004119
4120 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004121 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004122 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4123
John Kessenichfad62972017-07-18 02:35:46 -06004124 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4125 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06004126
John Kessenichfad62972017-07-18 02:35:46 -06004127 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004128 for (int p = 0; p < (int)parameters.size(); ++p) {
4129 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4130 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004131 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004132 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004133 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004134 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4135 else
John Kessenich4bf71552016-09-02 11:20:21 -06004136 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004137 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004138 paramTypes.push_back(typeId);
4139 }
4140
4141 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004142 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4143 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004144 glslFunction->getName().c_str(), paramTypes,
4145 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004146 if (implicitThis)
4147 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004148
4149 // Track function to emit/call later
4150 functionMap[glslFunction->getName().c_str()] = function;
4151
4152 // Set the parameter id's
4153 for (int p = 0; p < (int)parameters.size(); ++p) {
4154 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4155 // give a name too
4156 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004157
4158 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4159 if (paramType.containsBasicType(glslang::EbtInt8) ||
4160 paramType.containsBasicType(glslang::EbtUint8))
4161 builder.addCapability(spv::CapabilityInt8);
4162 if (paramType.containsBasicType(glslang::EbtInt16) ||
4163 paramType.containsBasicType(glslang::EbtUint16))
4164 builder.addCapability(spv::CapabilityInt16);
4165 if (paramType.containsBasicType(glslang::EbtFloat16))
4166 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004167 }
4168 }
4169}
4170
4171// Process all the initializers, while skipping the functions and link objects
4172void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4173{
4174 builder.setBuildPoint(shaderEntry->getLastBlock());
4175 for (int i = 0; i < (int)initializers.size(); ++i) {
4176 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
4177 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
4178
4179 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004180 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004181 initializer->traverse(this);
4182 }
4183 }
4184}
4185
4186// Process all the functions, while skipping initializers.
4187void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4188{
4189 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4190 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004191 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004192 node->traverse(this);
4193 }
4194}
4195
4196void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4197{
qining25262b32016-05-06 17:25:16 -04004198 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004199 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004200 currentFunction = functionMap[node->getName().c_str()];
4201 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004202 builder.setBuildPoint(functionBlock);
4203}
4204
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004205void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004206{
Rex Xufc618912015-09-09 16:42:49 +08004207 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004208
4209 glslang::TSampler sampler = {};
4210 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004211#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004212 bool f16ShadowCompare = false;
4213#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004214 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004215 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4216 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004217#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004218 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4219#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004220 }
4221
John Kessenich140f3df2015-06-26 16:58:36 -06004222 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4223 builder.clearAccessChain();
4224 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004225
John Kessenicha28f7a72019-08-06 07:00:58 -06004226#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004227 // Special case l-value operands
4228 bool lvalue = false;
4229 switch (node.getOp()) {
4230 case glslang::EOpImageAtomicAdd:
4231 case glslang::EOpImageAtomicMin:
4232 case glslang::EOpImageAtomicMax:
4233 case glslang::EOpImageAtomicAnd:
4234 case glslang::EOpImageAtomicOr:
4235 case glslang::EOpImageAtomicXor:
4236 case glslang::EOpImageAtomicExchange:
4237 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004238 case glslang::EOpImageAtomicLoad:
4239 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004240 if (i == 0)
4241 lvalue = true;
4242 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004243 case glslang::EOpSparseImageLoad:
4244 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4245 lvalue = true;
4246 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004247 case glslang::EOpSparseTexture:
4248 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4249 lvalue = true;
4250 break;
4251 case glslang::EOpSparseTextureClamp:
4252 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4253 lvalue = true;
4254 break;
4255 case glslang::EOpSparseTextureLod:
4256 case glslang::EOpSparseTextureOffset:
4257 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4258 lvalue = true;
4259 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004260 case glslang::EOpSparseTextureFetch:
4261 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4262 lvalue = true;
4263 break;
4264 case glslang::EOpSparseTextureFetchOffset:
4265 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4266 lvalue = true;
4267 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004268 case glslang::EOpSparseTextureLodOffset:
4269 case glslang::EOpSparseTextureGrad:
4270 case glslang::EOpSparseTextureOffsetClamp:
4271 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4272 lvalue = true;
4273 break;
4274 case glslang::EOpSparseTextureGradOffset:
4275 case glslang::EOpSparseTextureGradClamp:
4276 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4277 lvalue = true;
4278 break;
4279 case glslang::EOpSparseTextureGradOffsetClamp:
4280 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4281 lvalue = true;
4282 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004283 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004284 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4285 lvalue = true;
4286 break;
4287 case glslang::EOpSparseTextureGatherOffset:
4288 case glslang::EOpSparseTextureGatherOffsets:
4289 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4290 lvalue = true;
4291 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004292 case glslang::EOpSparseTextureGatherLod:
4293 if (i == 3)
4294 lvalue = true;
4295 break;
4296 case glslang::EOpSparseTextureGatherLodOffset:
4297 case glslang::EOpSparseTextureGatherLodOffsets:
4298 if (i == 4)
4299 lvalue = true;
4300 break;
Rex Xu129799a2017-07-05 17:23:28 +08004301 case glslang::EOpSparseImageLoadLod:
4302 if (i == 3)
4303 lvalue = true;
4304 break;
Chao Chen3a137962018-09-19 11:41:27 -07004305 case glslang::EOpImageSampleFootprintNV:
4306 if (i == 4)
4307 lvalue = true;
4308 break;
4309 case glslang::EOpImageSampleFootprintClampNV:
4310 case glslang::EOpImageSampleFootprintLodNV:
4311 if (i == 5)
4312 lvalue = true;
4313 break;
4314 case glslang::EOpImageSampleFootprintGradNV:
4315 if (i == 6)
4316 lvalue = true;
4317 break;
4318 case glslang::EOpImageSampleFootprintGradClampNV:
4319 if (i == 7)
4320 lvalue = true;
4321 break;
Rex Xufc618912015-09-09 16:42:49 +08004322 default:
4323 break;
4324 }
4325
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004326 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004327 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004328 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4329 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4330 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004331#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004332 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004333 }
4334}
4335
John Kessenichfc51d282015-08-19 13:34:18 -06004336void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004337{
John Kessenichfc51d282015-08-19 13:34:18 -06004338 builder.clearAccessChain();
4339 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004340 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004341}
John Kessenich140f3df2015-06-26 16:58:36 -06004342
John Kessenichfc51d282015-08-19 13:34:18 -06004343spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4344{
John Kesseniche485c7a2017-05-31 18:50:53 -06004345 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004346 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004347
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004348 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004349
John Kessenichfc51d282015-08-19 13:34:18 -06004350 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004351
John Kessenichf43c7392019-03-31 10:51:57 -06004352 const glslang::TType &imageType = node->getAsAggregate()
4353 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4354 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004355 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004356#ifdef GLSLANG_WEB
4357 const bool f16ShadowCompare = false;
4358#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004359 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004360 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4361 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004362#endif
4363
John Kessenichf43c7392019-03-31 10:51:57 -06004364 const auto signExtensionMask = [&]() {
4365 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4366 if (sampler.type == glslang::EbtUint)
4367 return spv::ImageOperandsZeroExtendMask;
4368 else if (sampler.type == glslang::EbtInt)
4369 return spv::ImageOperandsSignExtendMask;
4370 }
4371 return spv::ImageOperandsMaskNone;
4372 };
4373
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004374 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4375
John Kessenichfc51d282015-08-19 13:34:18 -06004376 std::vector<spv::Id> arguments;
4377 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004378 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004379 else
4380 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004381 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004382
4383 spv::Builder::TextureParameters params = { };
4384 params.sampler = arguments[0];
4385
Rex Xu04db3f52015-09-16 11:44:02 +08004386 glslang::TCrackedTextureOp cracked;
4387 node->crackTexture(sampler, cracked);
4388
amhagan05506bb2017-06-13 16:53:02 -04004389 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004390
John Kessenichfc51d282015-08-19 13:34:18 -06004391 // Check for queries
4392 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004393 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4394 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004395 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004396
John Kessenichfc51d282015-08-19 13:34:18 -06004397 switch (node->getOp()) {
4398 case glslang::EOpImageQuerySize:
4399 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004400 if (arguments.size() > 1) {
4401 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004402 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004403 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004404 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004405#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004406 case glslang::EOpImageQuerySamples:
4407 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004408 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004409 case glslang::EOpTextureQueryLod:
4410 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004411 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004412 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004413 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004414 case glslang::EOpSparseTexelsResident:
4415 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004416#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004417 default:
4418 assert(0);
4419 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004420 }
John Kessenich140f3df2015-06-26 16:58:36 -06004421 }
4422
LoopDawg4425f242018-02-18 11:40:01 -07004423 int components = node->getType().getVectorSize();
4424
4425 if (node->getOp() == glslang::EOpTextureFetch) {
4426 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4427 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4428 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4429 // here around e.g. which ones return scalars or other types.
4430 components = 4;
4431 }
4432
4433 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4434
4435 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4436
Rex Xufc618912015-09-09 16:42:49 +08004437 // Check for image functions other than queries
4438 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004439 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004440 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004441 spv::IdImmediate image = { true, *(opIt++) };
4442 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004443
4444 // Handle subpass operations
4445 // TODO: GLSL should change to have the "MS" only on the type rather than the
4446 // built-in function.
4447 if (cracked.subpass) {
4448 // add on the (0,0) coordinate
4449 spv::Id zero = builder.makeIntConstant(0);
4450 std::vector<spv::Id> comps;
4451 comps.push_back(zero);
4452 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004453 spv::IdImmediate coord = { true,
4454 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4455 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004456 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4457 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004458 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004459 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4460 }
4461 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004462 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004463 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004464 spv::IdImmediate imageOperand = { true, *(opIt++) };
4465 operands.push_back(imageOperand);
4466 }
John Kessenich6c292d32016-02-15 20:58:50 -07004467 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004468 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4469 builder.setPrecision(result, precision);
4470 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004471 }
4472
John Kessenich149afc32018-08-14 13:31:43 -06004473 spv::IdImmediate coord = { true, *(opIt++) };
4474 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004475 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004476 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004477 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004478 mask = mask | spv::ImageOperandsSampleMask;
4479 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004480 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004481 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4482 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004483 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004484 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004485 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4486 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004487 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004488 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004489 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4490 operands.push_back(imageOperands);
4491 }
4492 if (mask & spv::ImageOperandsSampleMask) {
4493 spv::IdImmediate imageOperand = { true, *opIt++ };
4494 operands.push_back(imageOperand);
4495 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004496 if (mask & spv::ImageOperandsLodMask) {
4497 spv::IdImmediate imageOperand = { true, *opIt++ };
4498 operands.push_back(imageOperand);
4499 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004500 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004501 spv::IdImmediate imageOperand = { true,
4502 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004503 operands.push_back(imageOperand);
4504 }
4505
John Kessenich149afc32018-08-14 13:31:43 -06004506 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004507 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004508
John Kessenich149afc32018-08-14 13:31:43 -06004509 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004510 builder.setPrecision(result[0], precision);
4511
4512 // If needed, add a conversion constructor to the proper size.
4513 if (components != node->getType().getVectorSize())
4514 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4515
4516 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004517 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004518
Jeff Bolz36831c92018-09-05 10:11:41 -05004519 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004520 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004521 spv::IdImmediate texel = { true, *(opIt + 1) };
4522 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004523 } else {
4524 spv::IdImmediate texel = { true, *opIt };
4525 operands.push_back(texel);
4526 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004527
4528 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004529 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004530 mask = mask | spv::ImageOperandsSampleMask;
4531 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004532 if (cracked.lod) {
4533 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4534 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4535 mask = mask | spv::ImageOperandsLodMask;
4536 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004537 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4538 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004539 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004540 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004541 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4542 operands.push_back(imageOperands);
4543 }
4544 if (mask & spv::ImageOperandsSampleMask) {
4545 spv::IdImmediate imageOperand = { true, *opIt++ };
4546 operands.push_back(imageOperand);
4547 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004548 if (mask & spv::ImageOperandsLodMask) {
4549 spv::IdImmediate imageOperand = { true, *opIt++ };
4550 operands.push_back(imageOperand);
4551 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004552 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004553 spv::IdImmediate imageOperand = { true,
4554 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004555 operands.push_back(imageOperand);
4556 }
4557
John Kessenich56bab042015-09-16 10:54:31 -06004558 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004559 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004560 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004561 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004562 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4563 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004564 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004565 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004566 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4567
Jeff Bolz36831c92018-09-05 10:11:41 -05004568 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004569 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004570 mask = mask | spv::ImageOperandsSampleMask;
4571 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004572 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004573 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4574 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4575
Jeff Bolz36831c92018-09-05 10:11:41 -05004576 mask = mask | spv::ImageOperandsLodMask;
4577 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004578 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4579 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004580 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004581 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004582 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004583 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004584 }
4585 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004586 spv::IdImmediate imageOperand = { true, *opIt++ };
4587 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004588 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004589 if (mask & spv::ImageOperandsLodMask) {
4590 spv::IdImmediate imageOperand = { true, *opIt++ };
4591 operands.push_back(imageOperand);
4592 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004593 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4594 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4595 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004596 }
4597
4598 // Create the return type that was a special structure
4599 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004600 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004601 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4602 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4603
4604 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4605
4606 // Decode the return type
4607 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4608 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004609 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004610 // Process image atomic operations
4611
4612 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4613 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004614 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004615 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004616 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004617
Jeff Bolz36831c92018-09-05 10:11:41 -05004618 spv::Id resultTypeId;
4619 // imageAtomicStore has a void return type so base the pointer type on
4620 // the type of the value operand.
4621 if (node->getOp() == glslang::EOpImageAtomicStore) {
4622 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4623 } else {
4624 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4625 }
John Kessenich56bab042015-09-16 10:54:31 -06004626 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004627
4628 std::vector<spv::Id> operands;
4629 operands.push_back(pointer);
4630 for (; opIt != arguments.end(); ++opIt)
4631 operands.push_back(*opIt);
4632
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004633 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004634 }
4635 }
4636
John Kessenicha28f7a72019-08-06 07:00:58 -06004637#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004638 // Check for fragment mask functions other than queries
4639 if (cracked.fragMask) {
4640 assert(sampler.ms);
4641
4642 auto opIt = arguments.begin();
4643 std::vector<spv::Id> operands;
4644
4645 // Extract the image if necessary
4646 if (builder.isSampledImage(params.sampler))
4647 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4648
4649 operands.push_back(params.sampler);
4650 ++opIt;
4651
4652 if (sampler.isSubpass()) {
4653 // add on the (0,0) coordinate
4654 spv::Id zero = builder.makeIntConstant(0);
4655 std::vector<spv::Id> comps;
4656 comps.push_back(zero);
4657 comps.push_back(zero);
4658 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4659 }
4660
4661 for (; opIt != arguments.end(); ++opIt)
4662 operands.push_back(*opIt);
4663
4664 spv::Op fragMaskOp = spv::OpNop;
4665 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4666 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4667 else if (node->getOp() == glslang::EOpFragmentFetch)
4668 fragMaskOp = spv::OpFragmentFetchAMD;
4669
4670 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4671 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4672 return builder.createOp(fragMaskOp, resultType(), operands);
4673 }
4674#endif
4675
Rex Xufc618912015-09-09 16:42:49 +08004676 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004677 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004678 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004679 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08004680
John Kessenichfc51d282015-08-19 13:34:18 -06004681 // check for bias argument
4682 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004683 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004684 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004685 if (cracked.gather)
4686 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004687
4688 if (f16ShadowCompare)
4689 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004690 if (cracked.offset)
4691 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004692 else if (cracked.offsets)
4693 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004694 if (cracked.grad)
4695 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004696 if (cracked.lodClamp)
4697 ++nonBiasArgCount;
4698 if (sparse)
4699 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004700 if (imageFootprint)
4701 //Following three extra arguments
4702 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4703 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06004704 if ((int)arguments.size() > nonBiasArgCount)
4705 bias = true;
4706 }
4707
John Kessenicha5c33d62016-06-02 23:45:21 -06004708 // See if the sampler param should really be just the SPV image part
4709 if (cracked.fetch) {
4710 // a fetch needs to have the image extracted first
4711 if (builder.isSampledImage(params.sampler))
4712 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4713 }
4714
John Kessenicha28f7a72019-08-06 07:00:58 -06004715#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08004716 if (cracked.gather) {
4717 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4718 if (bias || cracked.lod ||
4719 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4720 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004721 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004722 }
4723 }
4724#endif
4725
John Kessenichfc51d282015-08-19 13:34:18 -06004726 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004727
John Kessenichfc51d282015-08-19 13:34:18 -06004728 params.coords = arguments[1];
4729 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004730 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004731
4732 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004733 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004734 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004735 ++extraArgs;
4736 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004737 params.Dref = arguments[2];
4738 ++extraArgs;
4739 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004740 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004741 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004742 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004743 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004744 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004745 dRefComp = builder.getNumComponents(params.coords) - 1;
4746 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004747 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4748 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004749
4750 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004751 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004752 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004753 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004754 } else if (glslangIntermediate->getStage() != EShLangFragment
John Kessenicha28f7a72019-08-06 07:00:58 -06004755#ifndef GLSLANG_WEB
Chao Chenbeae2252018-09-19 11:40:45 -07004756 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4757 && !(glslangIntermediate->getStage() == EShLangCompute &&
4758 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4759#endif
4760 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004761 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4762 noImplicitLod = true;
4763 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004764
4765 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004766 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004767 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004768 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004769 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004770
4771 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004772 if (cracked.grad) {
4773 params.gradX = arguments[2 + extraArgs];
4774 params.gradY = arguments[3 + extraArgs];
4775 extraArgs += 2;
4776 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004777
4778 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004779 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004780 params.offset = arguments[2 + extraArgs];
4781 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004782 } else if (cracked.offsets) {
4783 params.offsets = arguments[2 + extraArgs];
4784 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004785 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004786
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004787#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06004788 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004789 if (cracked.lodClamp) {
4790 params.lodClamp = arguments[2 + extraArgs];
4791 ++extraArgs;
4792 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004793 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004794 if (sparse) {
4795 params.texelOut = arguments[2 + extraArgs];
4796 ++extraArgs;
4797 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004798 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004799 if (cracked.gather && ! sampler.shadow) {
4800 // default component is 0, if missing, otherwise an argument
4801 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004802 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004803 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004804 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004805 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004806 }
Chao Chen3a137962018-09-19 11:41:27 -07004807 spv::Id resultStruct = spv::NoResult;
4808 if (imageFootprint) {
4809 //Following three extra arguments
4810 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4811 params.granularity = arguments[2 + extraArgs];
4812 params.coarse = arguments[3 + extraArgs];
4813 resultStruct = arguments[4 + extraArgs];
4814 extraArgs += 3;
4815 }
4816#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004817 // bias
4818 if (bias) {
4819 params.bias = arguments[2 + extraArgs];
4820 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004821 }
John Kessenichfc51d282015-08-19 13:34:18 -06004822
John Kessenicha28f7a72019-08-06 07:00:58 -06004823#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07004824 if (imageFootprint) {
4825 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4826 builder.addCapability(spv::CapabilityImageFootprintNV);
4827
4828
4829 //resultStructType(OpenGL type) contains 5 elements:
4830 //struct gl_TextureFootprint2DNV {
4831 // uvec2 anchor;
4832 // uvec2 offset;
4833 // uvec2 mask;
4834 // uint lod;
4835 // uint granularity;
4836 //};
4837 //or
4838 //struct gl_TextureFootprint3DNV {
4839 // uvec3 anchor;
4840 // uvec3 offset;
4841 // uvec2 mask;
4842 // uint lod;
4843 // uint granularity;
4844 //};
4845 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4846 assert(builder.isStructType(resultStructType));
4847
4848 //resType (SPIR-V type) contains 6 elements:
4849 //Member 0 must be a Boolean type scalar(LOD),
4850 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4851 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4852 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4853 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4854 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4855 std::vector<spv::Id> members;
4856 members.push_back(resultType());
4857 for (int i = 0; i < 5; i++) {
4858 members.push_back(builder.getContainedTypeId(resultStructType, i));
4859 }
4860 spv::Id resType = builder.makeStructType(members, "ResType");
4861
4862 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06004863 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
4864 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07004865
4866 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4867 for (int i = 0; i < 5; i++) {
4868 builder.clearAccessChain();
4869 builder.setAccessChainLValue(resultStruct);
4870
4871 //Accessing to a struct we created, no coherent flag is set
4872 spv::Builder::AccessChain::CoherentFlags flags;
4873 flags.clear();
4874
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004875 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004876 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4877 }
4878 return builder.createCompositeExtract(res, resultType(), 0);
4879 }
4880#endif
4881
John Kessenich65336482016-06-16 14:06:26 -06004882 // projective component (might not to move)
4883 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4884 // are divided by the last component of P."
4885 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4886 // unused components will appear after all used components."
4887 if (cracked.proj) {
4888 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4889 int projTargetComp;
4890 switch (sampler.dim) {
4891 case glslang::Esd1D: projTargetComp = 1; break;
4892 case glslang::Esd2D: projTargetComp = 2; break;
4893 case glslang::EsdRect: projTargetComp = 2; break;
4894 default: projTargetComp = projSourceComp; break;
4895 }
4896 // copy the projective coordinate if we have to
4897 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004898 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004899 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4900 projSourceComp);
4901 params.coords = builder.createCompositeInsert(projComp, params.coords,
4902 builder.getTypeId(params.coords), projTargetComp);
4903 }
4904 }
4905
Jeff Bolz36831c92018-09-05 10:11:41 -05004906 // nonprivate
4907 if (imageType.getQualifier().nonprivate) {
4908 params.nonprivate = true;
4909 }
4910
4911 // volatile
4912 if (imageType.getQualifier().volatil) {
4913 params.volatil = true;
4914 }
4915
St0fFa1184dd2018-04-09 21:08:14 +02004916 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06004917 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
4918 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02004919 );
LoopDawg4425f242018-02-18 11:40:01 -07004920
4921 if (components != node->getType().getVectorSize())
4922 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4923
4924 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004925}
4926
4927spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4928{
4929 // Grab the function's pointer from the previously created function
4930 spv::Function* function = functionMap[node->getName().c_str()];
4931 if (! function)
4932 return 0;
4933
4934 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4935 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4936
4937 // See comments in makeFunctions() for details about the semantics for parameter passing.
4938 //
4939 // These imply we need a four step process:
4940 // 1. Evaluate the arguments
4941 // 2. Allocate and make copies of in, out, and inout arguments
4942 // 3. Make the call
4943 // 4. Copy back the results
4944
John Kessenichd3ed90b2018-05-04 11:43:03 -06004945 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004946 std::vector<spv::Builder::AccessChain> lValues;
4947 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004948 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004949 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004950 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004951 // build l-value
4952 builder.clearAccessChain();
4953 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004954 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004955 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004956 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004957 // save l-value
4958 lValues.push_back(builder.getAccessChain());
4959 } else {
4960 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004961 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004962 }
4963 }
4964
4965 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4966 // copy the original into that space.
4967 //
4968 // Also, build up the list of actual arguments to pass in for the call
4969 int lValueCount = 0;
4970 int rValueCount = 0;
4971 std::vector<spv::Id> spvArgs;
4972 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4973 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004974 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004975 builder.setAccessChain(lValues[lValueCount]);
4976 arg = builder.accessChainGetLValue();
4977 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004978 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004979 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004980 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004981 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4982 // need to copy the input into output space
4983 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004984 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004985 builder.clearAccessChain();
4986 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004987 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004988 }
4989 ++lValueCount;
4990 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004991 // process r-value, which involves a copy for a type mismatch
4992 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4993 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4994 builder.clearAccessChain();
4995 builder.setAccessChainLValue(argCopy);
4996 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4997 arg = builder.createLoad(argCopy);
4998 } else
4999 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005000 ++rValueCount;
5001 }
5002 spvArgs.push_back(arg);
5003 }
5004
5005 // 3. Make the call.
5006 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005007 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005008
5009 // 4. Copy back out an "out" arguments.
5010 lValueCount = 0;
5011 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005012 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005013 ++lValueCount;
5014 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005015 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5016 spv::Id copy = builder.createLoad(spvArgs[a]);
5017 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005018 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005019 }
5020 ++lValueCount;
5021 }
5022 }
5023
5024 return result;
5025}
5026
5027// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005028spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005029 spv::Id typeId, spv::Id left, spv::Id right,
5030 glslang::TBasicType typeProxy, bool reduceComparison)
5031{
John Kessenich66011cb2018-03-06 16:12:04 -07005032 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5033 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005034 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005035
5036 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005037 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005038 bool comparison = false;
5039
5040 switch (op) {
5041 case glslang::EOpAdd:
5042 case glslang::EOpAddAssign:
5043 if (isFloat)
5044 binOp = spv::OpFAdd;
5045 else
5046 binOp = spv::OpIAdd;
5047 break;
5048 case glslang::EOpSub:
5049 case glslang::EOpSubAssign:
5050 if (isFloat)
5051 binOp = spv::OpFSub;
5052 else
5053 binOp = spv::OpISub;
5054 break;
5055 case glslang::EOpMul:
5056 case glslang::EOpMulAssign:
5057 if (isFloat)
5058 binOp = spv::OpFMul;
5059 else
5060 binOp = spv::OpIMul;
5061 break;
5062 case glslang::EOpVectorTimesScalar:
5063 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005064 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005065 if (builder.isVector(right))
5066 std::swap(left, right);
5067 assert(builder.isScalar(right));
5068 needMatchingVectors = false;
5069 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005070 } else if (isFloat)
5071 binOp = spv::OpFMul;
5072 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005073 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005074 break;
5075 case glslang::EOpVectorTimesMatrix:
5076 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005077 binOp = spv::OpVectorTimesMatrix;
5078 break;
5079 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005080 binOp = spv::OpMatrixTimesVector;
5081 break;
5082 case glslang::EOpMatrixTimesScalar:
5083 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005084 binOp = spv::OpMatrixTimesScalar;
5085 break;
5086 case glslang::EOpMatrixTimesMatrix:
5087 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005088 binOp = spv::OpMatrixTimesMatrix;
5089 break;
5090 case glslang::EOpOuterProduct:
5091 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005092 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005093 break;
5094
5095 case glslang::EOpDiv:
5096 case glslang::EOpDivAssign:
5097 if (isFloat)
5098 binOp = spv::OpFDiv;
5099 else if (isUnsigned)
5100 binOp = spv::OpUDiv;
5101 else
5102 binOp = spv::OpSDiv;
5103 break;
5104 case glslang::EOpMod:
5105 case glslang::EOpModAssign:
5106 if (isFloat)
5107 binOp = spv::OpFMod;
5108 else if (isUnsigned)
5109 binOp = spv::OpUMod;
5110 else
5111 binOp = spv::OpSMod;
5112 break;
5113 case glslang::EOpRightShift:
5114 case glslang::EOpRightShiftAssign:
5115 if (isUnsigned)
5116 binOp = spv::OpShiftRightLogical;
5117 else
5118 binOp = spv::OpShiftRightArithmetic;
5119 break;
5120 case glslang::EOpLeftShift:
5121 case glslang::EOpLeftShiftAssign:
5122 binOp = spv::OpShiftLeftLogical;
5123 break;
5124 case glslang::EOpAnd:
5125 case glslang::EOpAndAssign:
5126 binOp = spv::OpBitwiseAnd;
5127 break;
5128 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005129 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005130 binOp = spv::OpLogicalAnd;
5131 break;
5132 case glslang::EOpInclusiveOr:
5133 case glslang::EOpInclusiveOrAssign:
5134 binOp = spv::OpBitwiseOr;
5135 break;
5136 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005137 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005138 binOp = spv::OpLogicalOr;
5139 break;
5140 case glslang::EOpExclusiveOr:
5141 case glslang::EOpExclusiveOrAssign:
5142 binOp = spv::OpBitwiseXor;
5143 break;
5144 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005145 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005146 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005147 break;
5148
5149 case glslang::EOpLessThan:
5150 case glslang::EOpGreaterThan:
5151 case glslang::EOpLessThanEqual:
5152 case glslang::EOpGreaterThanEqual:
5153 case glslang::EOpEqual:
5154 case glslang::EOpNotEqual:
5155 case glslang::EOpVectorEqual:
5156 case glslang::EOpVectorNotEqual:
5157 comparison = true;
5158 break;
5159 default:
5160 break;
5161 }
5162
John Kessenich7c1aa102015-10-15 13:29:11 -06005163 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005164 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005165 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005166 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5167 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005168 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005169
5170 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005171 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005172 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005173
qining25262b32016-05-06 17:25:16 -04005174 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005175 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005176 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005177 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005178 }
5179
5180 if (! comparison)
5181 return 0;
5182
John Kessenich7c1aa102015-10-15 13:29:11 -06005183 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005184
John Kessenich4583b612016-08-07 19:14:22 -06005185 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005186 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5187 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06005188 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005189 return result;
5190 }
John Kessenich140f3df2015-06-26 16:58:36 -06005191
5192 switch (op) {
5193 case glslang::EOpLessThan:
5194 if (isFloat)
5195 binOp = spv::OpFOrdLessThan;
5196 else if (isUnsigned)
5197 binOp = spv::OpULessThan;
5198 else
5199 binOp = spv::OpSLessThan;
5200 break;
5201 case glslang::EOpGreaterThan:
5202 if (isFloat)
5203 binOp = spv::OpFOrdGreaterThan;
5204 else if (isUnsigned)
5205 binOp = spv::OpUGreaterThan;
5206 else
5207 binOp = spv::OpSGreaterThan;
5208 break;
5209 case glslang::EOpLessThanEqual:
5210 if (isFloat)
5211 binOp = spv::OpFOrdLessThanEqual;
5212 else if (isUnsigned)
5213 binOp = spv::OpULessThanEqual;
5214 else
5215 binOp = spv::OpSLessThanEqual;
5216 break;
5217 case glslang::EOpGreaterThanEqual:
5218 if (isFloat)
5219 binOp = spv::OpFOrdGreaterThanEqual;
5220 else if (isUnsigned)
5221 binOp = spv::OpUGreaterThanEqual;
5222 else
5223 binOp = spv::OpSGreaterThanEqual;
5224 break;
5225 case glslang::EOpEqual:
5226 case glslang::EOpVectorEqual:
5227 if (isFloat)
5228 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005229 else if (isBool)
5230 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005231 else
5232 binOp = spv::OpIEqual;
5233 break;
5234 case glslang::EOpNotEqual:
5235 case glslang::EOpVectorNotEqual:
5236 if (isFloat)
5237 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005238 else if (isBool)
5239 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005240 else
5241 binOp = spv::OpINotEqual;
5242 break;
5243 default:
5244 break;
5245 }
5246
qining25262b32016-05-06 17:25:16 -04005247 if (binOp != spv::OpNop) {
5248 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005249 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005250 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005251 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005252 }
John Kessenich140f3df2015-06-26 16:58:36 -06005253
5254 return 0;
5255}
5256
John Kessenich04bb8a02015-12-12 12:28:14 -07005257//
5258// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5259// These can be any of:
5260//
5261// matrix * scalar
5262// scalar * matrix
5263// matrix * matrix linear algebraic
5264// matrix * vector
5265// vector * matrix
5266// matrix * matrix componentwise
5267// matrix op matrix op in {+, -, /}
5268// matrix op scalar op in {+, -, /}
5269// scalar op matrix op in {+, -, /}
5270//
John Kessenichead86222018-03-28 18:01:20 -06005271spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5272 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005273{
5274 bool firstClass = true;
5275
5276 // First, handle first-class matrix operations (* and matrix/scalar)
5277 switch (op) {
5278 case spv::OpFDiv:
5279 if (builder.isMatrix(left) && builder.isScalar(right)) {
5280 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005281 spv::Id resultType = builder.getTypeId(right);
5282 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005283 op = spv::OpMatrixTimesScalar;
5284 } else
5285 firstClass = false;
5286 break;
5287 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005288 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005289 std::swap(left, right);
5290 assert(builder.isScalar(right));
5291 break;
5292 case spv::OpVectorTimesMatrix:
5293 assert(builder.isVector(left));
5294 assert(builder.isMatrix(right));
5295 break;
5296 case spv::OpMatrixTimesVector:
5297 assert(builder.isMatrix(left));
5298 assert(builder.isVector(right));
5299 break;
5300 case spv::OpMatrixTimesMatrix:
5301 assert(builder.isMatrix(left));
5302 assert(builder.isMatrix(right));
5303 break;
5304 default:
5305 firstClass = false;
5306 break;
5307 }
5308
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005309 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5310 firstClass = true;
5311
qining25262b32016-05-06 17:25:16 -04005312 if (firstClass) {
5313 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005314 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005315 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005316 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005317 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005318
LoopDawg592860c2016-06-09 08:57:35 -06005319 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005320 // The result type of all of them is the same type as the (a) matrix operand.
5321 // The algorithm is to:
5322 // - break the matrix(es) into vectors
5323 // - smear any scalar to a vector
5324 // - do vector operations
5325 // - make a matrix out the vector results
5326 switch (op) {
5327 case spv::OpFAdd:
5328 case spv::OpFSub:
5329 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005330 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005331 case spv::OpFMul:
5332 {
5333 // one time set up...
5334 bool leftMat = builder.isMatrix(left);
5335 bool rightMat = builder.isMatrix(right);
5336 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5337 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5338 spv::Id scalarType = builder.getScalarTypeId(typeId);
5339 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5340 std::vector<spv::Id> results;
5341 spv::Id smearVec = spv::NoResult;
5342 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005343 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005344 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005345 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005346
5347 // do each vector op
5348 for (unsigned int c = 0; c < numCols; ++c) {
5349 std::vector<unsigned int> indexes;
5350 indexes.push_back(c);
5351 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5352 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005353 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005354 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005355 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005356 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005357 }
5358
5359 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005360 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005361 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005362 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005363 }
5364 default:
5365 assert(0);
5366 return spv::NoResult;
5367 }
5368}
5369
John Kessenichead86222018-03-28 18:01:20 -06005370spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005371 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005372{
5373 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005374 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005375 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005376 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5377 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005378
5379 switch (op) {
5380 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005381 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005382 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005383 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005384 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005385 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005386 unaryOp = spv::OpSNegate;
5387 break;
5388
5389 case glslang::EOpLogicalNot:
5390 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005391 unaryOp = spv::OpLogicalNot;
5392 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005393 case glslang::EOpBitwiseNot:
5394 unaryOp = spv::OpNot;
5395 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005396
John Kessenich140f3df2015-06-26 16:58:36 -06005397 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005398 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005399 break;
5400 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005401 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005402 break;
5403 case glslang::EOpTranspose:
5404 unaryOp = spv::OpTranspose;
5405 break;
5406
5407 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005408 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005409 break;
5410 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005411 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005412 break;
5413 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005414 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005415 break;
5416 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005417 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005418 break;
5419 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005420 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005421 break;
5422 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005423 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005424 break;
5425 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005426 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005427 break;
5428 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005429 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005430 break;
5431
5432 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005433 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005434 break;
5435 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005436 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005437 break;
5438 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005439 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005440 break;
5441 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005442 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005443 break;
5444 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005445 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005446 break;
5447 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005448 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005449 break;
5450
5451 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005452 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005453 break;
5454 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005455 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005456 break;
5457
5458 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005459 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005460 break;
5461 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005462 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005463 break;
5464 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005465 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005466 break;
5467 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005468 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005469 break;
5470 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005471 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005472 break;
5473 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005474 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005475 break;
5476
5477 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005478 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005479 break;
5480 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005481 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005482 break;
5483 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005484 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005485 break;
5486 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005487 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005488 break;
5489 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005490 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005491 break;
5492 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005493 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005494 break;
5495
5496 case glslang::EOpIsNan:
5497 unaryOp = spv::OpIsNan;
5498 break;
5499 case glslang::EOpIsInf:
5500 unaryOp = spv::OpIsInf;
5501 break;
LoopDawg592860c2016-06-09 08:57:35 -06005502 case glslang::EOpIsFinite:
5503 unaryOp = spv::OpIsFinite;
5504 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005505
Rex Xucbc426e2015-12-15 16:03:10 +08005506 case glslang::EOpFloatBitsToInt:
5507 case glslang::EOpFloatBitsToUint:
5508 case glslang::EOpIntBitsToFloat:
5509 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005510 case glslang::EOpDoubleBitsToInt64:
5511 case glslang::EOpDoubleBitsToUint64:
5512 case glslang::EOpInt64BitsToDouble:
5513 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005514 case glslang::EOpFloat16BitsToInt16:
5515 case glslang::EOpFloat16BitsToUint16:
5516 case glslang::EOpInt16BitsToFloat16:
5517 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005518 unaryOp = spv::OpBitcast;
5519 break;
5520
John Kessenich140f3df2015-06-26 16:58:36 -06005521 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005522 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005523 break;
5524 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005525 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005526 break;
5527 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005528 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005529 break;
5530 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005531 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005532 break;
5533 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005534 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005535 break;
5536 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005537 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005538 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005539 case glslang::EOpPackSnorm4x8:
5540 libCall = spv::GLSLstd450PackSnorm4x8;
5541 break;
5542 case glslang::EOpUnpackSnorm4x8:
5543 libCall = spv::GLSLstd450UnpackSnorm4x8;
5544 break;
5545 case glslang::EOpPackUnorm4x8:
5546 libCall = spv::GLSLstd450PackUnorm4x8;
5547 break;
5548 case glslang::EOpUnpackUnorm4x8:
5549 libCall = spv::GLSLstd450UnpackUnorm4x8;
5550 break;
5551 case glslang::EOpPackDouble2x32:
5552 libCall = spv::GLSLstd450PackDouble2x32;
5553 break;
5554 case glslang::EOpUnpackDouble2x32:
5555 libCall = spv::GLSLstd450UnpackDouble2x32;
5556 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005557
Rex Xu8ff43de2016-04-22 16:51:45 +08005558 case glslang::EOpPackInt2x32:
5559 case glslang::EOpUnpackInt2x32:
5560 case glslang::EOpPackUint2x32:
5561 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005562 case glslang::EOpPack16:
5563 case glslang::EOpPack32:
5564 case glslang::EOpPack64:
5565 case glslang::EOpUnpack32:
5566 case glslang::EOpUnpack16:
5567 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005568 case glslang::EOpPackInt2x16:
5569 case glslang::EOpUnpackInt2x16:
5570 case glslang::EOpPackUint2x16:
5571 case glslang::EOpUnpackUint2x16:
5572 case glslang::EOpPackInt4x16:
5573 case glslang::EOpUnpackInt4x16:
5574 case glslang::EOpPackUint4x16:
5575 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005576 case glslang::EOpPackFloat2x16:
5577 case glslang::EOpUnpackFloat2x16:
5578 unaryOp = spv::OpBitcast;
5579 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005580
John Kessenich140f3df2015-06-26 16:58:36 -06005581 case glslang::EOpDPdx:
5582 unaryOp = spv::OpDPdx;
5583 break;
5584 case glslang::EOpDPdy:
5585 unaryOp = spv::OpDPdy;
5586 break;
5587 case glslang::EOpFwidth:
5588 unaryOp = spv::OpFwidth;
5589 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005590
John Kessenich140f3df2015-06-26 16:58:36 -06005591 case glslang::EOpAny:
5592 unaryOp = spv::OpAny;
5593 break;
5594 case glslang::EOpAll:
5595 unaryOp = spv::OpAll;
5596 break;
5597
5598 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005599 if (isFloat)
5600 libCall = spv::GLSLstd450FAbs;
5601 else
5602 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005603 break;
5604 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005605 if (isFloat)
5606 libCall = spv::GLSLstd450FSign;
5607 else
5608 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005609 break;
5610
John Kessenicha28f7a72019-08-06 07:00:58 -06005611#ifndef GLSLANG_WEB
5612 case glslang::EOpDPdxFine:
5613 unaryOp = spv::OpDPdxFine;
5614 break;
5615 case glslang::EOpDPdyFine:
5616 unaryOp = spv::OpDPdyFine;
5617 break;
5618 case glslang::EOpFwidthFine:
5619 unaryOp = spv::OpFwidthFine;
5620 break;
5621 case glslang::EOpDPdxCoarse:
5622 unaryOp = spv::OpDPdxCoarse;
5623 break;
5624 case glslang::EOpDPdyCoarse:
5625 unaryOp = spv::OpDPdyCoarse;
5626 break;
5627 case glslang::EOpFwidthCoarse:
5628 unaryOp = spv::OpFwidthCoarse;
5629 break;
5630 case glslang::EOpInterpolateAtCentroid:
5631 if (typeProxy == glslang::EbtFloat16)
5632 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5633 libCall = spv::GLSLstd450InterpolateAtCentroid;
5634 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005635 case glslang::EOpAtomicCounterIncrement:
5636 case glslang::EOpAtomicCounterDecrement:
5637 case glslang::EOpAtomicCounter:
5638 {
5639 // Handle all of the atomics in one place, in createAtomicOperation()
5640 std::vector<spv::Id> operands;
5641 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005642 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005643 }
5644
John Kessenichfc51d282015-08-19 13:34:18 -06005645 case glslang::EOpBitFieldReverse:
5646 unaryOp = spv::OpBitReverse;
5647 break;
5648 case glslang::EOpBitCount:
5649 unaryOp = spv::OpBitCount;
5650 break;
5651 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005652 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005653 break;
5654 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005655 if (isUnsigned)
5656 libCall = spv::GLSLstd450FindUMsb;
5657 else
5658 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005659 break;
5660
Rex Xu574ab042016-04-14 16:53:07 +08005661 case glslang::EOpBallot:
5662 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005663 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005664 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005665 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005666 case glslang::EOpMinInvocations:
5667 case glslang::EOpMaxInvocations:
5668 case glslang::EOpAddInvocations:
5669 case glslang::EOpMinInvocationsNonUniform:
5670 case glslang::EOpMaxInvocationsNonUniform:
5671 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005672 case glslang::EOpMinInvocationsInclusiveScan:
5673 case glslang::EOpMaxInvocationsInclusiveScan:
5674 case glslang::EOpAddInvocationsInclusiveScan:
5675 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5676 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5677 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5678 case glslang::EOpMinInvocationsExclusiveScan:
5679 case glslang::EOpMaxInvocationsExclusiveScan:
5680 case glslang::EOpAddInvocationsExclusiveScan:
5681 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5682 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5683 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08005684 {
5685 std::vector<spv::Id> operands;
5686 operands.push_back(operand);
5687 return createInvocationsOperation(op, typeId, operands, typeProxy);
5688 }
John Kessenich66011cb2018-03-06 16:12:04 -07005689 case glslang::EOpSubgroupAll:
5690 case glslang::EOpSubgroupAny:
5691 case glslang::EOpSubgroupAllEqual:
5692 case glslang::EOpSubgroupBroadcastFirst:
5693 case glslang::EOpSubgroupBallot:
5694 case glslang::EOpSubgroupInverseBallot:
5695 case glslang::EOpSubgroupBallotBitCount:
5696 case glslang::EOpSubgroupBallotInclusiveBitCount:
5697 case glslang::EOpSubgroupBallotExclusiveBitCount:
5698 case glslang::EOpSubgroupBallotFindLSB:
5699 case glslang::EOpSubgroupBallotFindMSB:
5700 case glslang::EOpSubgroupAdd:
5701 case glslang::EOpSubgroupMul:
5702 case glslang::EOpSubgroupMin:
5703 case glslang::EOpSubgroupMax:
5704 case glslang::EOpSubgroupAnd:
5705 case glslang::EOpSubgroupOr:
5706 case glslang::EOpSubgroupXor:
5707 case glslang::EOpSubgroupInclusiveAdd:
5708 case glslang::EOpSubgroupInclusiveMul:
5709 case glslang::EOpSubgroupInclusiveMin:
5710 case glslang::EOpSubgroupInclusiveMax:
5711 case glslang::EOpSubgroupInclusiveAnd:
5712 case glslang::EOpSubgroupInclusiveOr:
5713 case glslang::EOpSubgroupInclusiveXor:
5714 case glslang::EOpSubgroupExclusiveAdd:
5715 case glslang::EOpSubgroupExclusiveMul:
5716 case glslang::EOpSubgroupExclusiveMin:
5717 case glslang::EOpSubgroupExclusiveMax:
5718 case glslang::EOpSubgroupExclusiveAnd:
5719 case glslang::EOpSubgroupExclusiveOr:
5720 case glslang::EOpSubgroupExclusiveXor:
5721 case glslang::EOpSubgroupQuadSwapHorizontal:
5722 case glslang::EOpSubgroupQuadSwapVertical:
5723 case glslang::EOpSubgroupQuadSwapDiagonal: {
5724 std::vector<spv::Id> operands;
5725 operands.push_back(operand);
5726 return createSubgroupOperation(op, typeId, operands, typeProxy);
5727 }
Rex Xu9d93a232016-05-05 12:30:44 +08005728 case glslang::EOpMbcnt:
5729 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5730 libCall = spv::MbcntAMD;
5731 break;
5732
5733 case glslang::EOpCubeFaceIndex:
5734 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5735 libCall = spv::CubeFaceIndexAMD;
5736 break;
5737
5738 case glslang::EOpCubeFaceCoord:
5739 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5740 libCall = spv::CubeFaceCoordAMD;
5741 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005742 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005743 unaryOp = spv::OpGroupNonUniformPartitionNV;
5744 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005745 case glslang::EOpConstructReference:
5746 unaryOp = spv::OpBitcast;
5747 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005748#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05005749
5750 case glslang::EOpCopyObject:
5751 unaryOp = spv::OpCopyObject;
5752 break;
5753
John Kessenich140f3df2015-06-26 16:58:36 -06005754 default:
5755 return 0;
5756 }
5757
5758 spv::Id id;
5759 if (libCall >= 0) {
5760 std::vector<spv::Id> args;
5761 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005762 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005763 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005764 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005765 }
John Kessenich140f3df2015-06-26 16:58:36 -06005766
John Kessenichead86222018-03-28 18:01:20 -06005767 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005768 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005769 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005770}
5771
John Kessenich7a53f762016-01-20 11:19:27 -07005772// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005773spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5774 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005775{
5776 // Handle unary operations vector by vector.
5777 // The result type is the same type as the original type.
5778 // The algorithm is to:
5779 // - break the matrix into vectors
5780 // - apply the operation to each vector
5781 // - make a matrix out the vector results
5782
5783 // get the types sorted out
5784 int numCols = builder.getNumColumns(operand);
5785 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005786 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5787 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005788 std::vector<spv::Id> results;
5789
5790 // do each vector op
5791 for (int c = 0; c < numCols; ++c) {
5792 std::vector<unsigned int> indexes;
5793 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005794 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5795 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005796 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005797 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005798 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005799 }
5800
5801 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005802 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005803 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005804 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005805}
5806
John Kessenichad7645f2018-06-04 19:11:25 -06005807// For converting integers where both the bitwidth and the signedness could
5808// change, but only do the width change here. The caller is still responsible
5809// for the signedness conversion.
5810spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005811{
John Kessenichad7645f2018-06-04 19:11:25 -06005812 // Get the result type width, based on the type to convert to.
5813 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005814 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005815 case glslang::EOpConvInt16ToUint8:
5816 case glslang::EOpConvIntToUint8:
5817 case glslang::EOpConvInt64ToUint8:
5818 case glslang::EOpConvUint16ToInt8:
5819 case glslang::EOpConvUintToInt8:
5820 case glslang::EOpConvUint64ToInt8:
5821 width = 8;
5822 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005823 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005824 case glslang::EOpConvIntToUint16:
5825 case glslang::EOpConvInt64ToUint16:
5826 case glslang::EOpConvUint8ToInt16:
5827 case glslang::EOpConvUintToInt16:
5828 case glslang::EOpConvUint64ToInt16:
5829 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005830 break;
5831 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005832 case glslang::EOpConvInt16ToUint:
5833 case glslang::EOpConvInt64ToUint:
5834 case glslang::EOpConvUint8ToInt:
5835 case glslang::EOpConvUint16ToInt:
5836 case glslang::EOpConvUint64ToInt:
5837 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005838 break;
5839 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005840 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005841 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005842 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005843 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005844 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005845 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005846 break;
5847
5848 default:
5849 assert(false && "Default missing");
5850 break;
5851 }
5852
John Kessenichad7645f2018-06-04 19:11:25 -06005853 // Get the conversion operation and result type,
5854 // based on the target width, but the source type.
5855 spv::Id type = spv::NoType;
5856 spv::Op convOp = spv::OpNop;
5857 switch(op) {
5858 case glslang::EOpConvInt8ToUint16:
5859 case glslang::EOpConvInt8ToUint:
5860 case glslang::EOpConvInt8ToUint64:
5861 case glslang::EOpConvInt16ToUint8:
5862 case glslang::EOpConvInt16ToUint:
5863 case glslang::EOpConvInt16ToUint64:
5864 case glslang::EOpConvIntToUint8:
5865 case glslang::EOpConvIntToUint16:
5866 case glslang::EOpConvIntToUint64:
5867 case glslang::EOpConvInt64ToUint8:
5868 case glslang::EOpConvInt64ToUint16:
5869 case glslang::EOpConvInt64ToUint:
5870 convOp = spv::OpSConvert;
5871 type = builder.makeIntType(width);
5872 break;
5873 default:
5874 convOp = spv::OpUConvert;
5875 type = builder.makeUintType(width);
5876 break;
5877 }
5878
John Kessenich66011cb2018-03-06 16:12:04 -07005879 if (vectorSize > 0)
5880 type = builder.makeVectorType(type, vectorSize);
5881
John Kessenichad7645f2018-06-04 19:11:25 -06005882 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005883}
5884
John Kessenichead86222018-03-28 18:01:20 -06005885spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5886 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005887{
5888 spv::Op convOp = spv::OpNop;
5889 spv::Id zero = 0;
5890 spv::Id one = 0;
5891
5892 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5893
5894 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005895 case glslang::EOpConvInt8ToBool:
5896 case glslang::EOpConvUint8ToBool:
5897 zero = builder.makeUint8Constant(0);
5898 zero = makeSmearedConstant(zero, vectorSize);
5899 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005900 case glslang::EOpConvInt16ToBool:
5901 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005902 zero = builder.makeUint16Constant(0);
5903 zero = makeSmearedConstant(zero, vectorSize);
5904 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5905 case glslang::EOpConvIntToBool:
5906 case glslang::EOpConvUintToBool:
5907 zero = builder.makeUintConstant(0);
5908 zero = makeSmearedConstant(zero, vectorSize);
5909 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5910 case glslang::EOpConvInt64ToBool:
5911 case glslang::EOpConvUint64ToBool:
5912 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005913 zero = makeSmearedConstant(zero, vectorSize);
5914 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5915
5916 case glslang::EOpConvFloatToBool:
5917 zero = builder.makeFloatConstant(0.0F);
5918 zero = makeSmearedConstant(zero, vectorSize);
5919 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5920
5921 case glslang::EOpConvDoubleToBool:
5922 zero = builder.makeDoubleConstant(0.0);
5923 zero = makeSmearedConstant(zero, vectorSize);
5924 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5925
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005926 case glslang::EOpConvFloat16ToBool:
5927 zero = builder.makeFloat16Constant(0.0F);
5928 zero = makeSmearedConstant(zero, vectorSize);
5929 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005930
John Kessenich140f3df2015-06-26 16:58:36 -06005931 case glslang::EOpConvBoolToFloat:
5932 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005933 zero = builder.makeFloatConstant(0.0F);
5934 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005935 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005936
John Kessenich140f3df2015-06-26 16:58:36 -06005937 case glslang::EOpConvBoolToDouble:
5938 convOp = spv::OpSelect;
5939 zero = builder.makeDoubleConstant(0.0);
5940 one = builder.makeDoubleConstant(1.0);
5941 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005942
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005943 case glslang::EOpConvBoolToFloat16:
5944 convOp = spv::OpSelect;
5945 zero = builder.makeFloat16Constant(0.0F);
5946 one = builder.makeFloat16Constant(1.0F);
5947 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005948
5949 case glslang::EOpConvBoolToInt8:
5950 zero = builder.makeInt8Constant(0);
5951 one = builder.makeInt8Constant(1);
5952 convOp = spv::OpSelect;
5953 break;
5954
5955 case glslang::EOpConvBoolToUint8:
5956 zero = builder.makeUint8Constant(0);
5957 one = builder.makeUint8Constant(1);
5958 convOp = spv::OpSelect;
5959 break;
5960
5961 case glslang::EOpConvBoolToInt16:
5962 zero = builder.makeInt16Constant(0);
5963 one = builder.makeInt16Constant(1);
5964 convOp = spv::OpSelect;
5965 break;
5966
5967 case glslang::EOpConvBoolToUint16:
5968 zero = builder.makeUint16Constant(0);
5969 one = builder.makeUint16Constant(1);
5970 convOp = spv::OpSelect;
5971 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005972
John Kessenich140f3df2015-06-26 16:58:36 -06005973 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005974 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005975 if (op == glslang::EOpConvBoolToInt64)
5976 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005977 else
5978 zero = builder.makeIntConstant(0);
5979
5980 if (op == glslang::EOpConvBoolToInt64)
5981 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005982 else
5983 one = builder.makeIntConstant(1);
5984
John Kessenich140f3df2015-06-26 16:58:36 -06005985 convOp = spv::OpSelect;
5986 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005987
John Kessenich140f3df2015-06-26 16:58:36 -06005988 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005989 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005990 if (op == glslang::EOpConvBoolToUint64)
5991 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005992 else
5993 zero = builder.makeUintConstant(0);
5994
5995 if (op == glslang::EOpConvBoolToUint64)
5996 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005997 else
5998 one = builder.makeUintConstant(1);
5999
John Kessenich140f3df2015-06-26 16:58:36 -06006000 convOp = spv::OpSelect;
6001 break;
6002
John Kessenich66011cb2018-03-06 16:12:04 -07006003 case glslang::EOpConvInt8ToFloat16:
6004 case glslang::EOpConvInt8ToFloat:
6005 case glslang::EOpConvInt8ToDouble:
6006 case glslang::EOpConvInt16ToFloat16:
6007 case glslang::EOpConvInt16ToFloat:
6008 case glslang::EOpConvInt16ToDouble:
6009 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006010 case glslang::EOpConvIntToFloat:
6011 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006012 case glslang::EOpConvInt64ToFloat:
6013 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006014 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006015 convOp = spv::OpConvertSToF;
6016 break;
6017
John Kessenich66011cb2018-03-06 16:12:04 -07006018 case glslang::EOpConvUint8ToFloat16:
6019 case glslang::EOpConvUint8ToFloat:
6020 case glslang::EOpConvUint8ToDouble:
6021 case glslang::EOpConvUint16ToFloat16:
6022 case glslang::EOpConvUint16ToFloat:
6023 case glslang::EOpConvUint16ToDouble:
6024 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006025 case glslang::EOpConvUintToFloat:
6026 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006027 case glslang::EOpConvUint64ToFloat:
6028 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006029 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006030 convOp = spv::OpConvertUToF;
6031 break;
6032
6033 case glslang::EOpConvDoubleToFloat:
6034 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006035 case glslang::EOpConvDoubleToFloat16:
6036 case glslang::EOpConvFloat16ToDouble:
6037 case glslang::EOpConvFloatToFloat16:
6038 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06006039 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08006040 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06006041 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06006042 break;
6043
John Kessenich66011cb2018-03-06 16:12:04 -07006044 case glslang::EOpConvFloat16ToInt8:
6045 case glslang::EOpConvFloatToInt8:
6046 case glslang::EOpConvDoubleToInt8:
6047 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006048 case glslang::EOpConvFloatToInt16:
6049 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006050 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006051 case glslang::EOpConvFloatToInt:
6052 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006053 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006054 case glslang::EOpConvFloatToInt64:
6055 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006056 convOp = spv::OpConvertFToS;
6057 break;
6058
John Kessenich66011cb2018-03-06 16:12:04 -07006059 case glslang::EOpConvUint8ToInt8:
6060 case glslang::EOpConvInt8ToUint8:
6061 case glslang::EOpConvUint16ToInt16:
6062 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006063 case glslang::EOpConvUintToInt:
6064 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006065 case glslang::EOpConvUint64ToInt64:
6066 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006067 if (builder.isInSpecConstCodeGenMode()) {
6068 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006069 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6070 zero = builder.makeUint8Constant(0);
6071 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006072 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006073 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6074 zero = builder.makeUint64Constant(0);
6075 } else {
Rex Xucabbb782017-03-24 13:41:14 +08006076 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006077 }
qining189b2032016-04-12 23:16:20 -04006078 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006079 // Use OpIAdd, instead of OpBitcast to do the conversion when
6080 // generating for OpSpecConstantOp instruction.
6081 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6082 }
6083 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006084 convOp = spv::OpBitcast;
6085 break;
6086
John Kessenich66011cb2018-03-06 16:12:04 -07006087 case glslang::EOpConvFloat16ToUint8:
6088 case glslang::EOpConvFloatToUint8:
6089 case glslang::EOpConvDoubleToUint8:
6090 case glslang::EOpConvFloat16ToUint16:
6091 case glslang::EOpConvFloatToUint16:
6092 case glslang::EOpConvDoubleToUint16:
6093 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006094 case glslang::EOpConvFloatToUint:
6095 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006096 case glslang::EOpConvFloatToUint64:
6097 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006098 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006099 convOp = spv::OpConvertFToU;
6100 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006101
John Kessenich66011cb2018-03-06 16:12:04 -07006102 case glslang::EOpConvInt8ToInt16:
6103 case glslang::EOpConvInt8ToInt:
6104 case glslang::EOpConvInt8ToInt64:
6105 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006106 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006107 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006108 case glslang::EOpConvIntToInt8:
6109 case glslang::EOpConvIntToInt16:
6110 case glslang::EOpConvIntToInt64:
6111 case glslang::EOpConvInt64ToInt8:
6112 case glslang::EOpConvInt64ToInt16:
6113 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006114 convOp = spv::OpSConvert;
6115 break;
6116
John Kessenich66011cb2018-03-06 16:12:04 -07006117 case glslang::EOpConvUint8ToUint16:
6118 case glslang::EOpConvUint8ToUint:
6119 case glslang::EOpConvUint8ToUint64:
6120 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006121 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006122 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006123 case glslang::EOpConvUintToUint8:
6124 case glslang::EOpConvUintToUint16:
6125 case glslang::EOpConvUintToUint64:
6126 case glslang::EOpConvUint64ToUint8:
6127 case glslang::EOpConvUint64ToUint16:
6128 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006129 convOp = spv::OpUConvert;
6130 break;
6131
John Kessenich66011cb2018-03-06 16:12:04 -07006132 case glslang::EOpConvInt8ToUint16:
6133 case glslang::EOpConvInt8ToUint:
6134 case glslang::EOpConvInt8ToUint64:
6135 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006136 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006137 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006138 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006139 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006140 case glslang::EOpConvIntToUint64:
6141 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006142 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006143 case glslang::EOpConvInt64ToUint:
6144 case glslang::EOpConvUint8ToInt16:
6145 case glslang::EOpConvUint8ToInt:
6146 case glslang::EOpConvUint8ToInt64:
6147 case glslang::EOpConvUint16ToInt8:
6148 case glslang::EOpConvUint16ToInt:
6149 case glslang::EOpConvUint16ToInt64:
6150 case glslang::EOpConvUintToInt8:
6151 case glslang::EOpConvUintToInt16:
6152 case glslang::EOpConvUintToInt64:
6153 case glslang::EOpConvUint64ToInt8:
6154 case glslang::EOpConvUint64ToInt16:
6155 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006156 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006157 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006158
6159 if (builder.isInSpecConstCodeGenMode()) {
6160 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006161 switch(op) {
6162 case glslang::EOpConvInt16ToUint8:
6163 case glslang::EOpConvIntToUint8:
6164 case glslang::EOpConvInt64ToUint8:
6165 case glslang::EOpConvUint16ToInt8:
6166 case glslang::EOpConvUintToInt8:
6167 case glslang::EOpConvUint64ToInt8:
6168 zero = builder.makeUint8Constant(0);
6169 break;
6170 case glslang::EOpConvInt8ToUint16:
6171 case glslang::EOpConvIntToUint16:
6172 case glslang::EOpConvInt64ToUint16:
6173 case glslang::EOpConvUint8ToInt16:
6174 case glslang::EOpConvUintToInt16:
6175 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006176 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006177 break;
6178 case glslang::EOpConvInt8ToUint:
6179 case glslang::EOpConvInt16ToUint:
6180 case glslang::EOpConvInt64ToUint:
6181 case glslang::EOpConvUint8ToInt:
6182 case glslang::EOpConvUint16ToInt:
6183 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006184 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006185 break;
6186 case glslang::EOpConvInt8ToUint64:
6187 case glslang::EOpConvInt16ToUint64:
6188 case glslang::EOpConvIntToUint64:
6189 case glslang::EOpConvUint8ToInt64:
6190 case glslang::EOpConvUint16ToInt64:
6191 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006192 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006193 break;
6194 default:
6195 assert(false && "Default missing");
6196 break;
6197 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006198 zero = makeSmearedConstant(zero, vectorSize);
6199 // Use OpIAdd, instead of OpBitcast to do the conversion when
6200 // generating for OpSpecConstantOp instruction.
6201 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6202 }
6203 // For normal run-time conversion instruction, use OpBitcast.
6204 convOp = spv::OpBitcast;
6205 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006206 case glslang::EOpConvUint64ToPtr:
6207 convOp = spv::OpConvertUToPtr;
6208 break;
6209 case glslang::EOpConvPtrToUint64:
6210 convOp = spv::OpConvertPtrToU;
6211 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006212 default:
6213 break;
6214 }
6215
6216 spv::Id result = 0;
6217 if (convOp == spv::OpNop)
6218 return result;
6219
6220 if (convOp == spv::OpSelect) {
6221 zero = makeSmearedConstant(zero, vectorSize);
6222 one = makeSmearedConstant(one, vectorSize);
6223 result = builder.createTriOp(convOp, destType, operand, one, zero);
6224 } else
6225 result = builder.createUnaryOp(convOp, destType, operand);
6226
John Kessenichead86222018-03-28 18:01:20 -06006227 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006228 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006229 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006230}
6231
6232spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6233{
6234 if (vectorSize == 0)
6235 return constant;
6236
6237 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6238 std::vector<spv::Id> components;
6239 for (int c = 0; c < vectorSize; ++c)
6240 components.push_back(constant);
6241 return builder.makeCompositeConstant(vectorTypeId, components);
6242}
6243
John Kessenich426394d2015-07-23 10:22:48 -06006244// For glslang ops that map to SPV atomic opCodes
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006245spv::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 -06006246{
6247 spv::Op opCode = spv::OpNop;
6248
6249 switch (op) {
6250 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006251 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006252 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006253 opCode = spv::OpAtomicIAdd;
6254 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006255 case glslang::EOpAtomicCounterSubtract:
6256 opCode = spv::OpAtomicISub;
6257 break;
John Kessenich426394d2015-07-23 10:22:48 -06006258 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006259 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006260 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006261 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006262 break;
6263 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006264 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006265 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006266 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006267 break;
6268 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006269 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006270 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006271 opCode = spv::OpAtomicAnd;
6272 break;
6273 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006274 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006275 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006276 opCode = spv::OpAtomicOr;
6277 break;
6278 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006279 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006280 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006281 opCode = spv::OpAtomicXor;
6282 break;
6283 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006284 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006285 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006286 opCode = spv::OpAtomicExchange;
6287 break;
6288 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006289 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006290 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006291 opCode = spv::OpAtomicCompareExchange;
6292 break;
6293 case glslang::EOpAtomicCounterIncrement:
6294 opCode = spv::OpAtomicIIncrement;
6295 break;
6296 case glslang::EOpAtomicCounterDecrement:
6297 opCode = spv::OpAtomicIDecrement;
6298 break;
6299 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006300 case glslang::EOpImageAtomicLoad:
6301 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006302 opCode = spv::OpAtomicLoad;
6303 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006304 case glslang::EOpAtomicStore:
6305 case glslang::EOpImageAtomicStore:
6306 opCode = spv::OpAtomicStore;
6307 break;
John Kessenich426394d2015-07-23 10:22:48 -06006308 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006309 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006310 break;
6311 }
6312
Rex Xue8fe8b02017-09-26 15:42:56 +08006313 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6314 builder.addCapability(spv::CapabilityInt64Atomics);
6315
John Kessenich426394d2015-07-23 10:22:48 -06006316 // Sort out the operands
6317 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006318 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006319 // - compare-exchange swaps the value and comparator
6320 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006321 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006322 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6323 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6324 spv::Id scopeId;
6325 if (glslangIntermediate->usingVulkanMemoryModel()) {
6326 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6327 } else {
6328 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6329 }
6330 // semantics default to relaxed
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006331 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.volatil ? spv::MemorySemanticsVolatileMask : spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006332 spv::Id semanticsId2 = semanticsId;
6333
6334 pointerId = operands[0];
6335 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6336 // no additional operands
6337 } else if (opCode == spv::OpAtomicCompareExchange) {
6338 compareId = operands[1];
6339 valueId = operands[2];
6340 if (operands.size() > 3) {
6341 scopeId = operands[3];
6342 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6343 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6344 }
6345 } else if (opCode == spv::OpAtomicLoad) {
6346 if (operands.size() > 1) {
6347 scopeId = operands[1];
6348 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6349 }
6350 } else {
6351 // atomic store or RMW
6352 valueId = operands[1];
6353 if (operands.size() > 2) {
6354 scopeId = operands[2];
6355 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6356 }
Rex Xu04db3f52015-09-16 11:44:02 +08006357 }
John Kessenich426394d2015-07-23 10:22:48 -06006358
Jeff Bolz36831c92018-09-05 10:11:41 -05006359 // Check for capabilities
6360 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006361 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6362 spv::MemorySemanticsMakeVisibleKHRMask |
6363 spv::MemorySemanticsOutputMemoryKHRMask |
6364 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006365 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6366 }
John Kessenich426394d2015-07-23 10:22:48 -06006367
Jeff Bolz36831c92018-09-05 10:11:41 -05006368 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6369 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6370 }
John Kessenich48d6e792017-10-06 21:21:48 -06006371
Jeff Bolz36831c92018-09-05 10:11:41 -05006372 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6373 spvAtomicOperands.push_back(pointerId);
6374 spvAtomicOperands.push_back(scopeId);
6375 spvAtomicOperands.push_back(semanticsId);
6376 if (opCode == spv::OpAtomicCompareExchange) {
6377 spvAtomicOperands.push_back(semanticsId2);
6378 spvAtomicOperands.push_back(valueId);
6379 spvAtomicOperands.push_back(compareId);
6380 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6381 spvAtomicOperands.push_back(valueId);
6382 }
John Kessenich48d6e792017-10-06 21:21:48 -06006383
Jeff Bolz36831c92018-09-05 10:11:41 -05006384 if (opCode == spv::OpAtomicStore) {
6385 builder.createNoResultOp(opCode, spvAtomicOperands);
6386 return 0;
6387 } else {
6388 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6389
6390 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6391 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6392 if (op == glslang::EOpAtomicCounterDecrement)
6393 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6394
6395 return resultId;
6396 }
John Kessenich426394d2015-07-23 10:22:48 -06006397}
6398
John Kessenicha28f7a72019-08-06 07:00:58 -06006399#ifndef GLSLANG_WEB
6400
John Kessenich91cef522016-05-05 16:45:40 -06006401// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006402spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006403{
John Kessenich66011cb2018-03-06 16:12:04 -07006404 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6405 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006406
Rex Xu51596642016-09-21 18:56:12 +08006407 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006408 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006409 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6410
chaocf200da82016-12-20 12:44:35 -08006411 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6412 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006413 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6414 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006415 } else if (op == glslang::EOpAnyInvocation ||
6416 op == glslang::EOpAllInvocations ||
6417 op == glslang::EOpAllInvocationsEqual) {
6418 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6419 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006420 } else {
6421 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006422 if (op == glslang::EOpMinInvocationsNonUniform ||
6423 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006424 op == glslang::EOpAddInvocationsNonUniform ||
6425 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6426 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6427 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6428 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6429 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6430 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006431 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006432
Rex Xu430ef402016-10-14 17:22:23 +08006433 switch (op) {
6434 case glslang::EOpMinInvocations:
6435 case glslang::EOpMaxInvocations:
6436 case glslang::EOpAddInvocations:
6437 case glslang::EOpMinInvocationsNonUniform:
6438 case glslang::EOpMaxInvocationsNonUniform:
6439 case glslang::EOpAddInvocationsNonUniform:
6440 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006441 break;
6442 case glslang::EOpMinInvocationsInclusiveScan:
6443 case glslang::EOpMaxInvocationsInclusiveScan:
6444 case glslang::EOpAddInvocationsInclusiveScan:
6445 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6446 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6447 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6448 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006449 break;
6450 case glslang::EOpMinInvocationsExclusiveScan:
6451 case glslang::EOpMaxInvocationsExclusiveScan:
6452 case glslang::EOpAddInvocationsExclusiveScan:
6453 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6454 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6455 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6456 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006457 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006458 default:
6459 break;
Rex Xu430ef402016-10-14 17:22:23 +08006460 }
John Kessenich149afc32018-08-14 13:31:43 -06006461 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6462 spvGroupOperands.push_back(scope);
6463 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006464 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006465 spvGroupOperands.push_back(groupOp);
6466 }
Rex Xu51596642016-09-21 18:56:12 +08006467 }
6468
John Kessenich149afc32018-08-14 13:31:43 -06006469 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6470 spv::IdImmediate op = { true, *opIt };
6471 spvGroupOperands.push_back(op);
6472 }
John Kessenich91cef522016-05-05 16:45:40 -06006473
6474 switch (op) {
6475 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006476 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006477 break;
John Kessenich91cef522016-05-05 16:45:40 -06006478 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006479 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006480 break;
John Kessenich91cef522016-05-05 16:45:40 -06006481 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006482 opCode = spv::OpSubgroupAllEqualKHR;
6483 break;
Rex Xu51596642016-09-21 18:56:12 +08006484 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006485 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006486 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006487 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006488 break;
6489 case glslang::EOpReadFirstInvocation:
6490 opCode = spv::OpSubgroupFirstInvocationKHR;
6491 break;
6492 case glslang::EOpBallot:
6493 {
6494 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6495 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6496 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6497 //
6498 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6499 //
6500 spv::Id uintType = builder.makeUintType(32);
6501 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6502 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6503
6504 std::vector<spv::Id> components;
6505 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6506 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6507
6508 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6509 return builder.createUnaryOp(spv::OpBitcast, typeId,
6510 builder.createCompositeConstruct(uvec2Type, components));
6511 }
6512
Rex Xu9d93a232016-05-05 12:30:44 +08006513 case glslang::EOpMinInvocations:
6514 case glslang::EOpMaxInvocations:
6515 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006516 case glslang::EOpMinInvocationsInclusiveScan:
6517 case glslang::EOpMaxInvocationsInclusiveScan:
6518 case glslang::EOpAddInvocationsInclusiveScan:
6519 case glslang::EOpMinInvocationsExclusiveScan:
6520 case glslang::EOpMaxInvocationsExclusiveScan:
6521 case glslang::EOpAddInvocationsExclusiveScan:
6522 if (op == glslang::EOpMinInvocations ||
6523 op == glslang::EOpMinInvocationsInclusiveScan ||
6524 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006525 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006526 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006527 else {
6528 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006529 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006530 else
Rex Xu51596642016-09-21 18:56:12 +08006531 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006532 }
Rex Xu430ef402016-10-14 17:22:23 +08006533 } else if (op == glslang::EOpMaxInvocations ||
6534 op == glslang::EOpMaxInvocationsInclusiveScan ||
6535 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006536 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006537 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006538 else {
6539 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006540 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006541 else
Rex Xu51596642016-09-21 18:56:12 +08006542 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006543 }
6544 } else {
6545 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006546 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006547 else
Rex Xu51596642016-09-21 18:56:12 +08006548 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006549 }
6550
Rex Xu2bbbe062016-08-23 15:41:05 +08006551 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006552 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006553
6554 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006555 case glslang::EOpMinInvocationsNonUniform:
6556 case glslang::EOpMaxInvocationsNonUniform:
6557 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006558 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6559 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6560 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6561 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6562 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6563 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6564 if (op == glslang::EOpMinInvocationsNonUniform ||
6565 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6566 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006567 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006568 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006569 else {
6570 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006571 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006572 else
Rex Xu51596642016-09-21 18:56:12 +08006573 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006574 }
6575 }
Rex Xu430ef402016-10-14 17:22:23 +08006576 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6577 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6578 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006579 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006580 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006581 else {
6582 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006583 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006584 else
Rex Xu51596642016-09-21 18:56:12 +08006585 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006586 }
6587 }
6588 else {
6589 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006590 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006591 else
Rex Xu51596642016-09-21 18:56:12 +08006592 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006593 }
6594
Rex Xu2bbbe062016-08-23 15:41:05 +08006595 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006596 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006597
6598 break;
John Kessenich91cef522016-05-05 16:45:40 -06006599 default:
6600 logger->missingFunctionality("invocation operation");
6601 return spv::NoResult;
6602 }
Rex Xu51596642016-09-21 18:56:12 +08006603
6604 assert(opCode != spv::OpNop);
6605 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006606}
6607
Rex Xu2bbbe062016-08-23 15:41:05 +08006608// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006609spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6610 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006611{
6612 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6613 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006614 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006615 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006616 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6617 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6618 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
6619
6620 // Handle group invocation operations scalar by scalar.
6621 // The result type is the same type as the original type.
6622 // The algorithm is to:
6623 // - break the vector into scalars
6624 // - apply the operation to each scalar
6625 // - make a vector out the scalar results
6626
6627 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006628 int numComponents = builder.getNumComponents(operands[0]);
6629 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006630 std::vector<spv::Id> results;
6631
6632 // do each scalar op
6633 for (int comp = 0; comp < numComponents; ++comp) {
6634 std::vector<unsigned int> indexes;
6635 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006636 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6637 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006638 if (op == spv::OpSubgroupReadInvocationKHR) {
6639 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006640 spv::IdImmediate operand = { true, operands[1] };
6641 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006642 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006643 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6644 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006645 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006646 spv::IdImmediate operand = { true, operands[1] };
6647 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006648 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006649 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6650 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006651 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006652 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006653 spvGroupOperands.push_back(scalar);
6654 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006655
Rex Xub7072052016-09-26 15:53:40 +08006656 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006657 }
6658
6659 // put the pieces together
6660 return builder.createCompositeConstruct(typeId, results);
6661}
Rex Xu2bbbe062016-08-23 15:41:05 +08006662
John Kessenich66011cb2018-03-06 16:12:04 -07006663// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006664spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6665 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006666{
6667 // Add the required capabilities.
6668 switch (op) {
6669 case glslang::EOpSubgroupElect:
6670 builder.addCapability(spv::CapabilityGroupNonUniform);
6671 break;
6672 case glslang::EOpSubgroupAll:
6673 case glslang::EOpSubgroupAny:
6674 case glslang::EOpSubgroupAllEqual:
6675 builder.addCapability(spv::CapabilityGroupNonUniform);
6676 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6677 break;
6678 case glslang::EOpSubgroupBroadcast:
6679 case glslang::EOpSubgroupBroadcastFirst:
6680 case glslang::EOpSubgroupBallot:
6681 case glslang::EOpSubgroupInverseBallot:
6682 case glslang::EOpSubgroupBallotBitExtract:
6683 case glslang::EOpSubgroupBallotBitCount:
6684 case glslang::EOpSubgroupBallotInclusiveBitCount:
6685 case glslang::EOpSubgroupBallotExclusiveBitCount:
6686 case glslang::EOpSubgroupBallotFindLSB:
6687 case glslang::EOpSubgroupBallotFindMSB:
6688 builder.addCapability(spv::CapabilityGroupNonUniform);
6689 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6690 break;
6691 case glslang::EOpSubgroupShuffle:
6692 case glslang::EOpSubgroupShuffleXor:
6693 builder.addCapability(spv::CapabilityGroupNonUniform);
6694 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6695 break;
6696 case glslang::EOpSubgroupShuffleUp:
6697 case glslang::EOpSubgroupShuffleDown:
6698 builder.addCapability(spv::CapabilityGroupNonUniform);
6699 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6700 break;
6701 case glslang::EOpSubgroupAdd:
6702 case glslang::EOpSubgroupMul:
6703 case glslang::EOpSubgroupMin:
6704 case glslang::EOpSubgroupMax:
6705 case glslang::EOpSubgroupAnd:
6706 case glslang::EOpSubgroupOr:
6707 case glslang::EOpSubgroupXor:
6708 case glslang::EOpSubgroupInclusiveAdd:
6709 case glslang::EOpSubgroupInclusiveMul:
6710 case glslang::EOpSubgroupInclusiveMin:
6711 case glslang::EOpSubgroupInclusiveMax:
6712 case glslang::EOpSubgroupInclusiveAnd:
6713 case glslang::EOpSubgroupInclusiveOr:
6714 case glslang::EOpSubgroupInclusiveXor:
6715 case glslang::EOpSubgroupExclusiveAdd:
6716 case glslang::EOpSubgroupExclusiveMul:
6717 case glslang::EOpSubgroupExclusiveMin:
6718 case glslang::EOpSubgroupExclusiveMax:
6719 case glslang::EOpSubgroupExclusiveAnd:
6720 case glslang::EOpSubgroupExclusiveOr:
6721 case glslang::EOpSubgroupExclusiveXor:
6722 builder.addCapability(spv::CapabilityGroupNonUniform);
6723 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6724 break;
6725 case glslang::EOpSubgroupClusteredAdd:
6726 case glslang::EOpSubgroupClusteredMul:
6727 case glslang::EOpSubgroupClusteredMin:
6728 case glslang::EOpSubgroupClusteredMax:
6729 case glslang::EOpSubgroupClusteredAnd:
6730 case glslang::EOpSubgroupClusteredOr:
6731 case glslang::EOpSubgroupClusteredXor:
6732 builder.addCapability(spv::CapabilityGroupNonUniform);
6733 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6734 break;
6735 case glslang::EOpSubgroupQuadBroadcast:
6736 case glslang::EOpSubgroupQuadSwapHorizontal:
6737 case glslang::EOpSubgroupQuadSwapVertical:
6738 case glslang::EOpSubgroupQuadSwapDiagonal:
6739 builder.addCapability(spv::CapabilityGroupNonUniform);
6740 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6741 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006742 case glslang::EOpSubgroupPartitionedAdd:
6743 case glslang::EOpSubgroupPartitionedMul:
6744 case glslang::EOpSubgroupPartitionedMin:
6745 case glslang::EOpSubgroupPartitionedMax:
6746 case glslang::EOpSubgroupPartitionedAnd:
6747 case glslang::EOpSubgroupPartitionedOr:
6748 case glslang::EOpSubgroupPartitionedXor:
6749 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6750 case glslang::EOpSubgroupPartitionedInclusiveMul:
6751 case glslang::EOpSubgroupPartitionedInclusiveMin:
6752 case glslang::EOpSubgroupPartitionedInclusiveMax:
6753 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6754 case glslang::EOpSubgroupPartitionedInclusiveOr:
6755 case glslang::EOpSubgroupPartitionedInclusiveXor:
6756 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6757 case glslang::EOpSubgroupPartitionedExclusiveMul:
6758 case glslang::EOpSubgroupPartitionedExclusiveMin:
6759 case glslang::EOpSubgroupPartitionedExclusiveMax:
6760 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6761 case glslang::EOpSubgroupPartitionedExclusiveOr:
6762 case glslang::EOpSubgroupPartitionedExclusiveXor:
6763 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6764 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6765 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006766 default: assert(0 && "Unhandled subgroup operation!");
6767 }
6768
6769 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6770 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6771 const bool isBool = typeProxy == glslang::EbtBool;
6772
6773 spv::Op opCode = spv::OpNop;
6774
6775 // Figure out which opcode to use.
6776 switch (op) {
6777 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6778 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6779 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6780 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6781 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6782 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6783 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6784 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6785 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6786 case glslang::EOpSubgroupBallotBitCount:
6787 case glslang::EOpSubgroupBallotInclusiveBitCount:
6788 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6789 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6790 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6791 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6792 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6793 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6794 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6795 case glslang::EOpSubgroupAdd:
6796 case glslang::EOpSubgroupInclusiveAdd:
6797 case glslang::EOpSubgroupExclusiveAdd:
6798 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006799 case glslang::EOpSubgroupPartitionedAdd:
6800 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6801 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07006802 if (isFloat) {
6803 opCode = spv::OpGroupNonUniformFAdd;
6804 } else {
6805 opCode = spv::OpGroupNonUniformIAdd;
6806 }
6807 break;
6808 case glslang::EOpSubgroupMul:
6809 case glslang::EOpSubgroupInclusiveMul:
6810 case glslang::EOpSubgroupExclusiveMul:
6811 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006812 case glslang::EOpSubgroupPartitionedMul:
6813 case glslang::EOpSubgroupPartitionedInclusiveMul:
6814 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07006815 if (isFloat) {
6816 opCode = spv::OpGroupNonUniformFMul;
6817 } else {
6818 opCode = spv::OpGroupNonUniformIMul;
6819 }
6820 break;
6821 case glslang::EOpSubgroupMin:
6822 case glslang::EOpSubgroupInclusiveMin:
6823 case glslang::EOpSubgroupExclusiveMin:
6824 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006825 case glslang::EOpSubgroupPartitionedMin:
6826 case glslang::EOpSubgroupPartitionedInclusiveMin:
6827 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07006828 if (isFloat) {
6829 opCode = spv::OpGroupNonUniformFMin;
6830 } else if (isUnsigned) {
6831 opCode = spv::OpGroupNonUniformUMin;
6832 } else {
6833 opCode = spv::OpGroupNonUniformSMin;
6834 }
6835 break;
6836 case glslang::EOpSubgroupMax:
6837 case glslang::EOpSubgroupInclusiveMax:
6838 case glslang::EOpSubgroupExclusiveMax:
6839 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006840 case glslang::EOpSubgroupPartitionedMax:
6841 case glslang::EOpSubgroupPartitionedInclusiveMax:
6842 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07006843 if (isFloat) {
6844 opCode = spv::OpGroupNonUniformFMax;
6845 } else if (isUnsigned) {
6846 opCode = spv::OpGroupNonUniformUMax;
6847 } else {
6848 opCode = spv::OpGroupNonUniformSMax;
6849 }
6850 break;
6851 case glslang::EOpSubgroupAnd:
6852 case glslang::EOpSubgroupInclusiveAnd:
6853 case glslang::EOpSubgroupExclusiveAnd:
6854 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006855 case glslang::EOpSubgroupPartitionedAnd:
6856 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6857 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07006858 if (isBool) {
6859 opCode = spv::OpGroupNonUniformLogicalAnd;
6860 } else {
6861 opCode = spv::OpGroupNonUniformBitwiseAnd;
6862 }
6863 break;
6864 case glslang::EOpSubgroupOr:
6865 case glslang::EOpSubgroupInclusiveOr:
6866 case glslang::EOpSubgroupExclusiveOr:
6867 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006868 case glslang::EOpSubgroupPartitionedOr:
6869 case glslang::EOpSubgroupPartitionedInclusiveOr:
6870 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07006871 if (isBool) {
6872 opCode = spv::OpGroupNonUniformLogicalOr;
6873 } else {
6874 opCode = spv::OpGroupNonUniformBitwiseOr;
6875 }
6876 break;
6877 case glslang::EOpSubgroupXor:
6878 case glslang::EOpSubgroupInclusiveXor:
6879 case glslang::EOpSubgroupExclusiveXor:
6880 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006881 case glslang::EOpSubgroupPartitionedXor:
6882 case glslang::EOpSubgroupPartitionedInclusiveXor:
6883 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07006884 if (isBool) {
6885 opCode = spv::OpGroupNonUniformLogicalXor;
6886 } else {
6887 opCode = spv::OpGroupNonUniformBitwiseXor;
6888 }
6889 break;
6890 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6891 case glslang::EOpSubgroupQuadSwapHorizontal:
6892 case glslang::EOpSubgroupQuadSwapVertical:
6893 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6894 default: assert(0 && "Unhandled subgroup operation!");
6895 }
6896
John Kessenich149afc32018-08-14 13:31:43 -06006897 // get the right Group Operation
6898 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006899 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006900 default:
6901 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006902 case glslang::EOpSubgroupBallotBitCount:
6903 case glslang::EOpSubgroupAdd:
6904 case glslang::EOpSubgroupMul:
6905 case glslang::EOpSubgroupMin:
6906 case glslang::EOpSubgroupMax:
6907 case glslang::EOpSubgroupAnd:
6908 case glslang::EOpSubgroupOr:
6909 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006910 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006911 break;
6912 case glslang::EOpSubgroupBallotInclusiveBitCount:
6913 case glslang::EOpSubgroupInclusiveAdd:
6914 case glslang::EOpSubgroupInclusiveMul:
6915 case glslang::EOpSubgroupInclusiveMin:
6916 case glslang::EOpSubgroupInclusiveMax:
6917 case glslang::EOpSubgroupInclusiveAnd:
6918 case glslang::EOpSubgroupInclusiveOr:
6919 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006920 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006921 break;
6922 case glslang::EOpSubgroupBallotExclusiveBitCount:
6923 case glslang::EOpSubgroupExclusiveAdd:
6924 case glslang::EOpSubgroupExclusiveMul:
6925 case glslang::EOpSubgroupExclusiveMin:
6926 case glslang::EOpSubgroupExclusiveMax:
6927 case glslang::EOpSubgroupExclusiveAnd:
6928 case glslang::EOpSubgroupExclusiveOr:
6929 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006930 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006931 break;
6932 case glslang::EOpSubgroupClusteredAdd:
6933 case glslang::EOpSubgroupClusteredMul:
6934 case glslang::EOpSubgroupClusteredMin:
6935 case glslang::EOpSubgroupClusteredMax:
6936 case glslang::EOpSubgroupClusteredAnd:
6937 case glslang::EOpSubgroupClusteredOr:
6938 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006939 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006940 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006941 case glslang::EOpSubgroupPartitionedAdd:
6942 case glslang::EOpSubgroupPartitionedMul:
6943 case glslang::EOpSubgroupPartitionedMin:
6944 case glslang::EOpSubgroupPartitionedMax:
6945 case glslang::EOpSubgroupPartitionedAnd:
6946 case glslang::EOpSubgroupPartitionedOr:
6947 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006948 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006949 break;
6950 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6951 case glslang::EOpSubgroupPartitionedInclusiveMul:
6952 case glslang::EOpSubgroupPartitionedInclusiveMin:
6953 case glslang::EOpSubgroupPartitionedInclusiveMax:
6954 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6955 case glslang::EOpSubgroupPartitionedInclusiveOr:
6956 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006957 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006958 break;
6959 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6960 case glslang::EOpSubgroupPartitionedExclusiveMul:
6961 case glslang::EOpSubgroupPartitionedExclusiveMin:
6962 case glslang::EOpSubgroupPartitionedExclusiveMax:
6963 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6964 case glslang::EOpSubgroupPartitionedExclusiveOr:
6965 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006966 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006967 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006968 }
6969
John Kessenich149afc32018-08-14 13:31:43 -06006970 // build the instruction
6971 std::vector<spv::IdImmediate> spvGroupOperands;
6972
6973 // Every operation begins with the Execution Scope operand.
6974 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6975 spvGroupOperands.push_back(executionScope);
6976
6977 // Next, for all operations that use a Group Operation, push that as an operand.
6978 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006979 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006980 spvGroupOperands.push_back(groupOperand);
6981 }
6982
John Kessenich66011cb2018-03-06 16:12:04 -07006983 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006984 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6985 spv::IdImmediate operand = { true, *opIt };
6986 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006987 }
6988
6989 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006990 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006991 switch (op) {
6992 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006993 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6994 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6995 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6996 }
6997 if (directionId != spv::NoResult) {
6998 spv::IdImmediate direction = { true, directionId };
6999 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007000 }
7001
7002 return builder.createOp(opCode, typeId, spvGroupOperands);
7003}
John Kessenicha28f7a72019-08-06 07:00:58 -06007004#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007005
John Kessenich5e4b1242015-08-06 22:53:06 -06007006spv::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 -06007007{
John Kessenich66011cb2018-03-06 16:12:04 -07007008 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7009 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007010
John Kessenich140f3df2015-06-26 16:58:36 -06007011 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007012 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007013 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007014 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007015 spv::Id typeId0 = 0;
7016 if (consumedOperands > 0)
7017 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007018 spv::Id typeId1 = 0;
7019 if (consumedOperands > 1)
7020 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007021 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007022
7023 switch (op) {
7024 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007025 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007026 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007027 else if (isUnsigned)
7028 libCall = spv::GLSLstd450UMin;
7029 else
7030 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007031 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007032 break;
7033 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007034 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007035 break;
7036 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007037 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007038 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007039 else if (isUnsigned)
7040 libCall = spv::GLSLstd450UMax;
7041 else
7042 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007043 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007044 break;
7045 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007046 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007047 break;
7048 case glslang::EOpDot:
7049 opCode = spv::OpDot;
7050 break;
7051 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007052 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007053 break;
7054
7055 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007056 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007057 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007058 else if (isUnsigned)
7059 libCall = spv::GLSLstd450UClamp;
7060 else
7061 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007062 builder.promoteScalar(precision, operands.front(), operands[1]);
7063 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007064 break;
7065 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007066 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7067 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007068 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007069 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007070 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007071 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007072 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007073 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007074 break;
7075 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007076 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007077 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007078 break;
7079 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007080 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007081 builder.promoteScalar(precision, operands[0], operands[2]);
7082 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007083 break;
7084
7085 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007086 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007087 break;
7088 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007089 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007090 break;
7091 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007092 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007093 break;
7094 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007095 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007096 break;
7097 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007098 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007099 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007100#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007101 case glslang::EOpInterpolateAtSample:
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::GLSLstd450InterpolateAtSample;
7105 break;
7106 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007107 if (typeProxy == glslang::EbtFloat16)
7108 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007109 libCall = spv::GLSLstd450InterpolateAtOffset;
7110 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007111 case glslang::EOpAddCarry:
7112 opCode = spv::OpIAddCarry;
7113 typeId = builder.makeStructResultType(typeId0, typeId0);
7114 consumedOperands = 2;
7115 break;
7116 case glslang::EOpSubBorrow:
7117 opCode = spv::OpISubBorrow;
7118 typeId = builder.makeStructResultType(typeId0, typeId0);
7119 consumedOperands = 2;
7120 break;
7121 case glslang::EOpUMulExtended:
7122 opCode = spv::OpUMulExtended;
7123 typeId = builder.makeStructResultType(typeId0, typeId0);
7124 consumedOperands = 2;
7125 break;
7126 case glslang::EOpIMulExtended:
7127 opCode = spv::OpSMulExtended;
7128 typeId = builder.makeStructResultType(typeId0, typeId0);
7129 consumedOperands = 2;
7130 break;
7131 case glslang::EOpBitfieldExtract:
7132 if (isUnsigned)
7133 opCode = spv::OpBitFieldUExtract;
7134 else
7135 opCode = spv::OpBitFieldSExtract;
7136 break;
7137 case glslang::EOpBitfieldInsert:
7138 opCode = spv::OpBitFieldInsert;
7139 break;
7140
7141 case glslang::EOpFma:
7142 libCall = spv::GLSLstd450Fma;
7143 break;
7144 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007145 {
7146 libCall = spv::GLSLstd450FrexpStruct;
7147 assert(builder.isPointerType(typeId1));
7148 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007149 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007150 if (width == 16)
7151 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7152 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007153 if (builder.getNumComponents(operands[0]) == 1)
7154 frexpIntType = builder.makeIntegerType(width, true);
7155 else
7156 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7157 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7158 consumedOperands = 1;
7159 }
John Kessenich55e7d112015-11-15 21:33:39 -07007160 break;
7161 case glslang::EOpLdexp:
7162 libCall = spv::GLSLstd450Ldexp;
7163 break;
7164
Rex Xu574ab042016-04-14 16:53:07 +08007165 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007166 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007167
John Kessenich66011cb2018-03-06 16:12:04 -07007168 case glslang::EOpSubgroupBroadcast:
7169 case glslang::EOpSubgroupBallotBitExtract:
7170 case glslang::EOpSubgroupShuffle:
7171 case glslang::EOpSubgroupShuffleXor:
7172 case glslang::EOpSubgroupShuffleUp:
7173 case glslang::EOpSubgroupShuffleDown:
7174 case glslang::EOpSubgroupClusteredAdd:
7175 case glslang::EOpSubgroupClusteredMul:
7176 case glslang::EOpSubgroupClusteredMin:
7177 case glslang::EOpSubgroupClusteredMax:
7178 case glslang::EOpSubgroupClusteredAnd:
7179 case glslang::EOpSubgroupClusteredOr:
7180 case glslang::EOpSubgroupClusteredXor:
7181 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007182 case glslang::EOpSubgroupPartitionedAdd:
7183 case glslang::EOpSubgroupPartitionedMul:
7184 case glslang::EOpSubgroupPartitionedMin:
7185 case glslang::EOpSubgroupPartitionedMax:
7186 case glslang::EOpSubgroupPartitionedAnd:
7187 case glslang::EOpSubgroupPartitionedOr:
7188 case glslang::EOpSubgroupPartitionedXor:
7189 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7190 case glslang::EOpSubgroupPartitionedInclusiveMul:
7191 case glslang::EOpSubgroupPartitionedInclusiveMin:
7192 case glslang::EOpSubgroupPartitionedInclusiveMax:
7193 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7194 case glslang::EOpSubgroupPartitionedInclusiveOr:
7195 case glslang::EOpSubgroupPartitionedInclusiveXor:
7196 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7197 case glslang::EOpSubgroupPartitionedExclusiveMul:
7198 case glslang::EOpSubgroupPartitionedExclusiveMin:
7199 case glslang::EOpSubgroupPartitionedExclusiveMax:
7200 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7201 case glslang::EOpSubgroupPartitionedExclusiveOr:
7202 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007203 return createSubgroupOperation(op, typeId, operands, typeProxy);
7204
Rex Xu9d93a232016-05-05 12:30:44 +08007205 case glslang::EOpSwizzleInvocations:
7206 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7207 libCall = spv::SwizzleInvocationsAMD;
7208 break;
7209 case glslang::EOpSwizzleInvocationsMasked:
7210 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7211 libCall = spv::SwizzleInvocationsMaskedAMD;
7212 break;
7213 case glslang::EOpWriteInvocation:
7214 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7215 libCall = spv::WriteInvocationAMD;
7216 break;
7217
7218 case glslang::EOpMin3:
7219 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7220 if (isFloat)
7221 libCall = spv::FMin3AMD;
7222 else {
7223 if (isUnsigned)
7224 libCall = spv::UMin3AMD;
7225 else
7226 libCall = spv::SMin3AMD;
7227 }
7228 break;
7229 case glslang::EOpMax3:
7230 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7231 if (isFloat)
7232 libCall = spv::FMax3AMD;
7233 else {
7234 if (isUnsigned)
7235 libCall = spv::UMax3AMD;
7236 else
7237 libCall = spv::SMax3AMD;
7238 }
7239 break;
7240 case glslang::EOpMid3:
7241 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7242 if (isFloat)
7243 libCall = spv::FMid3AMD;
7244 else {
7245 if (isUnsigned)
7246 libCall = spv::UMid3AMD;
7247 else
7248 libCall = spv::SMid3AMD;
7249 }
7250 break;
7251
7252 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007253 if (typeProxy == glslang::EbtFloat16)
7254 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007255 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7256 libCall = spv::InterpolateAtVertexAMD;
7257 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05007258 case glslang::EOpBarrier:
7259 {
7260 // This is for the extended controlBarrier function, with four operands.
7261 // The unextended barrier() goes through createNoArgOperation.
7262 assert(operands.size() == 4);
7263 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7264 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7265 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7266 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007267 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7268 spv::MemorySemanticsMakeVisibleKHRMask |
7269 spv::MemorySemanticsOutputMemoryKHRMask |
7270 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007271 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7272 }
7273 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7274 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7275 }
7276 return 0;
7277 }
7278 break;
7279 case glslang::EOpMemoryBarrier:
7280 {
7281 // This is for the extended memoryBarrier function, with three operands.
7282 // The unextended memoryBarrier() goes through createNoArgOperation.
7283 assert(operands.size() == 3);
7284 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7285 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7286 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007287 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7288 spv::MemorySemanticsMakeVisibleKHRMask |
7289 spv::MemorySemanticsOutputMemoryKHRMask |
7290 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007291 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7292 }
7293 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7294 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7295 }
7296 return 0;
7297 }
7298 break;
Chao Chen3c366992018-09-19 11:41:59 -07007299
Chao Chenb50c02e2018-09-19 11:42:24 -07007300 case glslang::EOpReportIntersectionNV:
7301 {
7302 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007303 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007304 }
7305 break;
7306 case glslang::EOpTraceNV:
7307 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007308 builder.createNoResultOp(spv::OpTraceNV, operands);
7309 return 0;
7310 }
7311 break;
7312 case glslang::EOpExecuteCallableNV:
7313 {
7314 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007315 return 0;
7316 }
7317 break;
Chao Chen3c366992018-09-19 11:41:59 -07007318 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7319 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7320 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007321 case glslang::EOpCooperativeMatrixMulAdd:
7322 opCode = spv::OpCooperativeMatrixMulAddNV;
7323 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007324#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007325 default:
7326 return 0;
7327 }
7328
7329 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007330 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007331 // Use an extended instruction from the standard library.
7332 // Construct the call arguments, without modifying the original operands vector.
7333 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7334 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007335 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007336 } else if (opCode == spv::OpDot && !isFloat) {
7337 // int dot(int, int)
7338 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7339 const int componentCount = builder.getNumComponents(operands[0]);
7340 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7341 builder.setPrecision(mulOp, precision);
7342 id = builder.createCompositeExtract(mulOp, typeId, 0);
7343 for (int i = 1; i < componentCount; ++i) {
7344 builder.setPrecision(id, precision);
7345 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7346 }
John Kessenich2359bd02015-12-06 19:29:11 -07007347 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007348 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007349 case 0:
7350 // should all be handled by visitAggregate and createNoArgOperation
7351 assert(0);
7352 return 0;
7353 case 1:
7354 // should all be handled by createUnaryOperation
7355 assert(0);
7356 return 0;
7357 case 2:
7358 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7359 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007360 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007361 // anything 3 or over doesn't have l-value operands, so all should be consumed
7362 assert(consumedOperands == operands.size());
7363 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007364 break;
7365 }
7366 }
7367
John Kessenich55e7d112015-11-15 21:33:39 -07007368 // Decode the return types that were structures
7369 switch (op) {
7370 case glslang::EOpAddCarry:
7371 case glslang::EOpSubBorrow:
7372 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7373 id = builder.createCompositeExtract(id, typeId0, 0);
7374 break;
7375 case glslang::EOpUMulExtended:
7376 case glslang::EOpIMulExtended:
7377 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7378 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7379 break;
7380 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007381 {
7382 assert(operands.size() == 2);
7383 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7384 // "exp" is floating-point type (from HLSL intrinsic)
7385 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7386 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7387 builder.createStore(member1, operands[1]);
7388 } else
7389 // "exp" is integer type (from GLSL built-in function)
7390 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7391 id = builder.createCompositeExtract(id, typeId0, 0);
7392 }
John Kessenich55e7d112015-11-15 21:33:39 -07007393 break;
7394 default:
7395 break;
7396 }
7397
John Kessenich32cfd492016-02-02 12:37:46 -07007398 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007399}
7400
Rex Xu9d93a232016-05-05 12:30:44 +08007401// Intrinsics with no arguments (or no return value, and no precision).
7402spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007403{
Jeff Bolz36831c92018-09-05 10:11:41 -05007404 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7405 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007406
7407 switch (op) {
John Kessenicha28f7a72019-08-06 07:00:58 -06007408#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007409 case glslang::EOpEmitVertex:
7410 builder.createNoResultOp(spv::OpEmitVertex);
7411 return 0;
7412 case glslang::EOpEndPrimitive:
7413 builder.createNoResultOp(spv::OpEndPrimitive);
7414 return 0;
7415 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007416 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007417 if (glslangIntermediate->usingVulkanMemoryModel()) {
7418 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7419 spv::MemorySemanticsOutputMemoryKHRMask |
7420 spv::MemorySemanticsAcquireReleaseMask);
7421 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7422 } else {
7423 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7424 }
John Kessenich82979362017-12-11 04:02:24 -07007425 } else {
7426 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7427 spv::MemorySemanticsWorkgroupMemoryMask |
7428 spv::MemorySemanticsAcquireReleaseMask);
7429 }
John Kessenich140f3df2015-06-26 16:58:36 -06007430 return 0;
7431 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007432 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7433 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007434 return 0;
7435 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007436 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7437 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007438 return 0;
7439 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007440 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7441 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007442 return 0;
7443 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007444 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7445 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007446 return 0;
7447 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007448 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7449 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007450 return 0;
7451 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007452 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7453 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007454 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007455 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007456 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007457 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007458 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007459 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007460 case glslang::EOpDeviceMemoryBarrier:
7461 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7462 spv::MemorySemanticsImageMemoryMask |
7463 spv::MemorySemanticsAcquireReleaseMask);
7464 return 0;
7465 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7466 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7467 spv::MemorySemanticsImageMemoryMask |
7468 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007469 return 0;
7470 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007471 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7472 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007473 return 0;
7474 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007475 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7476 spv::MemorySemanticsWorkgroupMemoryMask |
7477 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007478 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007479 case glslang::EOpSubgroupBarrier:
7480 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7481 spv::MemorySemanticsAcquireReleaseMask);
7482 return spv::NoResult;
7483 case glslang::EOpSubgroupMemoryBarrier:
7484 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7485 spv::MemorySemanticsAcquireReleaseMask);
7486 return spv::NoResult;
7487 case glslang::EOpSubgroupMemoryBarrierBuffer:
7488 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7489 spv::MemorySemanticsAcquireReleaseMask);
7490 return spv::NoResult;
7491 case glslang::EOpSubgroupMemoryBarrierImage:
7492 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7493 spv::MemorySemanticsAcquireReleaseMask);
7494 return spv::NoResult;
7495 case glslang::EOpSubgroupMemoryBarrierShared:
7496 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7497 spv::MemorySemanticsAcquireReleaseMask);
7498 return spv::NoResult;
7499 case glslang::EOpSubgroupElect: {
7500 std::vector<spv::Id> operands;
7501 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7502 }
Rex Xu9d93a232016-05-05 12:30:44 +08007503 case glslang::EOpTime:
7504 {
7505 std::vector<spv::Id> args; // Dummy arguments
7506 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7507 return builder.setPrecision(id, precision);
7508 }
Chao Chenb50c02e2018-09-19 11:42:24 -07007509 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007510 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007511 return 0;
7512 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007513 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007514 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007515
7516 case glslang::EOpBeginInvocationInterlock:
7517 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7518 return 0;
7519 case glslang::EOpEndInvocationInterlock:
7520 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7521 return 0;
7522
Jeff Bolzba6170b2019-07-01 09:23:23 -05007523 case glslang::EOpIsHelperInvocation:
7524 {
7525 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08007526 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
7527 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
7528 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05007529 }
7530
amhagan91fb0092019-07-10 21:14:38 -04007531 case glslang::EOpReadClockSubgroupKHR: {
7532 std::vector<spv::Id> args;
7533 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
7534 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7535 builder.addCapability(spv::CapabilityShaderClockKHR);
7536 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7537 }
7538
7539 case glslang::EOpReadClockDeviceKHR: {
7540 std::vector<spv::Id> args;
7541 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
7542 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7543 builder.addCapability(spv::CapabilityShaderClockKHR);
7544 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7545 }
John Kessenicha28f7a72019-08-06 07:00:58 -06007546#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007547 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007548 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007549 return 0;
7550 }
7551}
7552
7553spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7554{
John Kessenich2f273362015-07-18 22:34:27 -06007555 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007556 spv::Id id;
7557 if (symbolValues.end() != iter) {
7558 id = iter->second;
7559 return id;
7560 }
7561
7562 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06007563 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
7564 auto forcedType = getForcedType(builtIn, symbol->getType());
7565 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06007566 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06007567 if (forcedType.second != spv::NoType)
7568 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06007569
Rex Xuc884b4a2016-06-29 15:03:44 +08007570 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007571 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7572 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7573 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06007574#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007575 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7576#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007577 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007578 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007579 if (symbol->getQualifier().hasIndex())
7580 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7581 if (symbol->getQualifier().hasComponent())
7582 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007583 // atomic counters use this:
7584 if (symbol->getQualifier().hasOffset())
7585 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007586 }
7587
scygan2c864272016-05-18 18:09:17 +02007588 if (symbol->getQualifier().hasLocation())
7589 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007590 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007591 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007592 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007593 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007594 }
John Kessenich140f3df2015-06-26 16:58:36 -06007595 if (symbol->getQualifier().hasSet())
7596 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007597 else if (IsDescriptorResource(symbol->getType())) {
7598 // default to 0
7599 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7600 }
John Kessenich140f3df2015-06-26 16:58:36 -06007601 if (symbol->getQualifier().hasBinding())
7602 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007603 else if (IsDescriptorResource(symbol->getType())) {
7604 // default to 0
7605 builder.addDecoration(id, spv::DecorationBinding, 0);
7606 }
John Kessenich6c292d32016-02-15 20:58:50 -07007607 if (symbol->getQualifier().hasAttachment())
7608 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich7015bd62019-08-01 03:28:08 -06007609#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007610 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007611 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007612 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007613 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007614 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7615 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7616 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7617 }
7618 if (symbol->getQualifier().hasXfbOffset())
7619 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007620 }
John Kessenich7015bd62019-08-01 03:28:08 -06007621#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007622
Rex Xu1da878f2016-02-21 20:59:01 +08007623 if (symbol->getType().isImage()) {
7624 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007625 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007626 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007627 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007628 }
7629
John Kessenich9c14f772019-06-17 08:38:35 -06007630 // add built-in variable decoration
7631 if (builtIn != spv::BuiltInMax) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007632 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich9c14f772019-06-17 08:38:35 -06007633 }
John Kessenich140f3df2015-06-26 16:58:36 -06007634
John Kessenich5611c6d2018-04-05 11:25:02 -06007635 // nonuniform
7636 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7637
John Kessenicha28f7a72019-08-06 07:00:58 -06007638#ifndef GLSLANG_WEB
chaoc0ad6a4e2016-12-19 16:29:34 -08007639 if (builtIn == spv::BuiltInSampleMask) {
7640 spv::Decoration decoration;
7641 // GL_NV_sample_mask_override_coverage extension
7642 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007643 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007644 else
7645 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007646 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007647 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07007648 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08007649 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7650 }
7651 }
chaoc771d89f2017-01-13 01:10:53 -08007652 else if (builtIn == spv::BuiltInLayer) {
7653 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007654 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007655 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007656 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7657 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7658 }
John Kessenichb41bff62017-08-11 13:07:17 -06007659 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007660 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7661 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007662 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7663 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7664 }
7665 }
7666
chaoc6e5acae2016-12-20 13:28:52 -08007667 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007668 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007669 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007670 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7671 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007672 if (symbol->getQualifier().pervertexNV) {
7673 builder.addDecoration(id, spv::DecorationPerVertexNV);
7674 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7675 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7676 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007677#endif
7678
John Kessenich5d610ee2018-03-07 18:05:55 -07007679 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7680 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7681 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7682 symbol->getType().getQualifier().semanticName);
7683 }
7684
John Kessenich7015bd62019-08-01 03:28:08 -06007685 if (symbol->isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007686 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7687 }
7688
John Kessenich140f3df2015-06-26 16:58:36 -06007689 return id;
7690}
7691
John Kessenicha28f7a72019-08-06 07:00:58 -06007692#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007693// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7694void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7695{
7696 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007697 if (qualifier.perPrimitiveNV) {
7698 // Need to add capability/extension for fragment shader.
7699 // Mesh shader already adds this by default.
7700 if (glslangIntermediate->getStage() == EShLangFragment) {
7701 builder.addCapability(spv::CapabilityMeshShadingNV);
7702 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7703 }
Chao Chen3c366992018-09-19 11:41:59 -07007704 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007705 }
Chao Chen3c366992018-09-19 11:41:59 -07007706 if (qualifier.perViewNV)
7707 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7708 if (qualifier.perTaskNV)
7709 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7710 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007711 if (qualifier.perPrimitiveNV) {
7712 // Need to add capability/extension for fragment shader.
7713 // Mesh shader already adds this by default.
7714 if (glslangIntermediate->getStage() == EShLangFragment) {
7715 builder.addCapability(spv::CapabilityMeshShadingNV);
7716 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7717 }
Chao Chen3c366992018-09-19 11:41:59 -07007718 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007719 }
Chao Chen3c366992018-09-19 11:41:59 -07007720 if (qualifier.perViewNV)
7721 builder.addDecoration(id, spv::DecorationPerViewNV);
7722 if (qualifier.perTaskNV)
7723 builder.addDecoration(id, spv::DecorationPerTaskNV);
7724 }
7725}
7726#endif
7727
John Kessenich55e7d112015-11-15 21:33:39 -07007728// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007729// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007730//
7731// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7732//
7733// Recursively walk the nodes. The nodes form a tree whose leaves are
7734// regular constants, which themselves are trees that createSpvConstant()
7735// recursively walks. So, this function walks the "top" of the tree:
7736// - emit specialization constant-building instructions for specConstant
7737// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007738spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007739{
John Kessenich7cc0e282016-03-20 00:46:02 -06007740 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007741
qining4f4bb812016-04-03 23:55:17 -04007742 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007743 if (! node.getQualifier().specConstant) {
7744 // hand off to the non-spec-constant path
7745 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7746 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007747 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007748 nextConst, false);
7749 }
7750
7751 // We now know we have a specialization constant to build
7752
John Kessenichd94c0032016-05-30 19:29:40 -06007753 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007754 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7755 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7756 std::vector<spv::Id> dimConstId;
7757 for (int dim = 0; dim < 3; ++dim) {
7758 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7759 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007760 if (specConst) {
7761 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7762 glslangIntermediate->getLocalSizeSpecId(dim));
7763 }
qining4f4bb812016-04-03 23:55:17 -04007764 }
7765 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7766 }
7767
7768 // An AST node labelled as specialization constant should be a symbol node.
7769 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7770 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007771 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007772 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007773 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7774 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7775 // will set the builder into spec constant op instruction generating mode.
7776 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007777 result = accessChainLoad(sub_tree->getType());
7778 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007779 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007780 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007781 } else {
7782 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007783 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007784 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007785 builder.addName(result, sn->getName().c_str());
7786 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007787 }
qining4f4bb812016-04-03 23:55:17 -04007788
7789 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7790 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007791 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007792 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007793}
7794
John Kessenich140f3df2015-06-26 16:58:36 -06007795// Use 'consts' as the flattened glslang source of scalar constants to recursively
7796// build the aggregate SPIR-V constant.
7797//
7798// If there are not enough elements present in 'consts', 0 will be substituted;
7799// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7800//
qining08408382016-03-21 09:51:37 -04007801spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007802{
7803 // vector of constants for SPIR-V
7804 std::vector<spv::Id> spvConsts;
7805
7806 // Type is used for struct and array constants
7807 spv::Id typeId = convertGlslangToSpvType(glslangType);
7808
7809 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007810 glslang::TType elementType(glslangType, 0);
7811 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007812 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007813 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007814 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007815 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007816 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007817 } else if (glslangType.isCoopMat()) {
7818 glslang::TType componentType(glslangType.getBasicType());
7819 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007820 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007821 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7822 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007823 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007824 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007825 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7826 bool zero = nextConst >= consts.size();
7827 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007828 case glslang::EbtInt8:
7829 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7830 break;
7831 case glslang::EbtUint8:
7832 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7833 break;
7834 case glslang::EbtInt16:
7835 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7836 break;
7837 case glslang::EbtUint16:
7838 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7839 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007840 case glslang::EbtInt:
7841 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7842 break;
7843 case glslang::EbtUint:
7844 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7845 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007846 case glslang::EbtInt64:
7847 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7848 break;
7849 case glslang::EbtUint64:
7850 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7851 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007852 case glslang::EbtFloat:
7853 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7854 break;
7855 case glslang::EbtDouble:
7856 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7857 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007858 case glslang::EbtFloat16:
7859 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7860 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007861 case glslang::EbtBool:
7862 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7863 break;
7864 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007865 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007866 break;
7867 }
7868 ++nextConst;
7869 }
7870 } else {
7871 // we have a non-aggregate (scalar) constant
7872 bool zero = nextConst >= consts.size();
7873 spv::Id scalar = 0;
7874 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007875 case glslang::EbtInt8:
7876 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7877 break;
7878 case glslang::EbtUint8:
7879 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7880 break;
7881 case glslang::EbtInt16:
7882 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7883 break;
7884 case glslang::EbtUint16:
7885 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7886 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007887 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007888 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007889 break;
7890 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007891 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007892 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007893 case glslang::EbtInt64:
7894 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7895 break;
7896 case glslang::EbtUint64:
7897 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7898 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007899 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007900 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007901 break;
7902 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007903 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007904 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007905 case glslang::EbtFloat16:
7906 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7907 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007908 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007909 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007910 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06007911 case glslang::EbtReference:
7912 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7913 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
7914 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007915 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007916 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007917 break;
7918 }
7919 ++nextConst;
7920 return scalar;
7921 }
7922
7923 return builder.makeCompositeConstant(typeId, spvConsts);
7924}
7925
John Kessenich7c1aa102015-10-15 13:29:11 -06007926// Return true if the node is a constant or symbol whose reading has no
7927// non-trivial observable cost or effect.
7928bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7929{
7930 // don't know what this is
7931 if (node == nullptr)
7932 return false;
7933
7934 // a constant is safe
7935 if (node->getAsConstantUnion() != nullptr)
7936 return true;
7937
7938 // not a symbol means non-trivial
7939 if (node->getAsSymbolNode() == nullptr)
7940 return false;
7941
7942 // a symbol, depends on what's being read
7943 switch (node->getType().getQualifier().storage) {
7944 case glslang::EvqTemporary:
7945 case glslang::EvqGlobal:
7946 case glslang::EvqIn:
7947 case glslang::EvqInOut:
7948 case glslang::EvqConst:
7949 case glslang::EvqConstReadOnly:
7950 case glslang::EvqUniform:
7951 return true;
7952 default:
7953 return false;
7954 }
qining25262b32016-05-06 17:25:16 -04007955}
John Kessenich7c1aa102015-10-15 13:29:11 -06007956
7957// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007958// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007959// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007960// Return true if trivial.
7961bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7962{
7963 if (node == nullptr)
7964 return false;
7965
John Kessenich84cc15f2017-05-24 16:44:47 -06007966 // count non scalars as trivial, as well as anything coming from HLSL
7967 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007968 return true;
7969
John Kessenich7c1aa102015-10-15 13:29:11 -06007970 // symbols and constants are trivial
7971 if (isTrivialLeaf(node))
7972 return true;
7973
7974 // otherwise, it needs to be a simple operation or one or two leaf nodes
7975
7976 // not a simple operation
7977 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7978 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7979 if (binaryNode == nullptr && unaryNode == nullptr)
7980 return false;
7981
7982 // not on leaf nodes
7983 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7984 return false;
7985
7986 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7987 return false;
7988 }
7989
7990 switch (node->getAsOperator()->getOp()) {
7991 case glslang::EOpLogicalNot:
7992 case glslang::EOpConvIntToBool:
7993 case glslang::EOpConvUintToBool:
7994 case glslang::EOpConvFloatToBool:
7995 case glslang::EOpConvDoubleToBool:
7996 case glslang::EOpEqual:
7997 case glslang::EOpNotEqual:
7998 case glslang::EOpLessThan:
7999 case glslang::EOpGreaterThan:
8000 case glslang::EOpLessThanEqual:
8001 case glslang::EOpGreaterThanEqual:
8002 case glslang::EOpIndexDirect:
8003 case glslang::EOpIndexDirectStruct:
8004 case glslang::EOpLogicalXor:
8005 case glslang::EOpAny:
8006 case glslang::EOpAll:
8007 return true;
8008 default:
8009 return false;
8010 }
8011}
8012
8013// Emit short-circuiting code, where 'right' is never evaluated unless
8014// the left side is true (for &&) or false (for ||).
8015spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
8016{
8017 spv::Id boolTypeId = builder.makeBoolType();
8018
8019 // emit left operand
8020 builder.clearAccessChain();
8021 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008022 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008023
8024 // Operands to accumulate OpPhi operands
8025 std::vector<spv::Id> phiOperands;
8026 // accumulate left operand's phi information
8027 phiOperands.push_back(leftId);
8028 phiOperands.push_back(builder.getBuildPoint()->getId());
8029
8030 // Make the two kinds of operation symmetric with a "!"
8031 // || => emit "if (! left) result = right"
8032 // && => emit "if ( left) result = right"
8033 //
8034 // TODO: this runtime "not" for || could be avoided by adding functionality
8035 // to 'builder' to have an "else" without an "then"
8036 if (op == glslang::EOpLogicalOr)
8037 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8038
8039 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008040 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008041
8042 // emit right operand as the "then" part of the "if"
8043 builder.clearAccessChain();
8044 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008045 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008046
8047 // accumulate left operand's phi information
8048 phiOperands.push_back(rightId);
8049 phiOperands.push_back(builder.getBuildPoint()->getId());
8050
8051 // finish the "if"
8052 ifBuilder.makeEndIf();
8053
8054 // phi together the two results
8055 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8056}
8057
John Kessenicha28f7a72019-08-06 07:00:58 -06008058#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008059// Return type Id of the imported set of extended instructions corresponds to the name.
8060// Import this set if it has not been imported yet.
8061spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8062{
8063 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8064 return extBuiltinMap[name];
8065 else {
Rex Xu51596642016-09-21 18:56:12 +08008066 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008067 spv::Id extBuiltins = builder.import(name);
8068 extBuiltinMap[name] = extBuiltins;
8069 return extBuiltins;
8070 }
8071}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008072#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008073
John Kessenich140f3df2015-06-26 16:58:36 -06008074}; // end anonymous namespace
8075
8076namespace glslang {
8077
John Kessenich68d78fd2015-07-12 19:28:10 -06008078void GetSpirvVersion(std::string& version)
8079{
John Kessenich9e55f632015-07-15 10:03:39 -06008080 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008081 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008082 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008083 version = buf;
8084}
8085
John Kessenicha372a3e2017-11-02 22:32:14 -06008086// For low-order part of the generator's magic number. Bump up
8087// when there is a change in the style (e.g., if SSA form changes,
8088// or a different instruction sequence to do something gets used).
8089int GetSpirvGeneratorVersion()
8090{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008091 // return 1; // start
8092 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008093 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008094 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008095 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008096 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8097 // versions 4 and 6 each generate OpArrayLength as it has long been done
8098 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06008099}
8100
John Kessenich140f3df2015-06-26 16:58:36 -06008101// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008102void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008103{
8104 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008105 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008106 if (out.fail())
8107 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008108 for (int i = 0; i < (int)spirv.size(); ++i) {
8109 unsigned int word = spirv[i];
8110 out.write((const char*)&word, 4);
8111 }
8112 out.close();
8113}
8114
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008115// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008116void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008117{
8118 std::ofstream out;
8119 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008120 if (out.fail())
8121 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008122 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008123 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008124 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008125 if (varName != nullptr) {
8126 out << "\t #pragma once" << std::endl;
8127 out << "const uint32_t " << varName << "[] = {" << std::endl;
8128 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008129 const int WORDS_PER_LINE = 8;
8130 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8131 out << "\t";
8132 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8133 const unsigned int word = spirv[i + j];
8134 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8135 if (i + j + 1 < (int)spirv.size()) {
8136 out << ",";
8137 }
8138 }
8139 out << std::endl;
8140 }
Flavio15017db2017-02-15 14:29:33 -08008141 if (varName != nullptr) {
8142 out << "};";
8143 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008144 out.close();
8145}
8146
John Kessenich140f3df2015-06-26 16:58:36 -06008147//
8148// Set up the glslang traversal
8149//
John Kessenich4e11b612018-08-30 16:56:59 -06008150void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008151{
Lei Zhang17535f72016-05-04 15:55:59 -04008152 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008153 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008154}
8155
John Kessenich4e11b612018-08-30 16:56:59 -06008156void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008157 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008158{
John Kessenich140f3df2015-06-26 16:58:36 -06008159 TIntermNode* root = intermediate.getTreeRoot();
8160
8161 if (root == 0)
8162 return;
8163
John Kessenich4e11b612018-08-30 16:56:59 -06008164 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008165 if (options == nullptr)
8166 options = &defaultOptions;
8167
John Kessenich4e11b612018-08-30 16:56:59 -06008168 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008169
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008170 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008171 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008172 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008173 it.dumpSpv(spirv);
8174
GregFfb03a552018-03-29 11:49:14 -06008175#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008176 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8177 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008178 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8179 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008180 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008181 prelegalization = false;
8182 }
John Kessenich717c80a2018-08-23 15:17:10 -06008183
John Kessenich4e11b612018-08-30 16:56:59 -06008184 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008185 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008186
John Kessenich717c80a2018-08-23 15:17:10 -06008187 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008188 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008189
GregFcd1f1692017-09-21 18:40:22 -06008190#endif
8191
John Kessenich4e11b612018-08-30 16:56:59 -06008192 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008193}
8194
8195}; // end namespace glslang