blob: a91f18073725a79fdc5baf75caef820f870a86a0 [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 Kessenich155d3512019-08-08 23:29:20 -0600251#ifdef GLSLANG_WEB
252 return spv::SourceLanguageESSL;
253#endif
254
John Kessenich66e2faf2016-03-12 18:34:36 -0700255 switch (source) {
256 case glslang::EShSourceGlsl:
257 switch (profile) {
258 case ENoProfile:
259 case ECoreProfile:
260 case ECompatibilityProfile:
261 return spv::SourceLanguageGLSL;
262 case EEsProfile:
263 return spv::SourceLanguageESSL;
264 default:
265 return spv::SourceLanguageUnknown;
266 }
267 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600268 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600269 default:
270 return spv::SourceLanguageUnknown;
271 }
272}
273
274// Translate glslang language (stage) to SPIR-V execution model.
275spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
276{
277 switch (stage) {
278 case EShLangVertex: return spv::ExecutionModelVertex;
John Kessenicha28f7a72019-08-06 07:00:58 -0600279 case EShLangFragment: return spv::ExecutionModelFragment;
280#ifndef GLSLANG_WEB
281 case EShLangCompute: return spv::ExecutionModelGLCompute;
John Kessenich140f3df2015-06-26 16:58:36 -0600282 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
283 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
284 case EShLangGeometry: return spv::ExecutionModelGeometry;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700285 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
286 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
287 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
288 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
289 case EShLangMissNV: return spv::ExecutionModelMissNV;
290 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700291 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
292 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
293#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600294 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700295 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600296 return spv::ExecutionModelFragment;
297 }
298}
299
John Kessenich140f3df2015-06-26 16:58:36 -0600300// Translate glslang sampler type to SPIR-V dimensionality.
301spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
302{
303 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700304 case glslang::Esd1D: return spv::Dim1D;
305 case glslang::Esd2D: return spv::Dim2D;
306 case glslang::Esd3D: return spv::Dim3D;
307 case glslang::EsdCube: return spv::DimCube;
308 case glslang::EsdRect: return spv::DimRect;
309 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700310 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600311 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700312 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600313 return spv::Dim2D;
314 }
315}
316
John Kessenichf6640762016-08-01 19:44:00 -0600317// Translate glslang precision to SPIR-V precision decorations.
318spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600319{
John Kessenichf6640762016-08-01 19:44:00 -0600320 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700321 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600322 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600323 default:
324 return spv::NoPrecision;
325 }
326}
327
John Kessenichf6640762016-08-01 19:44:00 -0600328// Translate glslang type to SPIR-V precision decorations.
329spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
330{
331 return TranslatePrecisionDecoration(type.getQualifier().precision);
332}
333
John Kessenich140f3df2015-06-26 16:58:36 -0600334// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600335spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600336{
337 if (type.getBasicType() == glslang::EbtBlock) {
338 switch (type.getQualifier().storage) {
339 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600340 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600341 case glslang::EvqVaryingIn: return spv::DecorationBlock;
342 case glslang::EvqVaryingOut: return spv::DecorationBlock;
John Kessenicha28f7a72019-08-06 07:00:58 -0600343#ifndef GLSLANG_WEB
Chao Chenb50c02e2018-09-19 11:42:24 -0700344 case glslang::EvqPayloadNV: return spv::DecorationBlock;
345 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
346 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700347 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
348 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700349#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600350 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700351 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600352 break;
353 }
354 }
355
John Kessenich4016e382016-07-15 11:53:56 -0600356 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600357}
358
Rex Xu1da878f2016-02-21 20:59:01 +0800359// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500360void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800361{
Jeff Bolz36831c92018-09-05 10:11:41 -0500362 if (!useVulkanMemoryModel) {
363 if (qualifier.coherent)
364 memory.push_back(spv::DecorationCoherent);
365 if (qualifier.volatil) {
366 memory.push_back(spv::DecorationVolatile);
367 memory.push_back(spv::DecorationCoherent);
368 }
John Kessenich14b85d32018-06-04 15:36:03 -0600369 }
Rex Xu1da878f2016-02-21 20:59:01 +0800370 if (qualifier.restrict)
371 memory.push_back(spv::DecorationRestrict);
372 if (qualifier.readonly)
373 memory.push_back(spv::DecorationNonWritable);
374 if (qualifier.writeonly)
375 memory.push_back(spv::DecorationNonReadable);
376}
377
John Kessenich140f3df2015-06-26 16:58:36 -0600378// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700379spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600380{
381 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700382 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600383 case glslang::ElmRowMajor:
384 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700385 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600386 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700387 default:
388 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600389 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600390 }
391 } else {
392 switch (type.getBasicType()) {
393 default:
John Kessenich4016e382016-07-15 11:53:56 -0600394 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600395 break;
396 case glslang::EbtBlock:
397 switch (type.getQualifier().storage) {
398 case glslang::EvqUniform:
399 case glslang::EvqBuffer:
400 switch (type.getQualifier().layoutPacking) {
401 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600402 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
403 default:
John Kessenich4016e382016-07-15 11:53:56 -0600404 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600405 }
406 case glslang::EvqVaryingIn:
407 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700408 if (type.getQualifier().isTaskMemory()) {
409 switch (type.getQualifier().layoutPacking) {
410 case glslang::ElpShared: return spv::DecorationGLSLShared;
411 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
412 default: break;
413 }
414 } else {
415 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
416 }
John Kessenich4016e382016-07-15 11:53:56 -0600417 return spv::DecorationMax;
John Kessenicha28f7a72019-08-06 07:00:58 -0600418#ifndef GLSLANG_WEB
Chao Chenb50c02e2018-09-19 11:42:24 -0700419 case glslang::EvqPayloadNV:
420 case glslang::EvqPayloadInNV:
421 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700422 case glslang::EvqCallableDataNV:
423 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700424 return spv::DecorationMax;
425#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600426 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700427 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600428 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600429 }
430 }
431 }
432}
433
434// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600435// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700436// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800437spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600438{
Rex Xubbceed72016-05-21 09:40:44 +0800439 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700440 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600441 return spv::DecorationMax;
John Kessenich7015bd62019-08-01 03:28:08 -0600442 else if (qualifier.isNonPerspective())
John Kessenich55e7d112015-11-15 21:33:39 -0700443 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700444 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600445 return spv::DecorationFlat;
John Kessenicha28f7a72019-08-06 07:00:58 -0600446 else if (qualifier.isExplicitInterpolation()) {
Rex Xu17ff3432016-10-14 17:41:45 +0800447 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800448 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800449 }
Rex Xubbceed72016-05-21 09:40:44 +0800450 else
John Kessenich4016e382016-07-15 11:53:56 -0600451 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800452}
453
454// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600455// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800456// should be applied.
457spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
458{
459 if (qualifier.patch)
460 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700461 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600462 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700463 else if (qualifier.sample) {
464 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600465 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700466 } else
John Kessenich4016e382016-07-15 11:53:56 -0600467 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600468}
469
John Kessenich92187592016-02-01 13:45:25 -0700470// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700471spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600472{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700473 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600474 return spv::DecorationInvariant;
475 else
John Kessenich4016e382016-07-15 11:53:56 -0600476 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600477}
478
qining9220dbb2016-05-04 17:34:38 -0400479// If glslang type is noContraction, return SPIR-V NoContraction decoration.
480spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
481{
John Kessenicha28f7a72019-08-06 07:00:58 -0600482 if (qualifier.isNoContraction())
qining9220dbb2016-05-04 17:34:38 -0400483 return spv::DecorationNoContraction;
484 else
John Kessenich4016e382016-07-15 11:53:56 -0600485 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400486}
487
John Kessenich5611c6d2018-04-05 11:25:02 -0600488// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
489spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
490{
491 if (qualifier.isNonUniform()) {
492 builder.addExtension("SPV_EXT_descriptor_indexing");
493 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
494 return spv::DecorationNonUniformEXT;
495 } else
496 return spv::DecorationMax;
497}
498
Jeff Bolz36831c92018-09-05 10:11:41 -0500499spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
500{
501 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage) {
502 return spv::MemoryAccessMaskNone;
503 }
504 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
505 if (coherentFlags.volatil ||
506 coherentFlags.coherent ||
507 coherentFlags.devicecoherent ||
508 coherentFlags.queuefamilycoherent ||
509 coherentFlags.workgroupcoherent ||
510 coherentFlags.subgroupcoherent) {
511 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
512 spv::MemoryAccessMakePointerVisibleKHRMask;
513 }
514 if (coherentFlags.nonprivate) {
515 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
516 }
517 if (coherentFlags.volatil) {
518 mask = mask | spv::MemoryAccessVolatileMask;
519 }
520 if (mask != spv::MemoryAccessMaskNone) {
521 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
522 }
523 return mask;
524}
525
526spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
527{
528 if (!glslangIntermediate->usingVulkanMemoryModel()) {
529 return spv::ImageOperandsMaskNone;
530 }
531 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
532 if (coherentFlags.volatil ||
533 coherentFlags.coherent ||
534 coherentFlags.devicecoherent ||
535 coherentFlags.queuefamilycoherent ||
536 coherentFlags.workgroupcoherent ||
537 coherentFlags.subgroupcoherent) {
538 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
539 spv::ImageOperandsMakeTexelVisibleKHRMask;
540 }
541 if (coherentFlags.nonprivate) {
542 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
543 }
544 if (coherentFlags.volatil) {
545 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
546 }
547 if (mask != spv::ImageOperandsMaskNone) {
548 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
549 }
550 return mask;
551}
552
553spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
554{
555 spv::Builder::AccessChain::CoherentFlags flags;
556 flags.coherent = type.getQualifier().coherent;
557 flags.devicecoherent = type.getQualifier().devicecoherent;
558 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
559 // shared variables are implicitly workgroupcoherent in GLSL.
560 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
561 type.getQualifier().storage == glslang::EvqShared;
562 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600563 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500564 // *coherent variables are implicitly nonprivate in GLSL
565 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500566 flags.subgroupcoherent ||
567 flags.workgroupcoherent ||
568 flags.queuefamilycoherent ||
569 flags.devicecoherent ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600570 flags.coherent ||
571 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500572 flags.isImage = type.getBasicType() == glslang::EbtSampler;
573 return flags;
574}
575
576spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
577{
578 spv::Scope scope;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600579 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500580 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
581 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
582 } else if (coherentFlags.devicecoherent) {
583 scope = spv::ScopeDevice;
584 } else if (coherentFlags.queuefamilycoherent) {
585 scope = spv::ScopeQueueFamilyKHR;
586 } else if (coherentFlags.workgroupcoherent) {
587 scope = spv::ScopeWorkgroup;
588 } else if (coherentFlags.subgroupcoherent) {
589 scope = spv::ScopeSubgroup;
590 } else {
591 scope = spv::ScopeMax;
592 }
593 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
594 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
595 }
596 return scope;
597}
598
David Netoa901ffe2016-06-08 14:11:40 +0100599// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
600// associated capabilities when required. For some built-in variables, a capability
601// is generated only when using the variable in an executable instruction, but not when
602// just declaring a struct member variable with it. This is true for PointSize,
603// ClipDistance, and CullDistance.
604spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600605{
606 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700607 case glslang::EbvPointSize:
John Kessenich155d3512019-08-08 23:29:20 -0600608#ifndef GLSLANG_WEB
John Kessenich78a45572016-07-08 14:05:15 -0600609 // Defer adding the capability until the built-in is actually used.
610 if (! memberDeclaration) {
611 switch (glslangIntermediate->getStage()) {
612 case EShLangGeometry:
613 builder.addCapability(spv::CapabilityGeometryPointSize);
614 break;
615 case EShLangTessControl:
616 case EShLangTessEvaluation:
617 builder.addCapability(spv::CapabilityTessellationPointSize);
618 break;
619 default:
620 break;
621 }
John Kessenich92187592016-02-01 13:45:25 -0700622 }
John Kessenich155d3512019-08-08 23:29:20 -0600623#endif
John Kessenich92187592016-02-01 13:45:25 -0700624 return spv::BuiltInPointSize;
625
John Kessenicha28f7a72019-08-06 07:00:58 -0600626 case glslang::EbvPosition: return spv::BuiltInPosition;
627 case glslang::EbvVertexId: return spv::BuiltInVertexId;
628 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
629 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
630 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
631
632 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
633 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
634 case glslang::EbvFace: return spv::BuiltInFrontFacing;
635 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
636
637#ifndef GLSLANG_WEB
John Kessenichebb50532016-05-16 19:22:05 -0600638 // These *Distance capabilities logically belong here, but if the member is declared and
639 // then never used, consumers of SPIR-V prefer the capability not be declared.
640 // They are now generated when used, rather than here when declared.
641 // Potentially, the specification should be more clear what the minimum
642 // use needed is to trigger the capability.
643 //
John Kessenich92187592016-02-01 13:45:25 -0700644 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100645 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800646 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700647 return spv::BuiltInClipDistance;
648
649 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100650 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800651 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700652 return spv::BuiltInCullDistance;
653
654 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600655 builder.addCapability(spv::CapabilityMultiViewport);
656 if (glslangIntermediate->getStage() == EShLangVertex ||
657 glslangIntermediate->getStage() == EShLangTessControl ||
658 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800659
John Kessenichba6a3c22017-09-13 13:22:50 -0600660 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
661 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800662 }
John Kessenich92187592016-02-01 13:45:25 -0700663 return spv::BuiltInViewportIndex;
664
John Kessenich5e801132016-02-15 11:09:46 -0700665 case glslang::EbvSampleId:
666 builder.addCapability(spv::CapabilitySampleRateShading);
667 return spv::BuiltInSampleId;
668
669 case glslang::EbvSamplePosition:
670 builder.addCapability(spv::CapabilitySampleRateShading);
671 return spv::BuiltInSamplePosition;
672
673 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700674 return spv::BuiltInSampleMask;
675
John Kessenich78a45572016-07-08 14:05:15 -0600676 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700677 if (glslangIntermediate->getStage() == EShLangMeshNV) {
678 return spv::BuiltInLayer;
679 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600680 builder.addCapability(spv::CapabilityGeometry);
681 if (glslangIntermediate->getStage() == EShLangVertex ||
682 glslangIntermediate->getStage() == EShLangTessControl ||
683 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800684
John Kessenichba6a3c22017-09-13 13:22:50 -0600685 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
686 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800687 }
John Kessenich78a45572016-07-08 14:05:15 -0600688 return spv::BuiltInLayer;
689
John Kessenichda581a22015-10-14 14:10:30 -0600690 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700691 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800692 builder.addCapability(spv::CapabilityDrawParameters);
693 return spv::BuiltInBaseVertex;
694
John Kessenichda581a22015-10-14 14:10:30 -0600695 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700696 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800697 builder.addCapability(spv::CapabilityDrawParameters);
698 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200699
John Kessenichda581a22015-10-14 14:10:30 -0600700 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700701 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800702 builder.addCapability(spv::CapabilityDrawParameters);
703 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200704
705 case glslang::EbvPrimitiveId:
706 if (glslangIntermediate->getStage() == EShLangFragment)
707 builder.addCapability(spv::CapabilityGeometry);
708 return spv::BuiltInPrimitiveId;
709
Rex Xu37cdcee2017-06-29 17:46:34 +0800710 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800711 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
712 builder.addCapability(spv::CapabilityStencilExportEXT);
713 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800714
John Kessenich140f3df2015-06-26 16:58:36 -0600715 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600716 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
717 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
718 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
719 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
John Kessenich140f3df2015-06-26 16:58:36 -0600720 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
721 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
722 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
723 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
724 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
725 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
726 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800727
Rex Xu574ab042016-04-14 16:53:07 +0800728 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800729 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800730 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
731 return spv::BuiltInSubgroupSize;
732
Rex Xu574ab042016-04-14 16:53:07 +0800733 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800734 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800735 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
736 return spv::BuiltInSubgroupLocalInvocationId;
737
Rex Xu574ab042016-04-14 16:53:07 +0800738 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800739 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
740 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600741 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800742
Rex Xu574ab042016-04-14 16:53:07 +0800743 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800744 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
745 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600746 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800747
Rex Xu574ab042016-04-14 16:53:07 +0800748 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800749 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
750 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600751 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800752
Rex Xu574ab042016-04-14 16:53:07 +0800753 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800754 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
755 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600756 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800757
Rex Xu574ab042016-04-14 16:53:07 +0800758 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800759 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
760 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600761 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800762
John Kessenich66011cb2018-03-06 16:12:04 -0700763 case glslang::EbvNumSubgroups:
764 builder.addCapability(spv::CapabilityGroupNonUniform);
765 return spv::BuiltInNumSubgroups;
766
767 case glslang::EbvSubgroupID:
768 builder.addCapability(spv::CapabilityGroupNonUniform);
769 return spv::BuiltInSubgroupId;
770
771 case glslang::EbvSubgroupSize2:
772 builder.addCapability(spv::CapabilityGroupNonUniform);
773 return spv::BuiltInSubgroupSize;
774
775 case glslang::EbvSubgroupInvocation2:
776 builder.addCapability(spv::CapabilityGroupNonUniform);
777 return spv::BuiltInSubgroupLocalInvocationId;
778
779 case glslang::EbvSubgroupEqMask2:
780 builder.addCapability(spv::CapabilityGroupNonUniform);
781 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
782 return spv::BuiltInSubgroupEqMask;
783
784 case glslang::EbvSubgroupGeMask2:
785 builder.addCapability(spv::CapabilityGroupNonUniform);
786 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
787 return spv::BuiltInSubgroupGeMask;
788
789 case glslang::EbvSubgroupGtMask2:
790 builder.addCapability(spv::CapabilityGroupNonUniform);
791 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
792 return spv::BuiltInSubgroupGtMask;
793
794 case glslang::EbvSubgroupLeMask2:
795 builder.addCapability(spv::CapabilityGroupNonUniform);
796 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
797 return spv::BuiltInSubgroupLeMask;
798
799 case glslang::EbvSubgroupLtMask2:
800 builder.addCapability(spv::CapabilityGroupNonUniform);
801 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
802 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600803
Rex Xu17ff3432016-10-14 17:41:45 +0800804 case glslang::EbvBaryCoordNoPersp:
805 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
806 return spv::BuiltInBaryCoordNoPerspAMD;
807
808 case glslang::EbvBaryCoordNoPerspCentroid:
809 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
810 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
811
812 case glslang::EbvBaryCoordNoPerspSample:
813 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
814 return spv::BuiltInBaryCoordNoPerspSampleAMD;
815
816 case glslang::EbvBaryCoordSmooth:
817 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
818 return spv::BuiltInBaryCoordSmoothAMD;
819
820 case glslang::EbvBaryCoordSmoothCentroid:
821 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
822 return spv::BuiltInBaryCoordSmoothCentroidAMD;
823
824 case glslang::EbvBaryCoordSmoothSample:
825 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
826 return spv::BuiltInBaryCoordSmoothSampleAMD;
827
828 case glslang::EbvBaryCoordPullModel:
829 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
830 return spv::BuiltInBaryCoordPullModelAMD;
chaoc771d89f2017-01-13 01:10:53 -0800831
John Kessenich6c8aaac2017-02-27 01:20:51 -0700832 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700833 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700834 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700835 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700836
837 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700838 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700839 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700840 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700841
Daniel Koch5154db52018-11-26 10:01:58 -0500842 case glslang::EbvFragSizeEXT:
843 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
844 builder.addCapability(spv::CapabilityFragmentDensityEXT);
845 return spv::BuiltInFragSizeEXT;
846
847 case glslang::EbvFragInvocationCountEXT:
848 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
849 builder.addCapability(spv::CapabilityFragmentDensityEXT);
850 return spv::BuiltInFragInvocationCountEXT;
851
chaoc771d89f2017-01-13 01:10:53 -0800852 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800853 if (!memberDeclaration) {
854 builder.addExtension(spv::E_SPV_NV_viewport_array2);
855 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
856 }
chaoc771d89f2017-01-13 01:10:53 -0800857 return spv::BuiltInViewportMaskNV;
858 case glslang::EbvSecondaryPositionNV:
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::BuiltInSecondaryPositionNV;
864 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800865 if (!memberDeclaration) {
866 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
867 builder.addCapability(spv::CapabilityShaderStereoViewNV);
868 }
chaoc771d89f2017-01-13 01:10:53 -0800869 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800870 case glslang::EbvPositionPerViewNV:
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::BuiltInPositionPerViewNV;
876 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800877 if (!memberDeclaration) {
878 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
879 builder.addCapability(spv::CapabilityPerViewAttributesNV);
880 }
chaocdf3956c2017-02-14 14:52:34 -0800881 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700882 case glslang::EbvFragFullyCoveredNV:
883 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
884 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
885 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700886 case glslang::EbvFragmentSizeNV:
887 builder.addExtension(spv::E_SPV_NV_shading_rate);
888 builder.addCapability(spv::CapabilityShadingRateNV);
889 return spv::BuiltInFragmentSizeNV;
890 case glslang::EbvInvocationsPerPixelNV:
891 builder.addExtension(spv::E_SPV_NV_shading_rate);
892 builder.addCapability(spv::CapabilityShadingRateNV);
893 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700894
Daniel Koch593a4e02019-05-27 16:46:31 -0400895 // ray tracing
Chao Chenb50c02e2018-09-19 11:42:24 -0700896 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700897 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700898 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700899 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700900 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700901 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700902 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700903 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700904 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700905 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700906 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700907 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700908 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700909 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700910 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700911 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700912 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700913 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700914 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700915 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700916 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700917 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700918 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700919 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700920 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700921 return spv::BuiltInWorldToObjectNV;
922 case glslang::EbvIncomingRayFlagsNV:
923 return spv::BuiltInIncomingRayFlagsNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400924
925 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700926 case glslang::EbvBaryCoordNV:
927 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
928 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
929 return spv::BuiltInBaryCoordNV;
930 case glslang::EbvBaryCoordNoPerspNV:
931 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
932 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
933 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400934
935 // mesh shaders
936 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700937 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400938 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700939 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400940 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700941 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400942 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700943 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400944 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700945 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400946 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700947 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400948 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700949 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400950 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700951 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch2cb2f192019-06-04 08:43:32 -0400952
953 // sm builtins
954 case glslang::EbvWarpsPerSM:
955 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
956 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
957 return spv::BuiltInWarpsPerSMNV;
958 case glslang::EbvSMCount:
959 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
960 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
961 return spv::BuiltInSMCountNV;
962 case glslang::EbvWarpID:
963 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
964 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
965 return spv::BuiltInWarpIDNV;
966 case glslang::EbvSMID:
967 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
968 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
969 return spv::BuiltInSMIDNV;
John Kessenicha28f7a72019-08-06 07:00:58 -0600970#endif
971
Rex Xu3e783f92017-02-22 16:44:48 +0800972 default:
973 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600974 }
975}
976
Rex Xufc618912015-09-09 16:42:49 +0800977// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700978spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800979{
980 assert(type.getBasicType() == glslang::EbtSampler);
981
John Kessenich5d0fa972016-02-15 11:57:00 -0700982 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -0600983 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -0700984 case glslang::ElfRg32f:
985 case glslang::ElfRg16f:
986 case glslang::ElfR11fG11fB10f:
987 case glslang::ElfR16f:
988 case glslang::ElfRgba16:
989 case glslang::ElfRgb10A2:
990 case glslang::ElfRg16:
991 case glslang::ElfRg8:
992 case glslang::ElfR16:
993 case glslang::ElfR8:
994 case glslang::ElfRgba16Snorm:
995 case glslang::ElfRg16Snorm:
996 case glslang::ElfRg8Snorm:
997 case glslang::ElfR16Snorm:
998 case glslang::ElfR8Snorm:
999
1000 case glslang::ElfRg32i:
1001 case glslang::ElfRg16i:
1002 case glslang::ElfRg8i:
1003 case glslang::ElfR16i:
1004 case glslang::ElfR8i:
1005
1006 case glslang::ElfRgb10a2ui:
1007 case glslang::ElfRg32ui:
1008 case glslang::ElfRg16ui:
1009 case glslang::ElfRg8ui:
1010 case glslang::ElfR16ui:
1011 case glslang::ElfR8ui:
1012 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1013 break;
1014
1015 default:
1016 break;
1017 }
1018
1019 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001020 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001021 case glslang::ElfNone: return spv::ImageFormatUnknown;
1022 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1023 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1024 case glslang::ElfR32f: return spv::ImageFormatR32f;
1025 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1026 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1027 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1028 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1029 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1030 case glslang::ElfR16f: return spv::ImageFormatR16f;
1031 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1032 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1033 case glslang::ElfRg16: return spv::ImageFormatRg16;
1034 case glslang::ElfRg8: return spv::ImageFormatRg8;
1035 case glslang::ElfR16: return spv::ImageFormatR16;
1036 case glslang::ElfR8: return spv::ImageFormatR8;
1037 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1038 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1039 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1040 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1041 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1042 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1043 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1044 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1045 case glslang::ElfR32i: return spv::ImageFormatR32i;
1046 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1047 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1048 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1049 case glslang::ElfR16i: return spv::ImageFormatR16i;
1050 case glslang::ElfR8i: return spv::ImageFormatR8i;
1051 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1052 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1053 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1054 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1055 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1056 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1057 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1058 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1059 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1060 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001061 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001062 }
1063}
1064
John Kesseniche18fd202018-01-30 11:01:39 -07001065spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001066{
John Kesseniche18fd202018-01-30 11:01:39 -07001067 if (selectionNode.getFlatten())
1068 return spv::SelectionControlFlattenMask;
1069 if (selectionNode.getDontFlatten())
1070 return spv::SelectionControlDontFlattenMask;
1071 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001072}
1073
John Kesseniche18fd202018-01-30 11:01:39 -07001074spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001075{
John Kesseniche18fd202018-01-30 11:01:39 -07001076 if (switchNode.getFlatten())
1077 return spv::SelectionControlFlattenMask;
1078 if (switchNode.getDontFlatten())
1079 return spv::SelectionControlDontFlattenMask;
1080 return spv::SelectionControlMaskNone;
1081}
1082
John Kessenicha2858d92018-01-31 08:11:18 -07001083// return a non-0 dependency if the dependency argument must be set
1084spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001085 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001086{
1087 spv::LoopControlMask control = spv::LoopControlMaskNone;
1088
1089 if (loopNode.getDontUnroll())
1090 control = control | spv::LoopControlDontUnrollMask;
1091 if (loopNode.getUnroll())
1092 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001093 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001094 control = control | spv::LoopControlDependencyInfiniteMask;
1095 else if (loopNode.getLoopDependency() > 0) {
1096 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001097 operands.push_back((unsigned int)loopNode.getLoopDependency());
1098 }
1099 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1100 if (loopNode.getMinIterations() > 0) {
1101 control = control | spv::LoopControlMinIterationsMask;
1102 operands.push_back(loopNode.getMinIterations());
1103 }
1104 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1105 control = control | spv::LoopControlMaxIterationsMask;
1106 operands.push_back(loopNode.getMaxIterations());
1107 }
1108 if (loopNode.getIterationMultiple() > 1) {
1109 control = control | spv::LoopControlIterationMultipleMask;
1110 operands.push_back(loopNode.getIterationMultiple());
1111 }
1112 if (loopNode.getPeelCount() > 0) {
1113 control = control | spv::LoopControlPeelCountMask;
1114 operands.push_back(loopNode.getPeelCount());
1115 }
1116 if (loopNode.getPartialCount() > 0) {
1117 control = control | spv::LoopControlPartialCountMask;
1118 operands.push_back(loopNode.getPartialCount());
1119 }
John Kessenicha2858d92018-01-31 08:11:18 -07001120 }
John Kesseniche18fd202018-01-30 11:01:39 -07001121
1122 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001123}
1124
John Kessenicha5c5fb62017-05-05 05:09:58 -06001125// Translate glslang type to SPIR-V storage class.
1126spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1127{
1128 if (type.getQualifier().isPipeInput())
1129 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001130 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001131 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001132
1133 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001134 type.getQualifier().storage == glslang::EvqUniform) {
1135#ifndef GLSLANG_WEB
John Kessenichbed4e4f2017-09-08 02:38:07 -06001136 if (type.getBasicType() == glslang::EbtAtomicUint)
1137 return spv::StorageClassAtomicCounter;
John Kessenicha28f7a72019-08-06 07:00:58 -06001138#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001139 if (type.containsOpaque())
1140 return spv::StorageClassUniformConstant;
1141 }
1142
John Kessenicha28f7a72019-08-06 07:00:58 -06001143#ifndef GLSLANG_WEB
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001144 if (type.getQualifier().isUniformOrBuffer() &&
1145 type.getQualifier().layoutShaderRecordNV) {
1146 return spv::StorageClassShaderRecordBufferNV;
1147 }
1148#endif
1149
John Kessenichbed4e4f2017-09-08 02:38:07 -06001150 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001151 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001152 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001153 }
1154
1155 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha28f7a72019-08-06 07:00:58 -06001156#ifndef GLSLANG_WEB
John Kessenich7015bd62019-08-01 03:28:08 -06001157 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001158 return spv::StorageClassPushConstant;
John Kessenicha28f7a72019-08-06 07:00:58 -06001159#endif
John Kessenicha5c5fb62017-05-05 05:09:58 -06001160 if (type.getBasicType() == glslang::EbtBlock)
1161 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001162 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001163 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001164
1165 switch (type.getQualifier().storage) {
John Kessenichbed4e4f2017-09-08 02:38:07 -06001166 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1167 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1168 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenicha28f7a72019-08-06 07:00:58 -06001169#ifndef GLSLANG_WEB
1170 case glslang::EvqShared: return spv::StorageClassWorkgroup;
Ashwin Leleff1783d2018-10-22 16:41:44 -07001171 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1172 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1173 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1174 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1175 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001176#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001177 default:
1178 assert(0);
1179 break;
1180 }
1181
1182 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001183}
1184
John Kessenich5611c6d2018-04-05 11:25:02 -06001185// Add capabilities pertaining to how an array is indexed.
1186void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1187 const glslang::TType& indexType)
1188{
1189 if (indexType.getQualifier().isNonUniform()) {
1190 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001191 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001192 if (baseType.getBasicType() == glslang::EbtSampler) {
1193 if (baseType.getQualifier().hasAttachment())
1194 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001195 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001196 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001197 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001198 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1199 else if (baseType.isImage())
1200 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1201 else if (baseType.isTexture())
1202 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1203 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1204 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1205 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1206 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1207 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1208 }
1209 } else {
1210 // assume a dynamically uniform index
1211 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001212 if (baseType.getQualifier().hasAttachment()) {
1213 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001214 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001215 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001216 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001217 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001218 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001219 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001220 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001221 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001222 }
1223 }
1224}
1225
qining25262b32016-05-06 17:25:16 -04001226// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001227// descriptor set.
1228bool IsDescriptorResource(const glslang::TType& type)
1229{
John Kessenichf7497e22016-03-08 21:36:22 -07001230 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001231 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001232 return type.getQualifier().isUniformOrBuffer() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001233 ! type.getQualifier().isShaderRecordNV() &&
1234 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001235
1236 // non block...
1237 // basically samplerXXX/subpass/sampler/texture are all included
1238 // if they are the global-scope-class, not the function parameter
1239 // (or local, if they ever exist) class.
1240 if (type.getBasicType() == glslang::EbtSampler)
1241 return type.getQualifier().isUniformOrBuffer();
1242
1243 // None of the above.
1244 return false;
1245}
1246
John Kesseniche0b6cad2015-12-24 10:30:13 -07001247void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1248{
1249 if (child.layoutMatrix == glslang::ElmNone)
1250 child.layoutMatrix = parent.layoutMatrix;
1251
1252 if (parent.invariant)
1253 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001254 if (parent.flat)
1255 child.flat = true;
1256 if (parent.centroid)
1257 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001258#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001259 if (parent.nopersp)
1260 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001261 if (parent.explicitInterp)
1262 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001263 if (parent.perPrimitiveNV)
1264 child.perPrimitiveNV = true;
1265 if (parent.perViewNV)
1266 child.perViewNV = true;
1267 if (parent.perTaskNV)
1268 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001269 if (parent.patch)
1270 child.patch = true;
1271 if (parent.sample)
1272 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001273 if (parent.coherent)
1274 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001275 if (parent.devicecoherent)
1276 child.devicecoherent = true;
1277 if (parent.queuefamilycoherent)
1278 child.queuefamilycoherent = true;
1279 if (parent.workgroupcoherent)
1280 child.workgroupcoherent = true;
1281 if (parent.subgroupcoherent)
1282 child.subgroupcoherent = true;
1283 if (parent.nonprivate)
1284 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001285 if (parent.volatil)
1286 child.volatil = true;
1287 if (parent.restrict)
1288 child.restrict = true;
1289 if (parent.readonly)
1290 child.readonly = true;
1291 if (parent.writeonly)
1292 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001293#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001294}
1295
John Kessenichf2b7f332016-09-01 17:05:23 -06001296bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001297{
John Kessenich7b9fa252016-01-21 18:56:57 -07001298 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001299 // - struct members might inherit from a struct declaration
1300 // (note that non-block structs don't explicitly inherit,
1301 // only implicitly, meaning no decoration involved)
1302 // - affect decorations on the struct members
1303 // (note smooth does not, and expecting something like volatile
1304 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001305 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001306 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001307}
1308
John Kessenich140f3df2015-06-26 16:58:36 -06001309//
1310// Implement the TGlslangToSpvTraverser class.
1311//
1312
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001313TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001314 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1315 : TIntermTraverser(true, false, true),
1316 options(options),
1317 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001318 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001319 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001320 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich605afc72019-06-17 23:33:09 -06001321 glslangIntermediate(glslangIntermediate),
1322 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp())
John Kessenich140f3df2015-06-26 16:58:36 -06001323{
1324 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1325
1326 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001327 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1328 glslangIntermediate->getVersion());
1329
John Kessenich121853f2017-05-31 17:11:16 -06001330 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001331 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001332 builder.setSourceFile(glslangIntermediate->getSourceFile());
1333
1334 // Set the source shader's text. If for SPV version 1.0, include
1335 // a preamble in comments stating the OpModuleProcessed instructions.
1336 // Otherwise, emit those as actual instructions.
1337 std::string text;
1338 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1339 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001340 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001341 text.append("// OpModuleProcessed ");
1342 text.append(processes[p]);
1343 text.append("\n");
1344 } else
1345 builder.addModuleProcessed(processes[p]);
1346 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001347 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001348 text.append("#line 1\n");
1349 text.append(glslangIntermediate->getSourceText());
1350 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001351 // Pass name and text for all included files
1352 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1353 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1354 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001355 }
John Kessenich140f3df2015-06-26 16:58:36 -06001356 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001357
1358 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1359 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1360
1361 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1362 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
1363 builder.addExtension(spv::E_SPV_EXT_physical_storage_buffer);
1364 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1365 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001366 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001367 memoryModel = spv::MemoryModelVulkanKHR;
1368 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
Jeff Bolz36831c92018-09-05 10:11:41 -05001369 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
Jeff Bolz36831c92018-09-05 10:11:41 -05001370 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001371 builder.setMemoryModel(addressingModel, memoryModel);
1372
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001373 if (glslangIntermediate->usingVariablePointers()) {
1374 builder.addCapability(spv::CapabilityVariablePointers);
1375 }
1376
John Kessenicheee9d532016-09-19 18:09:30 -06001377 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1378 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001379
1380 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001381 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1382 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001383 builder.addSourceExtension(it->c_str());
1384
1385 // Add the top-level modes for this shader.
1386
John Kessenich92187592016-02-01 13:45:25 -07001387 if (glslangIntermediate->getXfbMode()) {
1388 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001389 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001390 }
John Kessenich140f3df2015-06-26 16:58:36 -06001391
1392 unsigned int mode;
1393 switch (glslangIntermediate->getStage()) {
1394 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001395 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001396 break;
1397
John Kessenicha28f7a72019-08-06 07:00:58 -06001398 case EShLangFragment:
1399 builder.addCapability(spv::CapabilityShader);
1400 if (glslangIntermediate->getPixelCenterInteger())
1401 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1402
1403 if (glslangIntermediate->getOriginUpperLeft())
1404 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1405 else
1406 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1407
1408 if (glslangIntermediate->getEarlyFragmentTests())
1409 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1410
1411 if (glslangIntermediate->getPostDepthCoverage()) {
1412 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1413 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1414 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1415 }
1416
1417 switch(glslangIntermediate->getDepth()) {
1418 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1419 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1420 default: mode = spv::ExecutionModeMax; break;
1421 }
1422 if (mode != spv::ExecutionModeMax)
1423 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1424
1425 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1426 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1427
1428 switch (glslangIntermediate->getInterlockOrdering()) {
1429 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT; break;
1430 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT; break;
1431 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT; break;
1432 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT; break;
1433 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT; break;
1434 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT; break;
1435 default: mode = spv::ExecutionModeMax; break;
1436 }
1437 if (mode != spv::ExecutionModeMax) {
1438 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1439 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1440 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1441 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1442 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1443 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1444 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1445 } else {
1446 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1447 }
1448 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1449 }
1450
1451 break;
1452
1453#ifndef GLSLANG_WEB
1454 case EShLangCompute:
1455 builder.addCapability(spv::CapabilityShader);
1456 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1457 glslangIntermediate->getLocalSize(1),
1458 glslangIntermediate->getLocalSize(2));
1459 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1460 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1461 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1462 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1463 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1464 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1465 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1466 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1467 }
1468 break;
steve-lunarge7412492017-03-23 11:56:07 -06001469 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001470 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001471 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001472
steve-lunarge7412492017-03-23 11:56:07 -06001473 glslang::TLayoutGeometry primitive;
1474
1475 if (glslangIntermediate->getStage() == EShLangTessControl) {
1476 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1477 primitive = glslangIntermediate->getOutputPrimitive();
1478 } else {
1479 primitive = glslangIntermediate->getInputPrimitive();
1480 }
1481
1482 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001483 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1484 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1485 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001486 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001487 }
John Kessenich4016e382016-07-15 11:53:56 -06001488 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001489 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1490
John Kesseniche6903322015-10-13 16:29:02 -06001491 switch (glslangIntermediate->getVertexSpacing()) {
1492 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1493 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1494 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001495 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001496 }
John Kessenich4016e382016-07-15 11:53:56 -06001497 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001498 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1499
1500 switch (glslangIntermediate->getVertexOrder()) {
1501 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1502 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001503 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001504 }
John Kessenich4016e382016-07-15 11:53:56 -06001505 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001506 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1507
1508 if (glslangIntermediate->getPointMode())
1509 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001510 break;
1511
1512 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001513 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001514 switch (glslangIntermediate->getInputPrimitive()) {
1515 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1516 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1517 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001518 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001519 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001520 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001521 }
John Kessenich4016e382016-07-15 11:53:56 -06001522 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001523 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001524
John Kessenich140f3df2015-06-26 16:58:36 -06001525 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1526
1527 switch (glslangIntermediate->getOutputPrimitive()) {
1528 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1529 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1530 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001531 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001532 }
John Kessenich4016e382016-07-15 11:53:56 -06001533 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001534 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1535 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1536 break;
1537
Chao Chenb50c02e2018-09-19 11:42:24 -07001538 case EShLangRayGenNV:
1539 case EShLangIntersectNV:
1540 case EShLangAnyHitNV:
1541 case EShLangClosestHitNV:
1542 case EShLangMissNV:
1543 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001544 builder.addCapability(spv::CapabilityRayTracingNV);
1545 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001546 break;
Chao Chen3c366992018-09-19 11:41:59 -07001547 case EShLangTaskNV:
1548 case EShLangMeshNV:
1549 builder.addCapability(spv::CapabilityMeshShadingNV);
1550 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1551 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1552 glslangIntermediate->getLocalSize(1),
1553 glslangIntermediate->getLocalSize(2));
1554 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1555 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1556 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1557
1558 switch (glslangIntermediate->getOutputPrimitive()) {
1559 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1560 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1561 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1562 default: mode = spv::ExecutionModeMax; break;
1563 }
1564 if (mode != spv::ExecutionModeMax)
1565 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1566 }
1567 break;
1568#endif
1569
John Kessenich140f3df2015-06-26 16:58:36 -06001570 default:
1571 break;
1572 }
John Kessenich140f3df2015-06-26 16:58:36 -06001573}
1574
John Kessenichfca82622016-11-26 13:23:20 -07001575// Finish creating SPV, after the traversal is complete.
1576void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001577{
John Kessenichf04c51b2018-08-03 15:56:12 -06001578 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001579 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001580 builder.setBuildPoint(shaderEntry->getLastBlock());
1581 builder.leaveFunction();
1582 }
1583
John Kessenich7ba63412015-12-20 17:37:07 -07001584 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001585 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1586 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001587
John Kessenich23d27752019-07-28 02:12:10 -06001588#ifndef GLSLANG_WEB
John Kessenichf04c51b2018-08-03 15:56:12 -06001589 // Add capabilities, extensions, remove unneeded decorations, etc.,
1590 // based on the resulting SPIR-V.
1591 builder.postProcess();
John Kessenich23d27752019-07-28 02:12:10 -06001592#endif
John Kessenich7ba63412015-12-20 17:37:07 -07001593}
1594
John Kessenichfca82622016-11-26 13:23:20 -07001595// Write the SPV into 'out'.
1596void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001597{
John Kessenichfca82622016-11-26 13:23:20 -07001598 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001599}
1600
1601//
1602// Implement the traversal functions.
1603//
1604// Return true from interior nodes to have the external traversal
1605// continue on to children. Return false if children were
1606// already processed.
1607//
1608
1609//
qining25262b32016-05-06 17:25:16 -04001610// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001611// - uniform/input reads
1612// - output writes
1613// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1614// - something simple that degenerates into the last bullet
1615//
1616void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1617{
qining75d1d802016-04-06 14:42:01 -04001618 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1619 if (symbol->getType().getQualifier().isSpecConstant())
1620 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1621
John Kessenich140f3df2015-06-26 16:58:36 -06001622 // getSymbolId() will set up all the IO decorations on the first call.
1623 // Formal function parameters were mapped during makeFunctions().
1624 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001625
John Kessenich7ba63412015-12-20 17:37:07 -07001626 if (builder.isPointer(id)) {
John Kessenich9c14f772019-06-17 08:38:35 -06001627 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
John Kessenich7c7731e2019-01-04 16:47:06 +07001628 // Consider adding to the OpEntryPoint interface list.
1629 // Only looking at structures if they have at least one member.
1630 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1631 spv::StorageClass sc = builder.getStorageClass(id);
1632 // Before SPIR-V 1.4, we only want to include Input and Output.
1633 // Starting with SPIR-V 1.4, we want all globals.
1634 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1635 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001636 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001637 }
John Kessenich5f77d862017-09-19 11:09:59 -06001638 }
John Kessenich9c14f772019-06-17 08:38:35 -06001639
1640 // If the SPIR-V type is required to be different than the AST type,
1641 // translate now from the SPIR-V type to the AST type, for the consuming
1642 // operation.
1643 // Note this turns it from an l-value to an r-value.
1644 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1645 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1646 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001647 }
1648
1649 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001650 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001651 // Prepare to generate code for the access
1652
1653 // L-value chains will be computed left to right. We're on the symbol now,
1654 // which is the left-most part of the access chain, so now is "clear" time,
1655 // followed by setting the base.
1656 builder.clearAccessChain();
1657
1658 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001659 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001660 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001661 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001662 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001663 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001664 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001665 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001666 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1667 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001668 builder.setAccessChainRValue(id);
1669 else
1670 builder.setAccessChainLValue(id);
1671 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001672
John Kessenich155d3512019-08-08 23:29:20 -06001673#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07001674 // Process linkage-only nodes for any special additional interface work.
1675 if (linkageOnly) {
1676 if (glslangIntermediate->getHlslFunctionality1()) {
1677 // Map implicit counter buffers to their originating buffers, which should have been
1678 // seen by now, given earlier pruning of unused counters, and preservation of order
1679 // of declaration.
1680 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1681 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1682 // Save possible originating buffers for counter buffers, keyed by
1683 // making the potential counter-buffer name.
1684 std::string keyName = symbol->getName().c_str();
1685 keyName = glslangIntermediate->addCounterBufferName(keyName);
1686 counterOriginator[keyName] = symbol;
1687 } else {
1688 // Handle a counter buffer, by finding the saved originating buffer.
1689 std::string keyName = symbol->getName().c_str();
1690 auto it = counterOriginator.find(keyName);
1691 if (it != counterOriginator.end()) {
1692 id = getSymbolId(it->second);
1693 if (id != spv::NoResult) {
1694 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001695 if (counterId != spv::NoResult) {
1696 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001697 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001698 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001699 }
1700 }
1701 }
1702 }
1703 }
1704 }
John Kessenich155d3512019-08-08 23:29:20 -06001705#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001706}
1707
1708bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1709{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001710 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001711
qining40887662016-04-03 22:20:42 -04001712 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1713 if (node->getType().getQualifier().isSpecConstant())
1714 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1715
John Kessenich140f3df2015-06-26 16:58:36 -06001716 // First, handle special cases
1717 switch (node->getOp()) {
1718 case glslang::EOpAssign:
1719 case glslang::EOpAddAssign:
1720 case glslang::EOpSubAssign:
1721 case glslang::EOpMulAssign:
1722 case glslang::EOpVectorTimesMatrixAssign:
1723 case glslang::EOpVectorTimesScalarAssign:
1724 case glslang::EOpMatrixTimesScalarAssign:
1725 case glslang::EOpMatrixTimesMatrixAssign:
1726 case glslang::EOpDivAssign:
1727 case glslang::EOpModAssign:
1728 case glslang::EOpAndAssign:
1729 case glslang::EOpInclusiveOrAssign:
1730 case glslang::EOpExclusiveOrAssign:
1731 case glslang::EOpLeftShiftAssign:
1732 case glslang::EOpRightShiftAssign:
1733 // A bin-op assign "a += b" means the same thing as "a = a + b"
1734 // where a is evaluated before b. For a simple assignment, GLSL
1735 // says to evaluate the left before the right. So, always, left
1736 // node then right node.
1737 {
1738 // get the left l-value, save it away
1739 builder.clearAccessChain();
1740 node->getLeft()->traverse(this);
1741 spv::Builder::AccessChain lValue = builder.getAccessChain();
1742
1743 // evaluate the right
1744 builder.clearAccessChain();
1745 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001746 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001747
1748 if (node->getOp() != glslang::EOpAssign) {
1749 // the left is also an r-value
1750 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001751 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001752
1753 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001754 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001755 TranslateNoContractionDecoration(node->getType().getQualifier()),
1756 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001757 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001758 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1759 node->getType().getBasicType());
1760
1761 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001762 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001763 }
1764
1765 // store the result
1766 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001767 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001768
1769 // assignments are expressions having an rValue after they are evaluated...
1770 builder.clearAccessChain();
1771 builder.setAccessChainRValue(rValue);
1772 }
1773 return false;
1774 case glslang::EOpIndexDirect:
1775 case glslang::EOpIndexDirectStruct:
1776 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001777 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001778 // Get the left part of the access chain.
1779 node->getLeft()->traverse(this);
1780
1781 // Add the next element in the chain
1782
David Netoa901ffe2016-06-08 14:11:40 +01001783 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001784 if (! node->getLeft()->getType().isArray() &&
1785 node->getLeft()->getType().isVector() &&
1786 node->getOp() == glslang::EOpIndexDirect) {
1787 // This is essentially a hard-coded vector swizzle of size 1,
1788 // so short circuit the access-chain stuff with a swizzle.
1789 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001790 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001791 int dummySize;
1792 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1793 TranslateCoherent(node->getLeft()->getType()),
1794 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001795 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001796
1797 // Load through a block reference is performed with a dot operator that
1798 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1799 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001800 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001801 !node->getLeft()->getType().isArray() &&
1802 node->getOp() == glslang::EOpIndexDirectStruct)
1803 {
1804 spv::Id left = accessChainLoad(node->getLeft()->getType());
1805 builder.clearAccessChain();
1806 builder.setAccessChainLValue(left);
1807 }
1808
David Netoa901ffe2016-06-08 14:11:40 +01001809 int spvIndex = glslangIndex;
1810 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1811 node->getOp() == glslang::EOpIndexDirectStruct)
1812 {
1813 // This may be, e.g., an anonymous block-member selection, which generally need
1814 // index remapping due to hidden members in anonymous blocks.
1815 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1816 assert(remapper.size() > 0);
1817 spvIndex = remapper[glslangIndex];
1818 }
John Kessenichebb50532016-05-16 19:22:05 -06001819
David Netoa901ffe2016-06-08 14:11:40 +01001820 // normal case for indexing array or structure or block
Jeff Bolz7895e472019-03-06 13:34:10 -06001821 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001822
1823 // Add capabilities here for accessing PointSize and clip/cull distance.
1824 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001825 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001826 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001827 }
1828 }
1829 return false;
1830 case glslang::EOpIndexIndirect:
1831 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001832 // Array, matrix, or vector indirection with variable index.
1833 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001834 // matrices are arrays of vectors, so will also work for a matrix.
1835 // Will use the access chain's 'component' for variable index into a vector.
1836
1837 // This adapter is building access chains left to right.
1838 // Set up the access chain to the left.
1839 node->getLeft()->traverse(this);
1840
1841 // save it so that computing the right side doesn't trash it
1842 spv::Builder::AccessChain partial = builder.getAccessChain();
1843
1844 // compute the next index in the chain
1845 builder.clearAccessChain();
1846 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001847 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001848
John Kessenich5611c6d2018-04-05 11:25:02 -06001849 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1850
John Kessenich140f3df2015-06-26 16:58:36 -06001851 // restore the saved access chain
1852 builder.setAccessChain(partial);
1853
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001854 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1855 int dummySize;
1856 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1857 TranslateCoherent(node->getLeft()->getType()),
1858 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1859 } else
Jeff Bolz7895e472019-03-06 13:34:10 -06001860 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001861 }
1862 return false;
1863 case glslang::EOpVectorSwizzle:
1864 {
1865 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001866 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001867 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001868 int dummySize;
1869 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1870 TranslateCoherent(node->getLeft()->getType()),
1871 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001872 }
1873 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001874 case glslang::EOpMatrixSwizzle:
1875 logger->missingFunctionality("matrix swizzle");
1876 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001877 case glslang::EOpLogicalOr:
1878 case glslang::EOpLogicalAnd:
1879 {
1880
1881 // These may require short circuiting, but can sometimes be done as straight
1882 // binary operations. The right operand must be short circuited if it has
1883 // side effects, and should probably be if it is complex.
1884 if (isTrivial(node->getRight()->getAsTyped()))
1885 break; // handle below as a normal binary operation
1886 // otherwise, we need to do dynamic short circuiting on the right operand
1887 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1888 builder.clearAccessChain();
1889 builder.setAccessChainRValue(result);
1890 }
1891 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001892 default:
1893 break;
1894 }
1895
1896 // Assume generic binary op...
1897
John Kessenich32cfd492016-02-02 12:37:46 -07001898 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001899 builder.clearAccessChain();
1900 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001901 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001902
John Kessenich32cfd492016-02-02 12:37:46 -07001903 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001904 builder.clearAccessChain();
1905 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001906 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001907
John Kessenich32cfd492016-02-02 12:37:46 -07001908 // get result
John Kessenichead86222018-03-28 18:01:20 -06001909 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001910 TranslateNoContractionDecoration(node->getType().getQualifier()),
1911 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001912 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001913 convertGlslangToSpvType(node->getType()), left, right,
1914 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001915
John Kessenich50e57562015-12-21 21:21:11 -07001916 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001917 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001918 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001919 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001920 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001921 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001922 return false;
1923 }
John Kessenich140f3df2015-06-26 16:58:36 -06001924}
1925
John Kessenich9c14f772019-06-17 08:38:35 -06001926// Figure out what, if any, type changes are needed when accessing a specific built-in.
1927// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
1928// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
1929std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(spv::BuiltIn builtIn,
1930 const glslang::TType& glslangType)
1931{
1932 switch(builtIn)
1933 {
1934 case spv::BuiltInSubgroupEqMask:
1935 case spv::BuiltInSubgroupGeMask:
1936 case spv::BuiltInSubgroupGtMask:
1937 case spv::BuiltInSubgroupLeMask:
1938 case spv::BuiltInSubgroupLtMask: {
1939 // these require changing a 64-bit scaler -> a vector of 32-bit components
1940 if (glslangType.isVector())
1941 break;
1942 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
1943 builder.makeUintType(64));
1944 return ret;
1945 }
1946 default:
1947 break;
1948 }
1949
1950 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
1951 return ret;
1952}
1953
1954// For an object previously identified (see getForcedType() and forceType)
1955// as needing type translations, do the translation needed for a load, turning
1956// an L-value into in R-value.
1957spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
1958{
1959 const auto forceIt = forceType.find(object);
1960 if (forceIt == forceType.end())
1961 return object;
1962
1963 spv::Id desiredTypeId = forceIt->second;
1964 spv::Id objectTypeId = builder.getTypeId(object);
1965 assert(builder.isPointerType(objectTypeId));
1966 objectTypeId = builder.getContainedTypeId(objectTypeId);
1967 if (builder.isVectorType(objectTypeId) &&
1968 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
1969 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
1970 // handle 32-bit v.xy* -> 64-bit
1971 builder.clearAccessChain();
1972 builder.setAccessChainLValue(object);
1973 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
1974 std::vector<spv::Id> components;
1975 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
1976 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
1977
1978 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
1979 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
1980 builder.createCompositeConstruct(vecType, components));
1981 } else {
1982 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
1983 }
1984 } else {
1985 logger->missingFunctionality("forcing non 32-bit vector type");
1986 }
1987
1988 return object;
1989}
1990
John Kessenich140f3df2015-06-26 16:58:36 -06001991bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1992{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001993 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001994
qining40887662016-04-03 22:20:42 -04001995 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1996 if (node->getType().getQualifier().isSpecConstant())
1997 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1998
John Kessenichfc51d282015-08-19 13:34:18 -06001999 spv::Id result = spv::NoResult;
2000
2001 // try texturing first
2002 result = createImageTextureFunctionCall(node);
2003 if (result != spv::NoResult) {
2004 builder.clearAccessChain();
2005 builder.setAccessChainRValue(result);
2006
2007 return false; // done with this node
2008 }
2009
2010 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002011
2012 if (node->getOp() == glslang::EOpArrayLength) {
2013 // Quite special; won't want to evaluate the operand.
2014
John Kessenich5611c6d2018-04-05 11:25:02 -06002015 // Currently, the front-end does not allow .length() on an array until it is sized,
2016 // except for the last block membeor of an SSBO.
2017 // TODO: If this changes, link-time sized arrays might show up here, and need their
2018 // size extracted.
2019
John Kessenichc9a80832015-09-12 12:17:44 -06002020 // Normal .length() would have been constant folded by the front-end.
2021 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002022 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002023
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002024 spv::Id length;
2025 if (node->getOperand()->getType().isCoopMat()) {
2026 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2027
2028 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2029 assert(builder.isCooperativeMatrixType(typeId));
2030
2031 length = builder.createCooperativeMatrixLength(typeId);
2032 } else {
2033 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2034 block->traverse(this);
2035 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
2036 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2037 }
John Kessenichc9a80832015-09-12 12:17:44 -06002038
John Kessenich8c869672018-11-28 07:01:37 -07002039 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2040 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2041 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002042 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2043 if (builder.isInSpecConstCodeGenMode()) {
2044 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2045 } else {
2046 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2047 }
2048 }
John Kessenich8c869672018-11-28 07:01:37 -07002049
John Kessenichc9a80832015-09-12 12:17:44 -06002050 builder.clearAccessChain();
2051 builder.setAccessChainRValue(length);
2052
2053 return false;
2054 }
2055
John Kessenichfc51d282015-08-19 13:34:18 -06002056 // Start by evaluating the operand
2057
John Kessenich8c8505c2016-07-26 12:50:38 -06002058 // Does it need a swizzle inversion? If so, evaluation is inverted;
2059 // operate first on the swizzle base, then apply the swizzle.
2060 spv::Id invertedType = spv::NoType;
2061 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
2062 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2063 invertedType = getInvertedSwizzleType(*node->getOperand());
2064
John Kessenich140f3df2015-06-26 16:58:36 -06002065 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002066 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002067 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002068 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002069 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002070 operandNode = node->getOperand();
2071
2072 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002073
Rex Xufc618912015-09-09 16:42:49 +08002074 spv::Id operand = spv::NoResult;
2075
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002076 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2077
Rex Xufc618912015-09-09 16:42:49 +08002078 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2079 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002080 node->getOp() == glslang::EOpAtomicCounter ||
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002081 node->getOp() == glslang::EOpInterpolateAtCentroid) {
Rex Xufc618912015-09-09 16:42:49 +08002082 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002083 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2084 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2085 } else
John Kessenich32cfd492016-02-02 12:37:46 -07002086 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002087
John Kessenichead86222018-03-28 18:01:20 -06002088 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002089 TranslateNoContractionDecoration(node->getType().getQualifier()),
2090 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002091
2092 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002093 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06002094 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002095
2096 // if not, then possibly an operation
2097 if (! result)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002098 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002099
2100 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002101 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002102 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002103 builder.addDecoration(result, decorations.nonUniform);
2104 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002105
John Kessenich140f3df2015-06-26 16:58:36 -06002106 builder.clearAccessChain();
2107 builder.setAccessChainRValue(result);
2108
2109 return false; // done with this node
2110 }
2111
2112 // it must be a special case, check...
2113 switch (node->getOp()) {
2114 case glslang::EOpPostIncrement:
2115 case glslang::EOpPostDecrement:
2116 case glslang::EOpPreIncrement:
2117 case glslang::EOpPreDecrement:
2118 {
2119 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002120 spv::Id one = 0;
2121 if (node->getBasicType() == glslang::EbtFloat)
2122 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002123#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002124 else if (node->getBasicType() == glslang::EbtDouble)
2125 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002126 else if (node->getBasicType() == glslang::EbtFloat16)
2127 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002128 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2129 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002130 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2131 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002132 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2133 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002134#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002135 else
2136 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002137 glslang::TOperator op;
2138 if (node->getOp() == glslang::EOpPreIncrement ||
2139 node->getOp() == glslang::EOpPostIncrement)
2140 op = glslang::EOpAdd;
2141 else
2142 op = glslang::EOpSub;
2143
John Kessenichead86222018-03-28 18:01:20 -06002144 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002145 convertGlslangToSpvType(node->getType()), operand, one,
2146 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002147 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002148
2149 // The result of operation is always stored, but conditionally the
2150 // consumed result. The consumed result is always an r-value.
2151 builder.accessChainStore(result);
2152 builder.clearAccessChain();
2153 if (node->getOp() == glslang::EOpPreIncrement ||
2154 node->getOp() == glslang::EOpPreDecrement)
2155 builder.setAccessChainRValue(result);
2156 else
2157 builder.setAccessChainRValue(operand);
2158 }
2159
2160 return false;
2161
John Kessenich155d3512019-08-08 23:29:20 -06002162#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002163 case glslang::EOpEmitStreamVertex:
2164 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2165 return false;
2166 case glslang::EOpEndStreamPrimitive:
2167 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2168 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002169#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002170
2171 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002172 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002173 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002174 }
John Kessenich140f3df2015-06-26 16:58:36 -06002175}
2176
Jeff Bolz53134492019-06-25 13:31:10 -05002177// Construct a composite object, recursively copying members if their types don't match
2178spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2179{
2180 for (int c = 0; c < (int)constituents.size(); ++c) {
2181 spv::Id& constituent = constituents[c];
2182 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2183 spv::Id rType = builder.getTypeId(constituent);
2184 if (lType != rType) {
2185 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2186 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2187 } else if (builder.isStructType(rType)) {
2188 std::vector<spv::Id> rTypeConstituents;
2189 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2190 for (int i = 0; i < numrTypeConstituents; ++i) {
2191 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, builder.getContainedTypeId(rType, i), i));
2192 }
2193 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2194 } else {
2195 assert(builder.isArrayType(rType));
2196 std::vector<spv::Id> rTypeConstituents;
2197 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2198
2199 spv::Id elementRType = builder.getContainedTypeId(rType);
2200 for (int i = 0; i < numrTypeConstituents; ++i) {
2201 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2202 }
2203 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2204 }
2205 }
2206 }
2207 return builder.createCompositeConstruct(resultTypeId, constituents);
2208}
2209
John Kessenich140f3df2015-06-26 16:58:36 -06002210bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2211{
qining27e04a02016-04-14 16:40:20 -04002212 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2213 if (node->getType().getQualifier().isSpecConstant())
2214 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2215
John Kessenichfc51d282015-08-19 13:34:18 -06002216 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002217 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2218 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002219
2220 // try texturing
2221 result = createImageTextureFunctionCall(node);
2222 if (result != spv::NoResult) {
2223 builder.clearAccessChain();
2224 builder.setAccessChainRValue(result);
2225
2226 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002227 }
2228#ifndef GLSLANG_WEB
2229 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002230 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002231 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002232 // "imageStore" is a special case, which has no result
2233 return false;
2234 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002235#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002236
John Kessenich140f3df2015-06-26 16:58:36 -06002237 glslang::TOperator binOp = glslang::EOpNull;
2238 bool reduceComparison = true;
2239 bool isMatrix = false;
2240 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002241 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002242
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002243 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2244
John Kessenich140f3df2015-06-26 16:58:36 -06002245 assert(node->getOp());
2246
John Kessenichf6640762016-08-01 19:44:00 -06002247 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002248
2249 switch (node->getOp()) {
2250 case glslang::EOpSequence:
2251 {
2252 if (preVisit)
2253 ++sequenceDepth;
2254 else
2255 --sequenceDepth;
2256
2257 if (sequenceDepth == 1) {
2258 // If this is the parent node of all the functions, we want to see them
2259 // early, so all call points have actual SPIR-V functions to reference.
2260 // In all cases, still let the traverser visit the children for us.
2261 makeFunctions(node->getAsAggregate()->getSequence());
2262
John Kessenich6fccb3c2016-09-19 16:01:41 -06002263 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002264 // anything else gets there, so visit out of order, doing them all now.
2265 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2266
John Kessenich6a60c2f2016-12-08 21:01:59 -07002267 // 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 -06002268 // so do them manually.
2269 visitFunctions(node->getAsAggregate()->getSequence());
2270
2271 return false;
2272 }
2273
2274 return true;
2275 }
2276 case glslang::EOpLinkerObjects:
2277 {
2278 if (visit == glslang::EvPreVisit)
2279 linkageOnly = true;
2280 else
2281 linkageOnly = false;
2282
2283 return true;
2284 }
2285 case glslang::EOpComma:
2286 {
2287 // processing from left to right naturally leaves the right-most
2288 // lying around in the access chain
2289 glslang::TIntermSequence& glslangOperands = node->getSequence();
2290 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2291 glslangOperands[i]->traverse(this);
2292
2293 return false;
2294 }
2295 case glslang::EOpFunction:
2296 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002297 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002298 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002299 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002300 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002301 } else {
2302 handleFunctionEntry(node);
2303 }
2304 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002305 if (inEntryPoint)
2306 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002307 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002308 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002309 }
2310
2311 return true;
2312 case glslang::EOpParameters:
2313 // Parameters will have been consumed by EOpFunction processing, but not
2314 // the body, so we still visited the function node's children, making this
2315 // child redundant.
2316 return false;
2317 case glslang::EOpFunctionCall:
2318 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002319 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002320 if (node->isUserDefined())
2321 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002322 // 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 -07002323 if (result) {
2324 builder.clearAccessChain();
2325 builder.setAccessChainRValue(result);
2326 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002327 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002328
2329 return false;
2330 }
2331 case glslang::EOpConstructMat2x2:
2332 case glslang::EOpConstructMat2x3:
2333 case glslang::EOpConstructMat2x4:
2334 case glslang::EOpConstructMat3x2:
2335 case glslang::EOpConstructMat3x3:
2336 case glslang::EOpConstructMat3x4:
2337 case glslang::EOpConstructMat4x2:
2338 case glslang::EOpConstructMat4x3:
2339 case glslang::EOpConstructMat4x4:
2340 case glslang::EOpConstructDMat2x2:
2341 case glslang::EOpConstructDMat2x3:
2342 case glslang::EOpConstructDMat2x4:
2343 case glslang::EOpConstructDMat3x2:
2344 case glslang::EOpConstructDMat3x3:
2345 case glslang::EOpConstructDMat3x4:
2346 case glslang::EOpConstructDMat4x2:
2347 case glslang::EOpConstructDMat4x3:
2348 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002349 case glslang::EOpConstructIMat2x2:
2350 case glslang::EOpConstructIMat2x3:
2351 case glslang::EOpConstructIMat2x4:
2352 case glslang::EOpConstructIMat3x2:
2353 case glslang::EOpConstructIMat3x3:
2354 case glslang::EOpConstructIMat3x4:
2355 case glslang::EOpConstructIMat4x2:
2356 case glslang::EOpConstructIMat4x3:
2357 case glslang::EOpConstructIMat4x4:
2358 case glslang::EOpConstructUMat2x2:
2359 case glslang::EOpConstructUMat2x3:
2360 case glslang::EOpConstructUMat2x4:
2361 case glslang::EOpConstructUMat3x2:
2362 case glslang::EOpConstructUMat3x3:
2363 case glslang::EOpConstructUMat3x4:
2364 case glslang::EOpConstructUMat4x2:
2365 case glslang::EOpConstructUMat4x3:
2366 case glslang::EOpConstructUMat4x4:
2367 case glslang::EOpConstructBMat2x2:
2368 case glslang::EOpConstructBMat2x3:
2369 case glslang::EOpConstructBMat2x4:
2370 case glslang::EOpConstructBMat3x2:
2371 case glslang::EOpConstructBMat3x3:
2372 case glslang::EOpConstructBMat3x4:
2373 case glslang::EOpConstructBMat4x2:
2374 case glslang::EOpConstructBMat4x3:
2375 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002376 case glslang::EOpConstructF16Mat2x2:
2377 case glslang::EOpConstructF16Mat2x3:
2378 case glslang::EOpConstructF16Mat2x4:
2379 case glslang::EOpConstructF16Mat3x2:
2380 case glslang::EOpConstructF16Mat3x3:
2381 case glslang::EOpConstructF16Mat3x4:
2382 case glslang::EOpConstructF16Mat4x2:
2383 case glslang::EOpConstructF16Mat4x3:
2384 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002385 isMatrix = true;
2386 // fall through
2387 case glslang::EOpConstructFloat:
2388 case glslang::EOpConstructVec2:
2389 case glslang::EOpConstructVec3:
2390 case glslang::EOpConstructVec4:
2391 case glslang::EOpConstructDouble:
2392 case glslang::EOpConstructDVec2:
2393 case glslang::EOpConstructDVec3:
2394 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002395 case glslang::EOpConstructFloat16:
2396 case glslang::EOpConstructF16Vec2:
2397 case glslang::EOpConstructF16Vec3:
2398 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002399 case glslang::EOpConstructBool:
2400 case glslang::EOpConstructBVec2:
2401 case glslang::EOpConstructBVec3:
2402 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002403 case glslang::EOpConstructInt8:
2404 case glslang::EOpConstructI8Vec2:
2405 case glslang::EOpConstructI8Vec3:
2406 case glslang::EOpConstructI8Vec4:
2407 case glslang::EOpConstructUint8:
2408 case glslang::EOpConstructU8Vec2:
2409 case glslang::EOpConstructU8Vec3:
2410 case glslang::EOpConstructU8Vec4:
2411 case glslang::EOpConstructInt16:
2412 case glslang::EOpConstructI16Vec2:
2413 case glslang::EOpConstructI16Vec3:
2414 case glslang::EOpConstructI16Vec4:
2415 case glslang::EOpConstructUint16:
2416 case glslang::EOpConstructU16Vec2:
2417 case glslang::EOpConstructU16Vec3:
2418 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002419 case glslang::EOpConstructInt:
2420 case glslang::EOpConstructIVec2:
2421 case glslang::EOpConstructIVec3:
2422 case glslang::EOpConstructIVec4:
2423 case glslang::EOpConstructUint:
2424 case glslang::EOpConstructUVec2:
2425 case glslang::EOpConstructUVec3:
2426 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002427 case glslang::EOpConstructInt64:
2428 case glslang::EOpConstructI64Vec2:
2429 case glslang::EOpConstructI64Vec3:
2430 case glslang::EOpConstructI64Vec4:
2431 case glslang::EOpConstructUint64:
2432 case glslang::EOpConstructU64Vec2:
2433 case glslang::EOpConstructU64Vec3:
2434 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002435 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002436 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002437 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002438 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002439 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002440 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002441 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002442 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002443 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002444 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002445 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002446 else if (node->getOp() == glslang::EOpConstructStruct ||
2447 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2448 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002449 std::vector<spv::Id> constituents;
2450 for (int c = 0; c < (int)arguments.size(); ++c)
2451 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002452 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002453 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002454 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002455 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002456 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002457
2458 builder.clearAccessChain();
2459 builder.setAccessChainRValue(constructed);
2460
2461 return false;
2462 }
2463
2464 // These six are component-wise compares with component-wise results.
2465 // Forward on to createBinaryOperation(), requesting a vector result.
2466 case glslang::EOpLessThan:
2467 case glslang::EOpGreaterThan:
2468 case glslang::EOpLessThanEqual:
2469 case glslang::EOpGreaterThanEqual:
2470 case glslang::EOpVectorEqual:
2471 case glslang::EOpVectorNotEqual:
2472 {
2473 // Map the operation to a binary
2474 binOp = node->getOp();
2475 reduceComparison = false;
2476 switch (node->getOp()) {
2477 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2478 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2479 default: binOp = node->getOp(); break;
2480 }
2481
2482 break;
2483 }
2484 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002485 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002486 binOp = glslang::EOpMul;
2487 break;
2488 case glslang::EOpOuterProduct:
2489 // two vectors multiplied to make a matrix
2490 binOp = glslang::EOpOuterProduct;
2491 break;
2492 case glslang::EOpDot:
2493 {
qining25262b32016-05-06 17:25:16 -04002494 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002495 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002496 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002497 binOp = glslang::EOpMul;
2498 break;
2499 }
2500 case glslang::EOpMod:
2501 // when an aggregate, this is the floating-point mod built-in function,
2502 // which can be emitted by the one in createBinaryOperation()
2503 binOp = glslang::EOpMod;
2504 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002505
2506#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002507 case glslang::EOpEmitVertex:
2508 case glslang::EOpEndPrimitive:
2509 case glslang::EOpBarrier:
2510 case glslang::EOpMemoryBarrier:
2511 case glslang::EOpMemoryBarrierAtomicCounter:
2512 case glslang::EOpMemoryBarrierBuffer:
2513 case glslang::EOpMemoryBarrierImage:
2514 case glslang::EOpMemoryBarrierShared:
2515 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002516 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002517 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002518 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002519 case glslang::EOpWorkgroupMemoryBarrier:
2520 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002521 case glslang::EOpSubgroupBarrier:
2522 case glslang::EOpSubgroupMemoryBarrier:
2523 case glslang::EOpSubgroupMemoryBarrierBuffer:
2524 case glslang::EOpSubgroupMemoryBarrierImage:
2525 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002526 noReturnValue = true;
2527 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2528 break;
2529
Jeff Bolz36831c92018-09-05 10:11:41 -05002530 case glslang::EOpAtomicStore:
2531 noReturnValue = true;
2532 // fallthrough
2533 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002534 case glslang::EOpAtomicAdd:
2535 case glslang::EOpAtomicMin:
2536 case glslang::EOpAtomicMax:
2537 case glslang::EOpAtomicAnd:
2538 case glslang::EOpAtomicOr:
2539 case glslang::EOpAtomicXor:
2540 case glslang::EOpAtomicExchange:
2541 case glslang::EOpAtomicCompSwap:
2542 atomic = true;
2543 break;
2544
John Kessenich0d0c6d32017-07-23 16:08:26 -06002545 case glslang::EOpAtomicCounterAdd:
2546 case glslang::EOpAtomicCounterSubtract:
2547 case glslang::EOpAtomicCounterMin:
2548 case glslang::EOpAtomicCounterMax:
2549 case glslang::EOpAtomicCounterAnd:
2550 case glslang::EOpAtomicCounterOr:
2551 case glslang::EOpAtomicCounterXor:
2552 case glslang::EOpAtomicCounterExchange:
2553 case glslang::EOpAtomicCounterCompSwap:
2554 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2555 builder.addCapability(spv::CapabilityAtomicStorageOps);
2556 atomic = true;
2557 break;
2558
Chao Chenb50c02e2018-09-19 11:42:24 -07002559 case glslang::EOpIgnoreIntersectionNV:
2560 case glslang::EOpTerminateRayNV:
2561 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002562 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002563 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2564 noReturnValue = true;
2565 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002566 case glslang::EOpCooperativeMatrixLoad:
2567 case glslang::EOpCooperativeMatrixStore:
2568 noReturnValue = true;
2569 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002570 case glslang::EOpBeginInvocationInterlock:
2571 case glslang::EOpEndInvocationInterlock:
2572 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2573 noReturnValue = true;
2574 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002575#endif
Chao Chen3c366992018-09-19 11:41:59 -07002576
John Kessenich140f3df2015-06-26 16:58:36 -06002577 default:
2578 break;
2579 }
2580
2581 //
2582 // See if it maps to a regular operation.
2583 //
John Kessenich140f3df2015-06-26 16:58:36 -06002584 if (binOp != glslang::EOpNull) {
2585 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2586 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2587 assert(left && right);
2588
2589 builder.clearAccessChain();
2590 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002591 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002592
2593 builder.clearAccessChain();
2594 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002595 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002596
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002597 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002598 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002599 TranslateNoContractionDecoration(node->getType().getQualifier()),
2600 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002601 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002602 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002603 left->getType().getBasicType(), reduceComparison);
2604
2605 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002606 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002607 builder.clearAccessChain();
2608 builder.setAccessChainRValue(result);
2609
2610 return false;
2611 }
2612
John Kessenich426394d2015-07-23 10:22:48 -06002613 //
2614 // Create the list of operands.
2615 //
John Kessenich140f3df2015-06-26 16:58:36 -06002616 glslang::TIntermSequence& glslangOperands = node->getSequence();
2617 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002618 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002619 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002620 // special case l-value operands; there are just a few
2621 bool lvalue = false;
2622 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002623 case glslang::EOpModf:
2624 if (arg == 1)
2625 lvalue = true;
2626 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002627#ifndef GLSLANG_WEB
2628 case glslang::EOpFrexp:
2629 if (arg == 1)
2630 lvalue = true;
2631 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002632 case glslang::EOpInterpolateAtSample:
2633 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002634 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002635 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002636 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002637
2638 // Does it need a swizzle inversion? If so, evaluation is inverted;
2639 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002640 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002641 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2642 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2643 }
Rex Xu7a26c172015-12-08 17:12:09 +08002644 break;
Rex Xud4782c12015-09-06 16:30:11 +08002645 case glslang::EOpAtomicAdd:
2646 case glslang::EOpAtomicMin:
2647 case glslang::EOpAtomicMax:
2648 case glslang::EOpAtomicAnd:
2649 case glslang::EOpAtomicOr:
2650 case glslang::EOpAtomicXor:
2651 case glslang::EOpAtomicExchange:
2652 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002653 case glslang::EOpAtomicLoad:
2654 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002655 case glslang::EOpAtomicCounterAdd:
2656 case glslang::EOpAtomicCounterSubtract:
2657 case glslang::EOpAtomicCounterMin:
2658 case glslang::EOpAtomicCounterMax:
2659 case glslang::EOpAtomicCounterAnd:
2660 case glslang::EOpAtomicCounterOr:
2661 case glslang::EOpAtomicCounterXor:
2662 case glslang::EOpAtomicCounterExchange:
2663 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002664 if (arg == 0)
2665 lvalue = true;
2666 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002667 case glslang::EOpAddCarry:
2668 case glslang::EOpSubBorrow:
2669 if (arg == 2)
2670 lvalue = true;
2671 break;
2672 case glslang::EOpUMulExtended:
2673 case glslang::EOpIMulExtended:
2674 if (arg >= 2)
2675 lvalue = true;
2676 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002677 case glslang::EOpCooperativeMatrixLoad:
2678 if (arg == 0 || arg == 1)
2679 lvalue = true;
2680 break;
2681 case glslang::EOpCooperativeMatrixStore:
2682 if (arg == 1)
2683 lvalue = true;
2684 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002685#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002686 default:
2687 break;
2688 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002689 builder.clearAccessChain();
2690 if (invertedType != spv::NoType && arg == 0)
2691 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2692 else
2693 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002694
2695 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2696 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2697
2698 if (arg == 1) {
2699 // fold "element" parameter into the access chain
2700 spv::Builder::AccessChain save = builder.getAccessChain();
2701 builder.clearAccessChain();
2702 glslangOperands[2]->traverse(this);
2703
2704 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2705
2706 builder.setAccessChain(save);
2707
2708 // Point to the first element of the array.
2709 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002710 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002711
2712 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2713 unsigned int alignment = builder.getAccessChain().alignment;
2714
2715 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2716 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2717 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2718 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2719 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2720 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2721 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2722 }
2723
2724 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2725
2726 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2727 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2728 }
2729
2730 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2731 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2732 }
2733 } else if (arg == 2) {
2734 continue;
2735 }
2736 }
2737
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002738 if (lvalue) {
John Kessenich140f3df2015-06-26 16:58:36 -06002739 operands.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002740 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2741 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2742 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002743 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002744 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002745 }
John Kessenich140f3df2015-06-26 16:58:36 -06002746 }
John Kessenich426394d2015-07-23 10:22:48 -06002747
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002748 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002749 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2750 std::vector<spv::IdImmediate> idImmOps;
2751
2752 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2753 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2754 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2755 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2756 // get the pointee type
2757 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2758 assert(builder.isCooperativeMatrixType(typeId));
2759 // do the op
2760 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2761 // store the result to the pointer (out param 'm')
2762 builder.createStore(result, operands[0]);
2763 result = 0;
2764 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2765 std::vector<spv::IdImmediate> idImmOps;
2766
2767 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2768 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2769 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2770 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2771 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2772
2773 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2774 result = 0;
2775 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002776 // Handle all atomics
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002777 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
John Kessenich426394d2015-07-23 10:22:48 -06002778 } else {
2779 // Pass through to generic operations.
2780 switch (glslangOperands.size()) {
2781 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002782 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002783 break;
2784 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002785 {
2786 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002787 TranslateNoContractionDecoration(node->getType().getQualifier()),
2788 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002789 result = createUnaryOperation(
2790 node->getOp(), decorations,
2791 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002792 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06002793 }
John Kessenich426394d2015-07-23 10:22:48 -06002794 break;
2795 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002796 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002797 break;
2798 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002799 if (invertedType)
2800 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002801 }
2802
2803 if (noReturnValue)
2804 return false;
2805
2806 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002807 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002808 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002809 } else {
2810 builder.clearAccessChain();
2811 builder.setAccessChainRValue(result);
2812 return false;
2813 }
2814}
2815
John Kessenich433e9ff2017-01-26 20:31:11 -07002816// This path handles both if-then-else and ?:
2817// The if-then-else has a node type of void, while
2818// ?: has either a void or a non-void node type
2819//
2820// Leaving the result, when not void:
2821// GLSL only has r-values as the result of a :?, but
2822// if we have an l-value, that can be more efficient if it will
2823// become the base of a complex r-value expression, because the
2824// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002825bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2826{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002827 // see if OpSelect can handle it
2828 const auto isOpSelectable = [&]() {
2829 if (node->getBasicType() == glslang::EbtVoid)
2830 return false;
2831 // OpSelect can do all other types starting with SPV 1.4
2832 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2833 // pre-1.4, only scalars and vectors can be handled
2834 if ((!node->getType().isScalar() && !node->getType().isVector()))
2835 return false;
2836 }
2837 return true;
2838 };
2839
John Kessenich4bee5312018-02-20 21:29:05 -07002840 // See if it simple and safe, or required, to execute both sides.
2841 // Crucially, side effects must be either semantically required or avoided,
2842 // and there are performance trade-offs.
2843 // Return true if required or a good idea (and safe) to execute both sides,
2844 // false otherwise.
2845 const auto bothSidesPolicy = [&]() -> bool {
2846 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002847 if (node->getTrueBlock() == nullptr ||
2848 node->getFalseBlock() == nullptr)
2849 return false;
2850
John Kessenich4bee5312018-02-20 21:29:05 -07002851 // required? (unless we write additional code to look for side effects
2852 // and make performance trade-offs if none are present)
2853 if (!node->getShortCircuit())
2854 return true;
2855
2856 // if not required to execute both, decide based on performance/practicality...
2857
John Kessenich0c1e71a2019-01-10 18:23:06 +07002858 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002859 return false;
2860
John Kessenich433e9ff2017-01-26 20:31:11 -07002861 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2862 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2863
2864 // return true if a single operand to ? : is okay for OpSelect
2865 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002866 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002867 };
2868
2869 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2870 operandOkay(node->getFalseBlock()->getAsTyped());
2871 };
2872
John Kessenich4bee5312018-02-20 21:29:05 -07002873 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2874 // emit the condition before doing anything with selection
2875 node->getCondition()->traverse(this);
2876 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2877
2878 // Find a way of executing both sides and selecting the right result.
2879 const auto executeBothSides = [&]() -> void {
2880 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002881 node->getTrueBlock()->traverse(this);
2882 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2883 node->getFalseBlock()->traverse(this);
2884 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2885
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002886 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002887
John Kessenich4bee5312018-02-20 21:29:05 -07002888 // done if void
2889 if (node->getBasicType() == glslang::EbtVoid)
2890 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002891
John Kessenich4bee5312018-02-20 21:29:05 -07002892 // emit code to select between trueValue and falseValue
2893
2894 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002895 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002896 // Emit OpSelect for this selection.
2897
2898 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002899 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2900 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002901 condition = builder.smearScalar(spv::NoPrecision, condition,
2902 builder.makeVectorType(builder.makeBoolType(),
2903 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002904 }
John Kessenich4bee5312018-02-20 21:29:05 -07002905
2906 // OpSelect
2907 result = builder.createTriOp(spv::OpSelect,
2908 convertGlslangToSpvType(node->getType()), condition,
2909 trueValue, falseValue);
2910
2911 builder.clearAccessChain();
2912 builder.setAccessChainRValue(result);
2913 } else {
2914 // We need control flow to select the result.
2915 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2916 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2917
2918 // Selection control:
2919 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2920
2921 // make an "if" based on the value created by the condition
2922 spv::Builder::If ifBuilder(condition, control, builder);
2923
2924 // emit the "then" statement
2925 builder.createStore(trueValue, result);
2926 ifBuilder.makeBeginElse();
2927 // emit the "else" statement
2928 builder.createStore(falseValue, result);
2929
2930 // finish off the control flow
2931 ifBuilder.makeEndIf();
2932
2933 builder.clearAccessChain();
2934 builder.setAccessChainLValue(result);
2935 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002936 };
2937
John Kessenich4bee5312018-02-20 21:29:05 -07002938 // Execute the one side needed, as per the condition
2939 const auto executeOneSide = [&]() {
2940 // Always emit control flow.
2941 if (node->getBasicType() != glslang::EbtVoid)
2942 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002943
John Kessenich4bee5312018-02-20 21:29:05 -07002944 // Selection control:
2945 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2946
2947 // make an "if" based on the value created by the condition
2948 spv::Builder::If ifBuilder(condition, control, builder);
2949
2950 // emit the "then" statement
2951 if (node->getTrueBlock() != nullptr) {
2952 node->getTrueBlock()->traverse(this);
2953 if (result != spv::NoResult)
2954 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2955 }
2956
2957 if (node->getFalseBlock() != nullptr) {
2958 ifBuilder.makeBeginElse();
2959 // emit the "else" statement
2960 node->getFalseBlock()->traverse(this);
2961 if (result != spv::NoResult)
2962 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2963 }
2964
2965 // finish off the control flow
2966 ifBuilder.makeEndIf();
2967
2968 if (result != spv::NoResult) {
2969 builder.clearAccessChain();
2970 builder.setAccessChainLValue(result);
2971 }
2972 };
2973
2974 // Try for OpSelect (or a requirement to execute both sides)
2975 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002976 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2977 if (node->getType().getQualifier().isSpecConstant())
2978 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002979 executeBothSides();
2980 } else
2981 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002982
2983 return false;
2984}
2985
2986bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2987{
2988 // emit and get the condition before doing anything with switch
2989 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002990 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002991
Rex Xu57e65922017-07-04 23:23:40 +08002992 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002993 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002994
John Kessenich140f3df2015-06-26 16:58:36 -06002995 // browse the children to sort out code segments
2996 int defaultSegment = -1;
2997 std::vector<TIntermNode*> codeSegments;
2998 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2999 std::vector<int> caseValues;
3000 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3001 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3002 TIntermNode* child = *c;
3003 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003004 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003005 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003006 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003007 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
3008 } else
3009 codeSegments.push_back(child);
3010 }
3011
qining25262b32016-05-06 17:25:16 -04003012 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003013 // statements between the last case and the end of the switch statement
3014 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3015 (int)codeSegments.size() == defaultSegment)
3016 codeSegments.push_back(nullptr);
3017
3018 // make the switch statement
3019 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08003020 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003021
3022 // emit all the code in the segments
3023 breakForLoop.push(false);
3024 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3025 builder.nextSwitchSegment(segmentBlocks, s);
3026 if (codeSegments[s])
3027 codeSegments[s]->traverse(this);
3028 else
3029 builder.addSwitchBreak();
3030 }
3031 breakForLoop.pop();
3032
3033 builder.endSwitch(segmentBlocks);
3034
3035 return false;
3036}
3037
3038void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3039{
3040 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003041 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003042
3043 builder.clearAccessChain();
3044 builder.setAccessChainRValue(constant);
3045}
3046
3047bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3048{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003049 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003050 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003051
3052 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003053 std::vector<unsigned int> operands;
3054 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003055
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003056 // Spec requires back edges to target header blocks, and every header block
3057 // must dominate its merge block. Make a header block first to ensure these
3058 // conditions are met. By definition, it will contain OpLoopMerge, followed
3059 // by a block-ending branch. But we don't want to put any other body/test
3060 // instructions in it, since the body/test may have arbitrary instructions,
3061 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003062 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003063 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003064 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003065 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003066 spv::Block& test = builder.makeNewBlock();
3067 builder.createBranch(&test);
3068
3069 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003070 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003071 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003072 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3073
3074 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003075 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003076 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003077 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003078 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003079 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003080
3081 builder.setBuildPoint(&blocks.continue_target);
3082 if (node->getTerminal())
3083 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003084 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003085 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003086 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003087 builder.createBranch(&blocks.body);
3088
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003089 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003090 builder.setBuildPoint(&blocks.body);
3091 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003092 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003093 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003094 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003095
3096 builder.setBuildPoint(&blocks.continue_target);
3097 if (node->getTerminal())
3098 node->getTerminal()->traverse(this);
3099 if (node->getTest()) {
3100 node->getTest()->traverse(this);
3101 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003102 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003103 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003104 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003105 // TODO: unless there was a break/return/discard instruction
3106 // somewhere in the body, this is an infinite loop, so we should
3107 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003108 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003109 }
John Kessenich140f3df2015-06-26 16:58:36 -06003110 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003111 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003112 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003113 return false;
3114}
3115
3116bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3117{
3118 if (node->getExpression())
3119 node->getExpression()->traverse(this);
3120
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003121 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003122
John Kessenich140f3df2015-06-26 16:58:36 -06003123 switch (node->getFlowOp()) {
3124 case glslang::EOpKill:
3125 builder.makeDiscard();
3126 break;
3127 case glslang::EOpBreak:
3128 if (breakForLoop.top())
3129 builder.createLoopExit();
3130 else
3131 builder.addSwitchBreak();
3132 break;
3133 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003134 builder.createLoopContinue();
3135 break;
3136 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003137 if (node->getExpression()) {
3138 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3139 spv::Id returnId = accessChainLoad(glslangReturnType);
3140 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3141 builder.clearAccessChain();
3142 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3143 builder.setAccessChainLValue(copyId);
3144 multiTypeStore(glslangReturnType, returnId);
3145 returnId = builder.createLoad(copyId);
3146 }
3147 builder.makeReturn(false, returnId);
3148 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003149 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003150
3151 builder.clearAccessChain();
3152 break;
3153
Jeff Bolzba6170b2019-07-01 09:23:23 -05003154 case glslang::EOpDemote:
3155 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3156 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3157 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3158 break;
3159
John Kessenich140f3df2015-06-26 16:58:36 -06003160 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003161 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003162 break;
3163 }
3164
3165 return false;
3166}
3167
John Kessenich9c14f772019-06-17 08:38:35 -06003168spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003169{
qining25262b32016-05-06 17:25:16 -04003170 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003171 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003172 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003173 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003174 spv::Id result = createSpvConstant(*node);
3175 if (result != spv::NoResult)
3176 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003177 }
3178
3179 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003180 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003181 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3182 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003183
Rex Xucabbb782017-03-24 13:41:14 +08003184 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
3185 node->getType().containsBasicType(glslang::EbtInt16) ||
3186 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08003187 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003188 switch (storageClass) {
3189 case spv::StorageClassInput:
3190 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07003191 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003192 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003193 break;
3194 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07003195 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003196 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06003197 break;
3198 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07003199 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003200 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3201 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003202 else
3203 builder.addCapability(spv::CapabilityStorageUniform16);
3204 break;
3205 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003206 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06003207 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
3208 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3209 break;
3210 default:
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003211 if (node->getType().containsBasicType(glslang::EbtFloat16))
3212 builder.addCapability(spv::CapabilityFloat16);
3213 if (node->getType().containsBasicType(glslang::EbtInt16) ||
3214 node->getType().containsBasicType(glslang::EbtUint16))
3215 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003216 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003217 }
3218 }
Rex Xuf89ad982017-04-07 23:22:33 +08003219
John Kessenich312dcfb2018-07-03 13:19:51 -06003220 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
3221 node->getType().containsBasicType(glslang::EbtUint8);
3222 if (contains8BitType) {
3223 if (storageClass == spv::StorageClassPushConstant) {
3224 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3225 builder.addCapability(spv::CapabilityStoragePushConstant8);
3226 } else if (storageClass == spv::StorageClassUniform) {
3227 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3228 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003229 } else if (storageClass == spv::StorageClassStorageBuffer) {
3230 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3231 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003232 } else {
3233 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003234 }
3235 }
3236
John Kessenich140f3df2015-06-26 16:58:36 -06003237 const char* name = node->getName().c_str();
3238 if (glslang::IsAnonymous(name))
3239 name = "";
3240
3241 return builder.createVariable(storageClass, spvType, name);
3242}
3243
3244// Return type Id of the sampled type.
3245spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3246{
3247 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003248 case glslang::EbtInt: return builder.makeIntType(32);
3249 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003250 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003251#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003252 case glslang::EbtFloat16:
3253 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3254 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3255 return builder.makeFloatType(16);
3256#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003257 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003258 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003259 return builder.makeFloatType(32);
3260 }
3261}
3262
John Kessenich8c8505c2016-07-26 12:50:38 -06003263// If node is a swizzle operation, return the type that should be used if
3264// the swizzle base is first consumed by another operation, before the swizzle
3265// is applied.
3266spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3267{
John Kessenichecba76f2017-01-06 00:34:48 -07003268 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003269 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3270 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3271 else
3272 return spv::NoType;
3273}
3274
3275// When inverting a swizzle with a parent op, this function
3276// will apply the swizzle operation to a completed parent operation.
3277spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3278{
3279 std::vector<unsigned> swizzle;
3280 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3281 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3282}
3283
John Kessenich8c8505c2016-07-26 12:50:38 -06003284// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3285void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3286{
3287 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3288 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3289 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3290}
3291
John Kessenich3ac051e2015-12-20 11:29:16 -07003292// Convert from a glslang type to an SPV type, by calling into a
3293// recursive version of this function. This establishes the inherited
3294// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003295spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003296{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003297 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003298}
3299
3300// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003301// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003302// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003303spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003304 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3305 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003306{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003307 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003308
3309 switch (type.getBasicType()) {
3310 case glslang::EbtVoid:
3311 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003312 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003313 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003314 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003315 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3316 // a 32-bit int where non-0 means true.
3317 if (explicitLayout != glslang::ElpNone)
3318 spvType = builder.makeUintType(32);
3319 else
3320 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003321 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003322 case glslang::EbtInt:
3323 spvType = builder.makeIntType(32);
3324 break;
3325 case glslang::EbtUint:
3326 spvType = builder.makeUintType(32);
3327 break;
3328 case glslang::EbtFloat:
3329 spvType = builder.makeFloatType(32);
3330 break;
3331#ifndef GLSLANG_WEB
3332 case glslang::EbtDouble:
3333 spvType = builder.makeFloatType(64);
3334 break;
3335 case glslang::EbtFloat16:
3336 spvType = builder.makeFloatType(16);
3337 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003338 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003339 spvType = builder.makeIntType(8);
3340 break;
3341 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003342 spvType = builder.makeUintType(8);
3343 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003344 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003345 spvType = builder.makeIntType(16);
3346 break;
3347 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003348 spvType = builder.makeUintType(16);
3349 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003350 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003351 spvType = builder.makeIntType(64);
3352 break;
3353 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003354 spvType = builder.makeUintType(64);
3355 break;
John Kessenich426394d2015-07-23 10:22:48 -06003356 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003357 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003358 spvType = builder.makeUintType(32);
3359 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003360 case glslang::EbtAccStructNV:
3361 spvType = builder.makeAccelerationStructureNVType();
3362 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003363 case glslang::EbtReference:
3364 {
3365 // Make the forward pointer, then recurse to convert the structure type, then
3366 // patch up the forward pointer with a real pointer type.
3367 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3368 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3369 forwardPointers[type.getReferentType()] = forwardId;
3370 }
3371 spvType = forwardPointers[type.getReferentType()];
3372 if (!forwardReferenceOnly) {
3373 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3374 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3375 forwardPointers[type.getReferentType()],
3376 referentType);
3377 }
3378 }
3379 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003380#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003381 case glslang::EbtSampler:
3382 {
3383 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003384 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003385 spvType = builder.makeSamplerType();
3386 } else {
3387 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003388 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3389 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3390 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3391 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003392 // already has both image and sampler, make the combined type
3393 spvType = builder.makeSampledImageType(spvType);
3394 }
John Kessenich55e7d112015-11-15 21:33:39 -07003395 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003396 }
John Kessenich140f3df2015-06-26 16:58:36 -06003397 break;
3398 case glslang::EbtStruct:
3399 case glslang::EbtBlock:
3400 {
3401 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003402 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003403
3404 // Try to share structs for different layouts, but not yet for other
3405 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003406 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003407 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003408 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003409 break;
3410
3411 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003412 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003413 memberRemapper[glslangMembers].resize(glslangMembers->size());
3414 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003415 }
3416 break;
3417 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003418 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003419 break;
3420 }
3421
3422 if (type.isMatrix())
3423 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3424 else {
3425 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3426 if (type.getVectorSize() > 1)
3427 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3428 }
3429
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003430 if (type.isCoopMat()) {
3431 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3432 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3433 if (type.getBasicType() == glslang::EbtFloat16)
3434 builder.addCapability(spv::CapabilityFloat16);
3435
3436 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3437 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3438 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3439
3440 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3441 }
3442
John Kessenich140f3df2015-06-26 16:58:36 -06003443 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003444 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3445
John Kessenichc9a80832015-09-12 12:17:44 -06003446 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003447 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003448 // We need to decorate array strides for types needing explicit layout, except blocks.
3449 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003450 // Use a dummy glslang type for querying internal strides of
3451 // arrays of arrays, but using just a one-dimensional array.
3452 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003453 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3454 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003455
3456 // Will compute the higher-order strides here, rather than making a whole
3457 // pile of types and doing repetitive recursion on their contents.
3458 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3459 }
John Kessenichf8842e52016-01-04 19:22:56 -07003460
3461 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003462 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003463 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003464 if (stride > 0)
3465 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003466 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003467 }
3468 } else {
3469 // single-dimensional array, and don't yet have stride
3470
John Kessenichf8842e52016-01-04 19:22:56 -07003471 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003472 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3473 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003474 }
John Kessenich31ed4832015-09-09 17:51:38 -06003475
John Kessenichead86222018-03-28 18:01:20 -06003476 // Do the outer dimension, which might not be known for a runtime-sized array.
3477 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3478 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003479 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003480 else {
3481 if (!lastBufferBlockMember) {
3482 builder.addExtension("SPV_EXT_descriptor_indexing");
3483 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3484 }
John Kessenichead86222018-03-28 18:01:20 -06003485 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003486 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003487 if (stride > 0)
3488 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003489 }
3490
3491 return spvType;
3492}
3493
John Kessenich0e737842017-03-24 18:38:16 -06003494// TODO: this functionality should exist at a higher level, in creating the AST
3495//
3496// Identify interface members that don't have their required extension turned on.
3497//
3498bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3499{
John Kessenicha28f7a72019-08-06 07:00:58 -06003500#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003501 auto& extensions = glslangIntermediate->getRequestedExtensions();
3502
Rex Xubcf291a2017-03-29 23:01:36 +08003503 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3504 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3505 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003506 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3507 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3508 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003509
3510 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3511 if (member.getFieldName() == "gl_ViewportMask" &&
3512 extensions.find("GL_NV_viewport_array2") == extensions.end())
3513 return true;
3514 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3515 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3516 return true;
3517 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3518 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3519 return true;
3520 }
3521#endif
John Kessenich0e737842017-03-24 18:38:16 -06003522
3523 return false;
3524};
3525
John Kessenich6090df02016-06-30 21:18:02 -06003526// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3527// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3528// Mutually recursive with convertGlslangToSpvType().
3529spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3530 const glslang::TTypeList* glslangMembers,
3531 glslang::TLayoutPacking explicitLayout,
3532 const glslang::TQualifier& qualifier)
3533{
3534 // Create a vector of struct types for SPIR-V to consume
3535 std::vector<spv::Id> spvMembers;
3536 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 -06003537 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003538 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3539 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3540 if (glslangMember.hiddenMember()) {
3541 ++memberDelta;
3542 if (type.getBasicType() == glslang::EbtBlock)
3543 memberRemapper[glslangMembers][i] = -1;
3544 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003545 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003546 if (filterMember(glslangMember)) {
3547 memberDelta++;
3548 memberRemapper[glslangMembers][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003549 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003550 }
3551 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003552 }
John Kessenich6090df02016-06-30 21:18:02 -06003553 // modify just this child's view of the qualifier
3554 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3555 InheritQualifiers(memberQualifier, qualifier);
3556
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003557 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003558 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003559 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003560
3561 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003562 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3563 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003564
3565 // Make forward pointers for any pointer members, and create a list of members to
3566 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003567 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003568 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3569 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3570 }
3571 spvMembers.push_back(
3572 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3573 } else {
3574 spvMembers.push_back(
3575 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3576 }
John Kessenich6090df02016-06-30 21:18:02 -06003577 }
3578 }
3579
3580 // Make the SPIR-V type
3581 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003582 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003583 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3584
3585 // Decorate it
3586 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3587
John Kessenichd72f4882019-01-16 14:55:37 +07003588 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003589 auto it = deferredForwardPointers[i];
3590 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3591 }
3592
John Kessenich6090df02016-06-30 21:18:02 -06003593 return spvType;
3594}
3595
3596void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3597 const glslang::TTypeList* glslangMembers,
3598 glslang::TLayoutPacking explicitLayout,
3599 const glslang::TQualifier& qualifier,
3600 spv::Id spvType)
3601{
3602 // Name and decorate the non-hidden members
3603 int offset = -1;
3604 int locationOffset = 0; // for use within the members of this struct
3605 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3606 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3607 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003608 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003609 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003610 if (filterMember(glslangMember))
3611 continue;
3612 }
John Kessenich6090df02016-06-30 21:18:02 -06003613
3614 // modify just this child's view of the qualifier
3615 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3616 InheritQualifiers(memberQualifier, qualifier);
3617
3618 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003619 if (member < 0)
3620 continue;
3621
3622 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3623 builder.addMemberDecoration(spvType, member,
3624 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3625 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3626 // Add interpolation and auxiliary storage decorations only to
3627 // top-level members of Input and Output storage classes
3628 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3629 type.getQualifier().storage == glslang::EvqVaryingOut) {
3630 if (type.getBasicType() == glslang::EbtBlock ||
3631 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3632 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3633 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003634#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003635 addMeshNVDecoration(spvType, member, memberQualifier);
3636#endif
John Kessenich6090df02016-06-30 21:18:02 -06003637 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003638 }
3639 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003640
John Kessenich5d610ee2018-03-07 18:05:55 -07003641 if (type.getBasicType() == glslang::EbtBlock &&
3642 qualifier.storage == glslang::EvqBuffer) {
3643 // Add memory decorations only to top-level members of shader storage block
3644 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003645 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003646 for (unsigned int i = 0; i < memory.size(); ++i)
3647 builder.addMemberDecoration(spvType, member, memory[i]);
3648 }
John Kessenich6090df02016-06-30 21:18:02 -06003649
John Kessenich5d610ee2018-03-07 18:05:55 -07003650 // Location assignment was already completed correctly by the front end,
3651 // just track whether a member needs to be decorated.
3652 // Ignore member locations if the container is an array, as that's
3653 // ill-specified and decisions have been made to not allow this.
3654 if (! type.isArray() && memberQualifier.hasLocation())
3655 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003656
John Kessenich5d610ee2018-03-07 18:05:55 -07003657 if (qualifier.hasLocation()) // track for upcoming inheritance
3658 locationOffset += glslangIntermediate->computeTypeLocationSize(
3659 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003660
John Kessenich5d610ee2018-03-07 18:05:55 -07003661 // component, XFB, others
3662 if (glslangMember.getQualifier().hasComponent())
3663 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3664 glslangMember.getQualifier().layoutComponent);
3665 if (glslangMember.getQualifier().hasXfbOffset())
3666 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3667 glslangMember.getQualifier().layoutXfbOffset);
3668 else if (explicitLayout != glslang::ElpNone) {
3669 // figure out what to do with offset, which is accumulating
3670 int nextOffset;
3671 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3672 if (offset >= 0)
3673 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3674 offset = nextOffset;
3675 }
John Kessenich6090df02016-06-30 21:18:02 -06003676
John Kessenich5d610ee2018-03-07 18:05:55 -07003677 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3678 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3679 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003680
John Kessenich5d610ee2018-03-07 18:05:55 -07003681 // built-in variable decorations
3682 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3683 if (builtIn != spv::BuiltInMax)
3684 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003685
John Kessenich5611c6d2018-04-05 11:25:02 -06003686 // nonuniform
3687 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3688
John Kessenichead86222018-03-28 18:01:20 -06003689 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3690 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3691 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3692 memberQualifier.semanticName);
3693 }
3694
John Kessenicha28f7a72019-08-06 07:00:58 -06003695#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003696 if (builtIn == spv::BuiltInLayer) {
3697 // SPV_NV_viewport_array2 extension
3698 if (glslangMember.getQualifier().layoutViewportRelative){
3699 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3700 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3701 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003702 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003703 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3704 builder.addMemberDecoration(spvType, member,
3705 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3706 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3707 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3708 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003709 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003710 }
3711 if (glslangMember.getQualifier().layoutPassthrough) {
3712 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3713 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3714 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3715 }
chaoc771d89f2017-01-13 01:10:53 -08003716#endif
John Kessenich6090df02016-06-30 21:18:02 -06003717 }
3718
3719 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003720 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3721 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003722}
3723
John Kessenich6c292d32016-02-15 20:58:50 -07003724// Turn the expression forming the array size into an id.
3725// This is not quite trivial, because of specialization constants.
3726// Sometimes, a raw constant is turned into an Id, and sometimes
3727// a specialization constant expression is.
3728spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3729{
3730 // First, see if this is sized with a node, meaning a specialization constant:
3731 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3732 if (specNode != nullptr) {
3733 builder.clearAccessChain();
3734 specNode->traverse(this);
3735 return accessChainLoad(specNode->getAsTyped()->getType());
3736 }
qining25262b32016-05-06 17:25:16 -04003737
John Kessenich6c292d32016-02-15 20:58:50 -07003738 // Otherwise, need a compile-time (front end) size, get it:
3739 int size = arraySizes.getDimSize(dim);
3740 assert(size > 0);
3741 return builder.makeUintConstant(size);
3742}
3743
John Kessenich103bef92016-02-08 21:38:15 -07003744// Wrap the builder's accessChainLoad to:
3745// - localize handling of RelaxedPrecision
3746// - use the SPIR-V inferred type instead of another conversion of the glslang type
3747// (avoids unnecessary work and possible type punning for structures)
3748// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003749spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3750{
John Kessenich103bef92016-02-08 21:38:15 -07003751 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003752
3753 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3754 coherentFlags |= TranslateCoherent(type);
3755
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003756 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003757 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003758
John Kessenich5611c6d2018-04-05 11:25:02 -06003759 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003760 TranslateNonUniformDecoration(type.getQualifier()),
3761 nominalTypeId,
3762 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003763 TranslateMemoryScope(coherentFlags),
3764 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003765
3766 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003767 if (type.getBasicType() == glslang::EbtBool) {
3768 if (builder.isScalarType(nominalTypeId)) {
3769 // Conversion for bool
3770 spv::Id boolType = builder.makeBoolType();
3771 if (nominalTypeId != boolType)
3772 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3773 } else if (builder.isVectorType(nominalTypeId)) {
3774 // Conversion for bvec
3775 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3776 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3777 if (nominalTypeId != bvecType)
3778 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3779 }
3780 }
John Kessenich103bef92016-02-08 21:38:15 -07003781
3782 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003783}
3784
Rex Xu27253232016-02-23 17:51:09 +08003785// Wrap the builder's accessChainStore to:
3786// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003787//
3788// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003789void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3790{
3791 // Need to convert to abstract types when necessary
3792 if (type.getBasicType() == glslang::EbtBool) {
3793 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3794
3795 if (builder.isScalarType(nominalTypeId)) {
3796 // Conversion for bool
3797 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003798 if (nominalTypeId != boolType) {
3799 // keep these outside arguments, for determinant order-of-evaluation
3800 spv::Id one = builder.makeUintConstant(1);
3801 spv::Id zero = builder.makeUintConstant(0);
3802 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3803 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003804 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003805 } else if (builder.isVectorType(nominalTypeId)) {
3806 // Conversion for bvec
3807 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3808 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003809 if (nominalTypeId != bvecType) {
3810 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003811 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3812 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3813 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003814 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003815 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3816 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003817 }
3818 }
3819
Jeff Bolz36831c92018-09-05 10:11:41 -05003820 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3821 coherentFlags |= TranslateCoherent(type);
3822
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003823 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003824 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003825
Jeff Bolz36831c92018-09-05 10:11:41 -05003826 builder.accessChainStore(rvalue,
3827 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003828 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003829}
3830
John Kessenich4bf71552016-09-02 11:20:21 -06003831// For storing when types match at the glslang level, but not might match at the
3832// SPIR-V level.
3833//
3834// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003835// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003836// as in a member-decorated way.
3837//
3838// NOTE: This function can handle any store request; if it's not special it
3839// simplifies to a simple OpStore.
3840//
3841// Implicitly uses the existing builder.accessChain as the storage target.
3842void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3843{
John Kessenichb3e24e42016-09-11 12:33:43 -06003844 // we only do the complex path here if it's an aggregate
3845 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003846 accessChainStore(type, rValue);
3847 return;
3848 }
3849
John Kessenichb3e24e42016-09-11 12:33:43 -06003850 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003851 spv::Id rType = builder.getTypeId(rValue);
3852 spv::Id lValue = builder.accessChainGetLValue();
3853 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3854 if (lType == rType) {
3855 accessChainStore(type, rValue);
3856 return;
3857 }
3858
John Kessenichb3e24e42016-09-11 12:33:43 -06003859 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003860 // where the two types were the same type in GLSL. This requires member
3861 // by member copy, recursively.
3862
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003863 // SPIR-V 1.4 added an instruction to do help do this.
3864 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3865 // However, bool in uniform space is changed to int, so
3866 // OpCopyLogical does not work for that.
3867 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3868 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3869 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3870 if (lBool == rBool) {
3871 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3872 accessChainStore(type, logicalCopy);
3873 return;
3874 }
3875 }
3876
John Kessenichb3e24e42016-09-11 12:33:43 -06003877 // If an array, copy element by element.
3878 if (type.isArray()) {
3879 glslang::TType glslangElementType(type, 0);
3880 spv::Id elementRType = builder.getContainedTypeId(rType);
3881 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3882 // get the source member
3883 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003884
John Kessenichb3e24e42016-09-11 12:33:43 -06003885 // set up the target storage
3886 builder.clearAccessChain();
3887 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003888 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003889
John Kessenichb3e24e42016-09-11 12:33:43 -06003890 // store the member
3891 multiTypeStore(glslangElementType, elementRValue);
3892 }
3893 } else {
3894 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003895
John Kessenichb3e24e42016-09-11 12:33:43 -06003896 // loop over structure members
3897 const glslang::TTypeList& members = *type.getStruct();
3898 for (int m = 0; m < (int)members.size(); ++m) {
3899 const glslang::TType& glslangMemberType = *members[m].type;
3900
3901 // get the source member
3902 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3903 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3904
3905 // set up the target storage
3906 builder.clearAccessChain();
3907 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003908 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003909
3910 // store the member
3911 multiTypeStore(glslangMemberType, memberRValue);
3912 }
John Kessenich4bf71552016-09-02 11:20:21 -06003913 }
3914}
3915
John Kessenichf85e8062015-12-19 13:57:10 -07003916// Decide whether or not this type should be
3917// decorated with offsets and strides, and if so
3918// whether std140 or std430 rules should be applied.
3919glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003920{
John Kessenichf85e8062015-12-19 13:57:10 -07003921 // has to be a block
3922 if (type.getBasicType() != glslang::EbtBlock)
3923 return glslang::ElpNone;
3924
Chao Chen3c366992018-09-19 11:41:59 -07003925 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003926 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003927 type.getQualifier().storage != glslang::EvqBuffer &&
3928 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003929 return glslang::ElpNone;
3930
3931 // return the layout to use
3932 switch (type.getQualifier().layoutPacking) {
3933 case glslang::ElpStd140:
3934 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003935 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003936 return type.getQualifier().layoutPacking;
3937 default:
3938 return glslang::ElpNone;
3939 }
John Kessenich31ed4832015-09-09 17:51:38 -06003940}
3941
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003942// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003943int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003944{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003945 int size;
John Kessenich49987892015-12-29 17:11:44 -07003946 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003947 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003948
3949 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003950}
3951
John Kessenich49987892015-12-29 17:11:44 -07003952// 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 -07003953// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003954int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003955{
John Kessenich49987892015-12-29 17:11:44 -07003956 glslang::TType elementType;
3957 elementType.shallowCopy(matrixType);
3958 elementType.clearArraySizes();
3959
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003960 int size;
John Kessenich49987892015-12-29 17:11:44 -07003961 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003962 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003963
3964 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003965}
3966
John Kessenich5e4b1242015-08-06 22:53:06 -06003967// Given a member type of a struct, realign the current offset for it, and compute
3968// the next (not yet aligned) offset for the next member, which will get aligned
3969// on the next call.
3970// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3971// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3972// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003973void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003974 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003975{
3976 // this will get a positive value when deemed necessary
3977 nextOffset = -1;
3978
John Kessenich5e4b1242015-08-06 22:53:06 -06003979 // override anything in currentOffset with user-set offset
3980 if (memberType.getQualifier().hasOffset())
3981 currentOffset = memberType.getQualifier().layoutOffset;
3982
3983 // It could be that current linker usage in glslang updated all the layoutOffset,
3984 // in which case the following code does not matter. But, that's not quite right
3985 // once cross-compilation unit GLSL validation is done, as the original user
3986 // settings are needed in layoutOffset, and then the following will come into play.
3987
John Kessenichf85e8062015-12-19 13:57:10 -07003988 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003989 if (! memberType.getQualifier().hasOffset())
3990 currentOffset = -1;
3991
3992 return;
3993 }
3994
John Kessenichf85e8062015-12-19 13:57:10 -07003995 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003996 if (currentOffset < 0)
3997 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003998
John Kessenich5e4b1242015-08-06 22:53:06 -06003999 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4000 // but possibly not yet correctly aligned.
4001
4002 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004003 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004004 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004005
4006 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004007 // TODO: make this consistent in early phases of code:
4008 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4009 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4010 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004011 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004012 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004013 int dummySize;
4014 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4015 if (componentAlignment <= 4)
4016 memberAlignment = componentAlignment;
4017 }
4018
4019 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004020 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004021
4022 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004023 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004024 glslang::RoundToPow2(currentOffset, 16);
4025
John Kessenich5e4b1242015-08-06 22:53:06 -06004026 nextOffset = currentOffset + memberSize;
4027}
4028
David Netoa901ffe2016-06-08 14:11:40 +01004029void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004030{
David Netoa901ffe2016-06-08 14:11:40 +01004031 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4032 switch (glslangBuiltIn)
4033 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004034 case glslang::EbvPointSize:
4035#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004036 case glslang::EbvClipDistance:
4037 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004038 case glslang::EbvViewportMaskNV:
4039 case glslang::EbvSecondaryPositionNV:
4040 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004041 case glslang::EbvPositionPerViewNV:
4042 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004043 case glslang::EbvTaskCountNV:
4044 case glslang::EbvPrimitiveCountNV:
4045 case glslang::EbvPrimitiveIndicesNV:
4046 case glslang::EbvClipDistancePerViewNV:
4047 case glslang::EbvCullDistancePerViewNV:
4048 case glslang::EbvLayerPerViewNV:
4049 case glslang::EbvMeshViewCountNV:
4050 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004051#endif
David Netoa901ffe2016-06-08 14:11:40 +01004052 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4053 // Alternately, we could just call this for any glslang built-in, since the
4054 // capability already guards against duplicates.
4055 TranslateBuiltInDecoration(glslangBuiltIn, false);
4056 break;
4057 default:
4058 // Capabilities were already generated when the struct was declared.
4059 break;
4060 }
John Kessenichebb50532016-05-16 19:22:05 -06004061}
4062
John Kessenich6fccb3c2016-09-19 16:01:41 -06004063bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004064{
John Kessenicheee9d532016-09-19 18:09:30 -06004065 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004066}
4067
John Kessenichd41993d2017-09-10 15:21:05 -06004068// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004069// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4070// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004071bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004072{
John Kessenich6a14f782017-12-04 02:48:10 -07004073 assert(qualifier == glslang::EvqIn ||
4074 qualifier == glslang::EvqOut ||
4075 qualifier == glslang::EvqInOut ||
4076 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004077 return qualifier != glslang::EvqConstReadOnly;
4078}
4079
4080// Is parameter pass-by-original?
4081bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4082 bool implicitThisParam)
4083{
4084 if (implicitThisParam) // implicit this
4085 return true;
4086 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004087 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004088 return paramType.containsOpaque() || // sampler, etc.
4089 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4090}
4091
John Kessenich140f3df2015-06-26 16:58:36 -06004092// Make all the functions, skeletally, without actually visiting their bodies.
4093void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4094{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004095 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004096 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4097 if (paramPrecision != spv::NoPrecision)
4098 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004099 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004100 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004101 // Original and non-writable params pass the pointer directly and
4102 // use restrict/aliased, others are stored to a pointer in Function
4103 // memory and use RestrictPointer/AliasedPointer.
4104 if (originalParam(type.getQualifier().storage, type, false) ||
4105 !writableParam(type.getQualifier().storage)) {
4106 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
4107 } else {
4108 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
4109 }
4110 }
John Kessenichfad62972017-07-18 02:35:46 -06004111 };
4112
John Kessenich140f3df2015-06-26 16:58:36 -06004113 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4114 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004115 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004116 continue;
4117
4118 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004119 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004120 //
qining25262b32016-05-06 17:25:16 -04004121 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004122 // function. What it is an address of varies:
4123 //
John Kessenich4bf71552016-09-02 11:20:21 -06004124 // - "in" parameters not marked as "const" can be written to without modifying the calling
4125 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004126 //
4127 // - "const in" parameters can just be the r-value, as no writes need occur.
4128 //
John Kessenich4bf71552016-09-02 11:20:21 -06004129 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4130 // 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 -06004131
4132 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004133 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004134 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4135
John Kessenich155d3512019-08-08 23:29:20 -06004136#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004137 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4138 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004139#else
4140 bool implicitThis = false;
4141#endif
John Kessenich37789792017-03-21 23:56:40 -06004142
John Kessenichfad62972017-07-18 02:35:46 -06004143 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004144 for (int p = 0; p < (int)parameters.size(); ++p) {
4145 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4146 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004147 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004148 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004149 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004150 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4151 else
John Kessenich4bf71552016-09-02 11:20:21 -06004152 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004153 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004154 paramTypes.push_back(typeId);
4155 }
4156
4157 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004158 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4159 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004160 glslFunction->getName().c_str(), paramTypes,
4161 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004162 if (implicitThis)
4163 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004164
4165 // Track function to emit/call later
4166 functionMap[glslFunction->getName().c_str()] = function;
4167
4168 // Set the parameter id's
4169 for (int p = 0; p < (int)parameters.size(); ++p) {
4170 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4171 // give a name too
4172 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004173
4174 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4175 if (paramType.containsBasicType(glslang::EbtInt8) ||
4176 paramType.containsBasicType(glslang::EbtUint8))
4177 builder.addCapability(spv::CapabilityInt8);
4178 if (paramType.containsBasicType(glslang::EbtInt16) ||
4179 paramType.containsBasicType(glslang::EbtUint16))
4180 builder.addCapability(spv::CapabilityInt16);
4181 if (paramType.containsBasicType(glslang::EbtFloat16))
4182 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004183 }
4184 }
4185}
4186
4187// Process all the initializers, while skipping the functions and link objects
4188void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4189{
4190 builder.setBuildPoint(shaderEntry->getLastBlock());
4191 for (int i = 0; i < (int)initializers.size(); ++i) {
4192 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
4193 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
4194
4195 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004196 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004197 initializer->traverse(this);
4198 }
4199 }
4200}
4201
4202// Process all the functions, while skipping initializers.
4203void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4204{
4205 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4206 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004207 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004208 node->traverse(this);
4209 }
4210}
4211
4212void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4213{
qining25262b32016-05-06 17:25:16 -04004214 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004215 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004216 currentFunction = functionMap[node->getName().c_str()];
4217 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004218 builder.setBuildPoint(functionBlock);
4219}
4220
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004221void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004222{
Rex Xufc618912015-09-09 16:42:49 +08004223 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004224
4225 glslang::TSampler sampler = {};
4226 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004227#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004228 bool f16ShadowCompare = false;
4229#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004230 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004231 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4232 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004233#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004234 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4235#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004236 }
4237
John Kessenich140f3df2015-06-26 16:58:36 -06004238 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4239 builder.clearAccessChain();
4240 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004241
John Kessenicha28f7a72019-08-06 07:00:58 -06004242#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004243 // Special case l-value operands
4244 bool lvalue = false;
4245 switch (node.getOp()) {
4246 case glslang::EOpImageAtomicAdd:
4247 case glslang::EOpImageAtomicMin:
4248 case glslang::EOpImageAtomicMax:
4249 case glslang::EOpImageAtomicAnd:
4250 case glslang::EOpImageAtomicOr:
4251 case glslang::EOpImageAtomicXor:
4252 case glslang::EOpImageAtomicExchange:
4253 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004254 case glslang::EOpImageAtomicLoad:
4255 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004256 if (i == 0)
4257 lvalue = true;
4258 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004259 case glslang::EOpSparseImageLoad:
4260 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4261 lvalue = true;
4262 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004263 case glslang::EOpSparseTexture:
4264 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4265 lvalue = true;
4266 break;
4267 case glslang::EOpSparseTextureClamp:
4268 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4269 lvalue = true;
4270 break;
4271 case glslang::EOpSparseTextureLod:
4272 case glslang::EOpSparseTextureOffset:
4273 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4274 lvalue = true;
4275 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004276 case glslang::EOpSparseTextureFetch:
4277 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4278 lvalue = true;
4279 break;
4280 case glslang::EOpSparseTextureFetchOffset:
4281 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4282 lvalue = true;
4283 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004284 case glslang::EOpSparseTextureLodOffset:
4285 case glslang::EOpSparseTextureGrad:
4286 case glslang::EOpSparseTextureOffsetClamp:
4287 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4288 lvalue = true;
4289 break;
4290 case glslang::EOpSparseTextureGradOffset:
4291 case glslang::EOpSparseTextureGradClamp:
4292 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4293 lvalue = true;
4294 break;
4295 case glslang::EOpSparseTextureGradOffsetClamp:
4296 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4297 lvalue = true;
4298 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004299 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004300 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4301 lvalue = true;
4302 break;
4303 case glslang::EOpSparseTextureGatherOffset:
4304 case glslang::EOpSparseTextureGatherOffsets:
4305 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4306 lvalue = true;
4307 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004308 case glslang::EOpSparseTextureGatherLod:
4309 if (i == 3)
4310 lvalue = true;
4311 break;
4312 case glslang::EOpSparseTextureGatherLodOffset:
4313 case glslang::EOpSparseTextureGatherLodOffsets:
4314 if (i == 4)
4315 lvalue = true;
4316 break;
Rex Xu129799a2017-07-05 17:23:28 +08004317 case glslang::EOpSparseImageLoadLod:
4318 if (i == 3)
4319 lvalue = true;
4320 break;
Chao Chen3a137962018-09-19 11:41:27 -07004321 case glslang::EOpImageSampleFootprintNV:
4322 if (i == 4)
4323 lvalue = true;
4324 break;
4325 case glslang::EOpImageSampleFootprintClampNV:
4326 case glslang::EOpImageSampleFootprintLodNV:
4327 if (i == 5)
4328 lvalue = true;
4329 break;
4330 case glslang::EOpImageSampleFootprintGradNV:
4331 if (i == 6)
4332 lvalue = true;
4333 break;
4334 case glslang::EOpImageSampleFootprintGradClampNV:
4335 if (i == 7)
4336 lvalue = true;
4337 break;
Rex Xufc618912015-09-09 16:42:49 +08004338 default:
4339 break;
4340 }
4341
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004342 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004343 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004344 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4345 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4346 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004347#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004348 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004349 }
4350}
4351
John Kessenichfc51d282015-08-19 13:34:18 -06004352void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004353{
John Kessenichfc51d282015-08-19 13:34:18 -06004354 builder.clearAccessChain();
4355 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004356 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004357}
John Kessenich140f3df2015-06-26 16:58:36 -06004358
John Kessenichfc51d282015-08-19 13:34:18 -06004359spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4360{
John Kesseniche485c7a2017-05-31 18:50:53 -06004361 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004362 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004363
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004364 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004365
John Kessenichfc51d282015-08-19 13:34:18 -06004366 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004367
John Kessenichf43c7392019-03-31 10:51:57 -06004368 const glslang::TType &imageType = node->getAsAggregate()
4369 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4370 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004371 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004372#ifdef GLSLANG_WEB
4373 const bool f16ShadowCompare = false;
4374#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004375 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004376 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4377 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004378#endif
4379
John Kessenichf43c7392019-03-31 10:51:57 -06004380 const auto signExtensionMask = [&]() {
4381 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4382 if (sampler.type == glslang::EbtUint)
4383 return spv::ImageOperandsZeroExtendMask;
4384 else if (sampler.type == glslang::EbtInt)
4385 return spv::ImageOperandsSignExtendMask;
4386 }
4387 return spv::ImageOperandsMaskNone;
4388 };
4389
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004390 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4391
John Kessenichfc51d282015-08-19 13:34:18 -06004392 std::vector<spv::Id> arguments;
4393 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004394 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004395 else
4396 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004397 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004398
4399 spv::Builder::TextureParameters params = { };
4400 params.sampler = arguments[0];
4401
Rex Xu04db3f52015-09-16 11:44:02 +08004402 glslang::TCrackedTextureOp cracked;
4403 node->crackTexture(sampler, cracked);
4404
amhagan05506bb2017-06-13 16:53:02 -04004405 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004406
John Kessenichfc51d282015-08-19 13:34:18 -06004407 // Check for queries
4408 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004409 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4410 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004411 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004412
John Kessenichfc51d282015-08-19 13:34:18 -06004413 switch (node->getOp()) {
4414 case glslang::EOpImageQuerySize:
4415 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004416 if (arguments.size() > 1) {
4417 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004418 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004419 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004420 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004421#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004422 case glslang::EOpImageQuerySamples:
4423 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004424 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004425 case glslang::EOpTextureQueryLod:
4426 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004427 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004428 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004429 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004430 case glslang::EOpSparseTexelsResident:
4431 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004432#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004433 default:
4434 assert(0);
4435 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004436 }
John Kessenich140f3df2015-06-26 16:58:36 -06004437 }
4438
LoopDawg4425f242018-02-18 11:40:01 -07004439 int components = node->getType().getVectorSize();
4440
4441 if (node->getOp() == glslang::EOpTextureFetch) {
4442 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4443 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4444 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4445 // here around e.g. which ones return scalars or other types.
4446 components = 4;
4447 }
4448
4449 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4450
4451 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4452
Rex Xufc618912015-09-09 16:42:49 +08004453 // Check for image functions other than queries
4454 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004455 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004456 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004457 spv::IdImmediate image = { true, *(opIt++) };
4458 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004459
4460 // Handle subpass operations
4461 // TODO: GLSL should change to have the "MS" only on the type rather than the
4462 // built-in function.
4463 if (cracked.subpass) {
4464 // add on the (0,0) coordinate
4465 spv::Id zero = builder.makeIntConstant(0);
4466 std::vector<spv::Id> comps;
4467 comps.push_back(zero);
4468 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004469 spv::IdImmediate coord = { true,
4470 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4471 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004472 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4473 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004474 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004475 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4476 }
4477 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004478 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004479 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004480 spv::IdImmediate imageOperand = { true, *(opIt++) };
4481 operands.push_back(imageOperand);
4482 }
John Kessenich6c292d32016-02-15 20:58:50 -07004483 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004484 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4485 builder.setPrecision(result, precision);
4486 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004487 }
4488
John Kessenich149afc32018-08-14 13:31:43 -06004489 spv::IdImmediate coord = { true, *(opIt++) };
4490 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004491 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004492 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004493 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004494 mask = mask | spv::ImageOperandsSampleMask;
4495 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004496 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004497 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4498 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004499 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004500 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004501 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4502 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004503 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004504 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004505 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4506 operands.push_back(imageOperands);
4507 }
4508 if (mask & spv::ImageOperandsSampleMask) {
4509 spv::IdImmediate imageOperand = { true, *opIt++ };
4510 operands.push_back(imageOperand);
4511 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004512 if (mask & spv::ImageOperandsLodMask) {
4513 spv::IdImmediate imageOperand = { true, *opIt++ };
4514 operands.push_back(imageOperand);
4515 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004516 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004517 spv::IdImmediate imageOperand = { true,
4518 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004519 operands.push_back(imageOperand);
4520 }
4521
John Kessenich149afc32018-08-14 13:31:43 -06004522 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004523 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004524
John Kessenich149afc32018-08-14 13:31:43 -06004525 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004526 builder.setPrecision(result[0], precision);
4527
4528 // If needed, add a conversion constructor to the proper size.
4529 if (components != node->getType().getVectorSize())
4530 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4531
4532 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004533 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004534
Jeff Bolz36831c92018-09-05 10:11:41 -05004535 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004536 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004537 spv::IdImmediate texel = { true, *(opIt + 1) };
4538 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004539 } else {
4540 spv::IdImmediate texel = { true, *opIt };
4541 operands.push_back(texel);
4542 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004543
4544 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004545 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004546 mask = mask | spv::ImageOperandsSampleMask;
4547 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004548 if (cracked.lod) {
4549 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4550 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4551 mask = mask | spv::ImageOperandsLodMask;
4552 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004553 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4554 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004555 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004556 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004557 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4558 operands.push_back(imageOperands);
4559 }
4560 if (mask & spv::ImageOperandsSampleMask) {
4561 spv::IdImmediate imageOperand = { true, *opIt++ };
4562 operands.push_back(imageOperand);
4563 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004564 if (mask & spv::ImageOperandsLodMask) {
4565 spv::IdImmediate imageOperand = { true, *opIt++ };
4566 operands.push_back(imageOperand);
4567 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004568 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004569 spv::IdImmediate imageOperand = { true,
4570 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004571 operands.push_back(imageOperand);
4572 }
4573
John Kessenich56bab042015-09-16 10:54:31 -06004574 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004575 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004576 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004577 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004578 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4579 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004580 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004581 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004582 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4583
Jeff Bolz36831c92018-09-05 10:11:41 -05004584 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004585 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004586 mask = mask | spv::ImageOperandsSampleMask;
4587 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004588 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004589 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4590 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4591
Jeff Bolz36831c92018-09-05 10:11:41 -05004592 mask = mask | spv::ImageOperandsLodMask;
4593 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004594 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4595 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004596 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004597 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004598 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004599 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004600 }
4601 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004602 spv::IdImmediate imageOperand = { true, *opIt++ };
4603 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004604 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004605 if (mask & spv::ImageOperandsLodMask) {
4606 spv::IdImmediate imageOperand = { true, *opIt++ };
4607 operands.push_back(imageOperand);
4608 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004609 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4610 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4611 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004612 }
4613
4614 // Create the return type that was a special structure
4615 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004616 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004617 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4618 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4619
4620 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4621
4622 // Decode the return type
4623 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4624 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004625 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004626 // Process image atomic operations
4627
4628 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4629 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004630 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004631 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004632 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004633
Jeff Bolz36831c92018-09-05 10:11:41 -05004634 spv::Id resultTypeId;
4635 // imageAtomicStore has a void return type so base the pointer type on
4636 // the type of the value operand.
4637 if (node->getOp() == glslang::EOpImageAtomicStore) {
4638 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4639 } else {
4640 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4641 }
John Kessenich56bab042015-09-16 10:54:31 -06004642 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004643
4644 std::vector<spv::Id> operands;
4645 operands.push_back(pointer);
4646 for (; opIt != arguments.end(); ++opIt)
4647 operands.push_back(*opIt);
4648
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004649 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004650 }
4651 }
4652
John Kessenicha28f7a72019-08-06 07:00:58 -06004653#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004654 // Check for fragment mask functions other than queries
4655 if (cracked.fragMask) {
4656 assert(sampler.ms);
4657
4658 auto opIt = arguments.begin();
4659 std::vector<spv::Id> operands;
4660
4661 // Extract the image if necessary
4662 if (builder.isSampledImage(params.sampler))
4663 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4664
4665 operands.push_back(params.sampler);
4666 ++opIt;
4667
4668 if (sampler.isSubpass()) {
4669 // add on the (0,0) coordinate
4670 spv::Id zero = builder.makeIntConstant(0);
4671 std::vector<spv::Id> comps;
4672 comps.push_back(zero);
4673 comps.push_back(zero);
4674 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4675 }
4676
4677 for (; opIt != arguments.end(); ++opIt)
4678 operands.push_back(*opIt);
4679
4680 spv::Op fragMaskOp = spv::OpNop;
4681 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4682 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4683 else if (node->getOp() == glslang::EOpFragmentFetch)
4684 fragMaskOp = spv::OpFragmentFetchAMD;
4685
4686 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4687 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4688 return builder.createOp(fragMaskOp, resultType(), operands);
4689 }
4690#endif
4691
Rex Xufc618912015-09-09 16:42:49 +08004692 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004693 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004694 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004695 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08004696
John Kessenichfc51d282015-08-19 13:34:18 -06004697 // check for bias argument
4698 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004699 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004700 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004701 if (cracked.gather)
4702 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004703
4704 if (f16ShadowCompare)
4705 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004706 if (cracked.offset)
4707 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004708 else if (cracked.offsets)
4709 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004710 if (cracked.grad)
4711 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004712 if (cracked.lodClamp)
4713 ++nonBiasArgCount;
4714 if (sparse)
4715 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004716 if (imageFootprint)
4717 //Following three extra arguments
4718 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4719 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06004720 if ((int)arguments.size() > nonBiasArgCount)
4721 bias = true;
4722 }
4723
John Kessenicha5c33d62016-06-02 23:45:21 -06004724 // See if the sampler param should really be just the SPV image part
4725 if (cracked.fetch) {
4726 // a fetch needs to have the image extracted first
4727 if (builder.isSampledImage(params.sampler))
4728 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4729 }
4730
John Kessenicha28f7a72019-08-06 07:00:58 -06004731#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08004732 if (cracked.gather) {
4733 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4734 if (bias || cracked.lod ||
4735 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4736 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004737 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004738 }
4739 }
4740#endif
4741
John Kessenichfc51d282015-08-19 13:34:18 -06004742 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004743
John Kessenichfc51d282015-08-19 13:34:18 -06004744 params.coords = arguments[1];
4745 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004746 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004747
4748 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004749 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004750 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004751 ++extraArgs;
4752 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004753 params.Dref = arguments[2];
4754 ++extraArgs;
4755 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004756 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004757 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004758 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004759 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004760 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004761 dRefComp = builder.getNumComponents(params.coords) - 1;
4762 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004763 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4764 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004765
4766 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004767 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004768 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004769 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004770 } else if (glslangIntermediate->getStage() != EShLangFragment
John Kessenicha28f7a72019-08-06 07:00:58 -06004771#ifndef GLSLANG_WEB
Chao Chenbeae2252018-09-19 11:40:45 -07004772 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4773 && !(glslangIntermediate->getStage() == EShLangCompute &&
4774 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4775#endif
4776 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004777 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4778 noImplicitLod = true;
4779 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004780
4781 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004782 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004783 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004784 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004785 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004786
4787 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004788 if (cracked.grad) {
4789 params.gradX = arguments[2 + extraArgs];
4790 params.gradY = arguments[3 + extraArgs];
4791 extraArgs += 2;
4792 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004793
4794 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004795 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004796 params.offset = arguments[2 + extraArgs];
4797 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004798 } else if (cracked.offsets) {
4799 params.offsets = arguments[2 + extraArgs];
4800 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004801 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004802
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004803#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06004804 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004805 if (cracked.lodClamp) {
4806 params.lodClamp = arguments[2 + extraArgs];
4807 ++extraArgs;
4808 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004809 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004810 if (sparse) {
4811 params.texelOut = arguments[2 + extraArgs];
4812 ++extraArgs;
4813 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004814 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004815 if (cracked.gather && ! sampler.shadow) {
4816 // default component is 0, if missing, otherwise an argument
4817 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004818 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004819 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004820 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004821 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004822 }
Chao Chen3a137962018-09-19 11:41:27 -07004823 spv::Id resultStruct = spv::NoResult;
4824 if (imageFootprint) {
4825 //Following three extra arguments
4826 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4827 params.granularity = arguments[2 + extraArgs];
4828 params.coarse = arguments[3 + extraArgs];
4829 resultStruct = arguments[4 + extraArgs];
4830 extraArgs += 3;
4831 }
4832#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004833 // bias
4834 if (bias) {
4835 params.bias = arguments[2 + extraArgs];
4836 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004837 }
John Kessenichfc51d282015-08-19 13:34:18 -06004838
John Kessenicha28f7a72019-08-06 07:00:58 -06004839#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07004840 if (imageFootprint) {
4841 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4842 builder.addCapability(spv::CapabilityImageFootprintNV);
4843
4844
4845 //resultStructType(OpenGL type) contains 5 elements:
4846 //struct gl_TextureFootprint2DNV {
4847 // uvec2 anchor;
4848 // uvec2 offset;
4849 // uvec2 mask;
4850 // uint lod;
4851 // uint granularity;
4852 //};
4853 //or
4854 //struct gl_TextureFootprint3DNV {
4855 // uvec3 anchor;
4856 // uvec3 offset;
4857 // uvec2 mask;
4858 // uint lod;
4859 // uint granularity;
4860 //};
4861 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4862 assert(builder.isStructType(resultStructType));
4863
4864 //resType (SPIR-V type) contains 6 elements:
4865 //Member 0 must be a Boolean type scalar(LOD),
4866 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4867 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4868 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4869 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4870 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4871 std::vector<spv::Id> members;
4872 members.push_back(resultType());
4873 for (int i = 0; i < 5; i++) {
4874 members.push_back(builder.getContainedTypeId(resultStructType, i));
4875 }
4876 spv::Id resType = builder.makeStructType(members, "ResType");
4877
4878 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06004879 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
4880 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07004881
4882 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4883 for (int i = 0; i < 5; i++) {
4884 builder.clearAccessChain();
4885 builder.setAccessChainLValue(resultStruct);
4886
4887 //Accessing to a struct we created, no coherent flag is set
4888 spv::Builder::AccessChain::CoherentFlags flags;
4889 flags.clear();
4890
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004891 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004892 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4893 }
4894 return builder.createCompositeExtract(res, resultType(), 0);
4895 }
4896#endif
4897
John Kessenich65336482016-06-16 14:06:26 -06004898 // projective component (might not to move)
4899 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4900 // are divided by the last component of P."
4901 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4902 // unused components will appear after all used components."
4903 if (cracked.proj) {
4904 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4905 int projTargetComp;
4906 switch (sampler.dim) {
4907 case glslang::Esd1D: projTargetComp = 1; break;
4908 case glslang::Esd2D: projTargetComp = 2; break;
4909 case glslang::EsdRect: projTargetComp = 2; break;
4910 default: projTargetComp = projSourceComp; break;
4911 }
4912 // copy the projective coordinate if we have to
4913 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004914 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004915 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4916 projSourceComp);
4917 params.coords = builder.createCompositeInsert(projComp, params.coords,
4918 builder.getTypeId(params.coords), projTargetComp);
4919 }
4920 }
4921
Jeff Bolz36831c92018-09-05 10:11:41 -05004922 // nonprivate
4923 if (imageType.getQualifier().nonprivate) {
4924 params.nonprivate = true;
4925 }
4926
4927 // volatile
4928 if (imageType.getQualifier().volatil) {
4929 params.volatil = true;
4930 }
4931
St0fFa1184dd2018-04-09 21:08:14 +02004932 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06004933 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
4934 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02004935 );
LoopDawg4425f242018-02-18 11:40:01 -07004936
4937 if (components != node->getType().getVectorSize())
4938 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4939
4940 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004941}
4942
4943spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4944{
4945 // Grab the function's pointer from the previously created function
4946 spv::Function* function = functionMap[node->getName().c_str()];
4947 if (! function)
4948 return 0;
4949
4950 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4951 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4952
4953 // See comments in makeFunctions() for details about the semantics for parameter passing.
4954 //
4955 // These imply we need a four step process:
4956 // 1. Evaluate the arguments
4957 // 2. Allocate and make copies of in, out, and inout arguments
4958 // 3. Make the call
4959 // 4. Copy back the results
4960
John Kessenichd3ed90b2018-05-04 11:43:03 -06004961 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004962 std::vector<spv::Builder::AccessChain> lValues;
4963 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004964 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004965 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004966 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004967 // build l-value
4968 builder.clearAccessChain();
4969 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004970 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004971 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004972 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004973 // save l-value
4974 lValues.push_back(builder.getAccessChain());
4975 } else {
4976 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004977 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004978 }
4979 }
4980
4981 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4982 // copy the original into that space.
4983 //
4984 // Also, build up the list of actual arguments to pass in for the call
4985 int lValueCount = 0;
4986 int rValueCount = 0;
4987 std::vector<spv::Id> spvArgs;
4988 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4989 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004990 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004991 builder.setAccessChain(lValues[lValueCount]);
4992 arg = builder.accessChainGetLValue();
4993 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004994 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004995 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004996 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004997 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4998 // need to copy the input into output space
4999 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005000 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005001 builder.clearAccessChain();
5002 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005003 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005004 }
5005 ++lValueCount;
5006 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005007 // process r-value, which involves a copy for a type mismatch
5008 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5009 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5010 builder.clearAccessChain();
5011 builder.setAccessChainLValue(argCopy);
5012 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5013 arg = builder.createLoad(argCopy);
5014 } else
5015 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005016 ++rValueCount;
5017 }
5018 spvArgs.push_back(arg);
5019 }
5020
5021 // 3. Make the call.
5022 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005023 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005024
5025 // 4. Copy back out an "out" arguments.
5026 lValueCount = 0;
5027 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005028 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005029 ++lValueCount;
5030 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005031 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5032 spv::Id copy = builder.createLoad(spvArgs[a]);
5033 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005034 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005035 }
5036 ++lValueCount;
5037 }
5038 }
5039
5040 return result;
5041}
5042
5043// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005044spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005045 spv::Id typeId, spv::Id left, spv::Id right,
5046 glslang::TBasicType typeProxy, bool reduceComparison)
5047{
John Kessenich66011cb2018-03-06 16:12:04 -07005048 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5049 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005050 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005051
5052 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005053 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005054 bool comparison = false;
5055
5056 switch (op) {
5057 case glslang::EOpAdd:
5058 case glslang::EOpAddAssign:
5059 if (isFloat)
5060 binOp = spv::OpFAdd;
5061 else
5062 binOp = spv::OpIAdd;
5063 break;
5064 case glslang::EOpSub:
5065 case glslang::EOpSubAssign:
5066 if (isFloat)
5067 binOp = spv::OpFSub;
5068 else
5069 binOp = spv::OpISub;
5070 break;
5071 case glslang::EOpMul:
5072 case glslang::EOpMulAssign:
5073 if (isFloat)
5074 binOp = spv::OpFMul;
5075 else
5076 binOp = spv::OpIMul;
5077 break;
5078 case glslang::EOpVectorTimesScalar:
5079 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005080 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005081 if (builder.isVector(right))
5082 std::swap(left, right);
5083 assert(builder.isScalar(right));
5084 needMatchingVectors = false;
5085 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005086 } else if (isFloat)
5087 binOp = spv::OpFMul;
5088 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005089 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005090 break;
5091 case glslang::EOpVectorTimesMatrix:
5092 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005093 binOp = spv::OpVectorTimesMatrix;
5094 break;
5095 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005096 binOp = spv::OpMatrixTimesVector;
5097 break;
5098 case glslang::EOpMatrixTimesScalar:
5099 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005100 binOp = spv::OpMatrixTimesScalar;
5101 break;
5102 case glslang::EOpMatrixTimesMatrix:
5103 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005104 binOp = spv::OpMatrixTimesMatrix;
5105 break;
5106 case glslang::EOpOuterProduct:
5107 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005108 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005109 break;
5110
5111 case glslang::EOpDiv:
5112 case glslang::EOpDivAssign:
5113 if (isFloat)
5114 binOp = spv::OpFDiv;
5115 else if (isUnsigned)
5116 binOp = spv::OpUDiv;
5117 else
5118 binOp = spv::OpSDiv;
5119 break;
5120 case glslang::EOpMod:
5121 case glslang::EOpModAssign:
5122 if (isFloat)
5123 binOp = spv::OpFMod;
5124 else if (isUnsigned)
5125 binOp = spv::OpUMod;
5126 else
5127 binOp = spv::OpSMod;
5128 break;
5129 case glslang::EOpRightShift:
5130 case glslang::EOpRightShiftAssign:
5131 if (isUnsigned)
5132 binOp = spv::OpShiftRightLogical;
5133 else
5134 binOp = spv::OpShiftRightArithmetic;
5135 break;
5136 case glslang::EOpLeftShift:
5137 case glslang::EOpLeftShiftAssign:
5138 binOp = spv::OpShiftLeftLogical;
5139 break;
5140 case glslang::EOpAnd:
5141 case glslang::EOpAndAssign:
5142 binOp = spv::OpBitwiseAnd;
5143 break;
5144 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005145 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005146 binOp = spv::OpLogicalAnd;
5147 break;
5148 case glslang::EOpInclusiveOr:
5149 case glslang::EOpInclusiveOrAssign:
5150 binOp = spv::OpBitwiseOr;
5151 break;
5152 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005153 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005154 binOp = spv::OpLogicalOr;
5155 break;
5156 case glslang::EOpExclusiveOr:
5157 case glslang::EOpExclusiveOrAssign:
5158 binOp = spv::OpBitwiseXor;
5159 break;
5160 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005161 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005162 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005163 break;
5164
5165 case glslang::EOpLessThan:
5166 case glslang::EOpGreaterThan:
5167 case glslang::EOpLessThanEqual:
5168 case glslang::EOpGreaterThanEqual:
5169 case glslang::EOpEqual:
5170 case glslang::EOpNotEqual:
5171 case glslang::EOpVectorEqual:
5172 case glslang::EOpVectorNotEqual:
5173 comparison = true;
5174 break;
5175 default:
5176 break;
5177 }
5178
John Kessenich7c1aa102015-10-15 13:29:11 -06005179 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005180 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005181 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005182 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5183 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005184 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005185
5186 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005187 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005188 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005189
qining25262b32016-05-06 17:25:16 -04005190 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005191 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005192 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005193 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005194 }
5195
5196 if (! comparison)
5197 return 0;
5198
John Kessenich7c1aa102015-10-15 13:29:11 -06005199 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005200
John Kessenich4583b612016-08-07 19:14:22 -06005201 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005202 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5203 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06005204 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005205 return result;
5206 }
John Kessenich140f3df2015-06-26 16:58:36 -06005207
5208 switch (op) {
5209 case glslang::EOpLessThan:
5210 if (isFloat)
5211 binOp = spv::OpFOrdLessThan;
5212 else if (isUnsigned)
5213 binOp = spv::OpULessThan;
5214 else
5215 binOp = spv::OpSLessThan;
5216 break;
5217 case glslang::EOpGreaterThan:
5218 if (isFloat)
5219 binOp = spv::OpFOrdGreaterThan;
5220 else if (isUnsigned)
5221 binOp = spv::OpUGreaterThan;
5222 else
5223 binOp = spv::OpSGreaterThan;
5224 break;
5225 case glslang::EOpLessThanEqual:
5226 if (isFloat)
5227 binOp = spv::OpFOrdLessThanEqual;
5228 else if (isUnsigned)
5229 binOp = spv::OpULessThanEqual;
5230 else
5231 binOp = spv::OpSLessThanEqual;
5232 break;
5233 case glslang::EOpGreaterThanEqual:
5234 if (isFloat)
5235 binOp = spv::OpFOrdGreaterThanEqual;
5236 else if (isUnsigned)
5237 binOp = spv::OpUGreaterThanEqual;
5238 else
5239 binOp = spv::OpSGreaterThanEqual;
5240 break;
5241 case glslang::EOpEqual:
5242 case glslang::EOpVectorEqual:
5243 if (isFloat)
5244 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005245 else if (isBool)
5246 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005247 else
5248 binOp = spv::OpIEqual;
5249 break;
5250 case glslang::EOpNotEqual:
5251 case glslang::EOpVectorNotEqual:
5252 if (isFloat)
5253 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005254 else if (isBool)
5255 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005256 else
5257 binOp = spv::OpINotEqual;
5258 break;
5259 default:
5260 break;
5261 }
5262
qining25262b32016-05-06 17:25:16 -04005263 if (binOp != spv::OpNop) {
5264 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005265 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005266 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005267 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005268 }
John Kessenich140f3df2015-06-26 16:58:36 -06005269
5270 return 0;
5271}
5272
John Kessenich04bb8a02015-12-12 12:28:14 -07005273//
5274// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5275// These can be any of:
5276//
5277// matrix * scalar
5278// scalar * matrix
5279// matrix * matrix linear algebraic
5280// matrix * vector
5281// vector * matrix
5282// matrix * matrix componentwise
5283// matrix op matrix op in {+, -, /}
5284// matrix op scalar op in {+, -, /}
5285// scalar op matrix op in {+, -, /}
5286//
John Kessenichead86222018-03-28 18:01:20 -06005287spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5288 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005289{
5290 bool firstClass = true;
5291
5292 // First, handle first-class matrix operations (* and matrix/scalar)
5293 switch (op) {
5294 case spv::OpFDiv:
5295 if (builder.isMatrix(left) && builder.isScalar(right)) {
5296 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005297 spv::Id resultType = builder.getTypeId(right);
5298 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005299 op = spv::OpMatrixTimesScalar;
5300 } else
5301 firstClass = false;
5302 break;
5303 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005304 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005305 std::swap(left, right);
5306 assert(builder.isScalar(right));
5307 break;
5308 case spv::OpVectorTimesMatrix:
5309 assert(builder.isVector(left));
5310 assert(builder.isMatrix(right));
5311 break;
5312 case spv::OpMatrixTimesVector:
5313 assert(builder.isMatrix(left));
5314 assert(builder.isVector(right));
5315 break;
5316 case spv::OpMatrixTimesMatrix:
5317 assert(builder.isMatrix(left));
5318 assert(builder.isMatrix(right));
5319 break;
5320 default:
5321 firstClass = false;
5322 break;
5323 }
5324
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005325 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5326 firstClass = true;
5327
qining25262b32016-05-06 17:25:16 -04005328 if (firstClass) {
5329 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005330 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005331 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005332 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005333 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005334
LoopDawg592860c2016-06-09 08:57:35 -06005335 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005336 // The result type of all of them is the same type as the (a) matrix operand.
5337 // The algorithm is to:
5338 // - break the matrix(es) into vectors
5339 // - smear any scalar to a vector
5340 // - do vector operations
5341 // - make a matrix out the vector results
5342 switch (op) {
5343 case spv::OpFAdd:
5344 case spv::OpFSub:
5345 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005346 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005347 case spv::OpFMul:
5348 {
5349 // one time set up...
5350 bool leftMat = builder.isMatrix(left);
5351 bool rightMat = builder.isMatrix(right);
5352 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5353 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5354 spv::Id scalarType = builder.getScalarTypeId(typeId);
5355 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5356 std::vector<spv::Id> results;
5357 spv::Id smearVec = spv::NoResult;
5358 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005359 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005360 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005361 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005362
5363 // do each vector op
5364 for (unsigned int c = 0; c < numCols; ++c) {
5365 std::vector<unsigned int> indexes;
5366 indexes.push_back(c);
5367 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5368 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005369 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005370 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005371 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005372 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005373 }
5374
5375 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005376 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005377 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005378 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005379 }
5380 default:
5381 assert(0);
5382 return spv::NoResult;
5383 }
5384}
5385
John Kessenichead86222018-03-28 18:01:20 -06005386spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005387 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005388{
5389 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005390 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005391 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005392 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5393 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005394
5395 switch (op) {
5396 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005397 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005398 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005399 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005400 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005401 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005402 unaryOp = spv::OpSNegate;
5403 break;
5404
5405 case glslang::EOpLogicalNot:
5406 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005407 unaryOp = spv::OpLogicalNot;
5408 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005409 case glslang::EOpBitwiseNot:
5410 unaryOp = spv::OpNot;
5411 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005412
John Kessenich140f3df2015-06-26 16:58:36 -06005413 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005414 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005415 break;
5416 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005417 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005418 break;
5419 case glslang::EOpTranspose:
5420 unaryOp = spv::OpTranspose;
5421 break;
5422
5423 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005424 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005425 break;
5426 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005427 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005428 break;
5429 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005430 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005431 break;
5432 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005433 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005434 break;
5435 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005436 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005437 break;
5438 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005439 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005440 break;
5441 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005442 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005443 break;
5444 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005445 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005446 break;
5447
5448 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005449 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005450 break;
5451 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005452 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005453 break;
5454 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005455 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005456 break;
5457 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005458 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005459 break;
5460 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005461 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005462 break;
5463 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005464 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005465 break;
5466
5467 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005468 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005469 break;
5470 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005471 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005472 break;
5473
5474 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005475 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005476 break;
5477 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005478 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005479 break;
5480 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005481 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005482 break;
5483 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005484 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005485 break;
5486 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005487 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005488 break;
5489 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005490 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005491 break;
5492
5493 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005494 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005495 break;
5496 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005497 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005498 break;
5499 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005500 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005501 break;
5502 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005503 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005504 break;
5505 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005506 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005507 break;
5508 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005509 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005510 break;
5511
5512 case glslang::EOpIsNan:
5513 unaryOp = spv::OpIsNan;
5514 break;
5515 case glslang::EOpIsInf:
5516 unaryOp = spv::OpIsInf;
5517 break;
LoopDawg592860c2016-06-09 08:57:35 -06005518 case glslang::EOpIsFinite:
5519 unaryOp = spv::OpIsFinite;
5520 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005521
Rex Xucbc426e2015-12-15 16:03:10 +08005522 case glslang::EOpFloatBitsToInt:
5523 case glslang::EOpFloatBitsToUint:
5524 case glslang::EOpIntBitsToFloat:
5525 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005526 case glslang::EOpDoubleBitsToInt64:
5527 case glslang::EOpDoubleBitsToUint64:
5528 case glslang::EOpInt64BitsToDouble:
5529 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005530 case glslang::EOpFloat16BitsToInt16:
5531 case glslang::EOpFloat16BitsToUint16:
5532 case glslang::EOpInt16BitsToFloat16:
5533 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005534 unaryOp = spv::OpBitcast;
5535 break;
5536
John Kessenich140f3df2015-06-26 16:58:36 -06005537 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005538 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005539 break;
5540 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005541 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005542 break;
5543 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005544 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005545 break;
5546 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005547 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005548 break;
5549 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005550 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005551 break;
5552 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005553 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005554 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005555 case glslang::EOpPackSnorm4x8:
5556 libCall = spv::GLSLstd450PackSnorm4x8;
5557 break;
5558 case glslang::EOpUnpackSnorm4x8:
5559 libCall = spv::GLSLstd450UnpackSnorm4x8;
5560 break;
5561 case glslang::EOpPackUnorm4x8:
5562 libCall = spv::GLSLstd450PackUnorm4x8;
5563 break;
5564 case glslang::EOpUnpackUnorm4x8:
5565 libCall = spv::GLSLstd450UnpackUnorm4x8;
5566 break;
5567 case glslang::EOpPackDouble2x32:
5568 libCall = spv::GLSLstd450PackDouble2x32;
5569 break;
5570 case glslang::EOpUnpackDouble2x32:
5571 libCall = spv::GLSLstd450UnpackDouble2x32;
5572 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005573
Rex Xu8ff43de2016-04-22 16:51:45 +08005574 case glslang::EOpPackInt2x32:
5575 case glslang::EOpUnpackInt2x32:
5576 case glslang::EOpPackUint2x32:
5577 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005578 case glslang::EOpPack16:
5579 case glslang::EOpPack32:
5580 case glslang::EOpPack64:
5581 case glslang::EOpUnpack32:
5582 case glslang::EOpUnpack16:
5583 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005584 case glslang::EOpPackInt2x16:
5585 case glslang::EOpUnpackInt2x16:
5586 case glslang::EOpPackUint2x16:
5587 case glslang::EOpUnpackUint2x16:
5588 case glslang::EOpPackInt4x16:
5589 case glslang::EOpUnpackInt4x16:
5590 case glslang::EOpPackUint4x16:
5591 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005592 case glslang::EOpPackFloat2x16:
5593 case glslang::EOpUnpackFloat2x16:
5594 unaryOp = spv::OpBitcast;
5595 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005596
John Kessenich140f3df2015-06-26 16:58:36 -06005597 case glslang::EOpDPdx:
5598 unaryOp = spv::OpDPdx;
5599 break;
5600 case glslang::EOpDPdy:
5601 unaryOp = spv::OpDPdy;
5602 break;
5603 case glslang::EOpFwidth:
5604 unaryOp = spv::OpFwidth;
5605 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005606
John Kessenich140f3df2015-06-26 16:58:36 -06005607 case glslang::EOpAny:
5608 unaryOp = spv::OpAny;
5609 break;
5610 case glslang::EOpAll:
5611 unaryOp = spv::OpAll;
5612 break;
5613
5614 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005615 if (isFloat)
5616 libCall = spv::GLSLstd450FAbs;
5617 else
5618 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005619 break;
5620 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005621 if (isFloat)
5622 libCall = spv::GLSLstd450FSign;
5623 else
5624 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005625 break;
5626
John Kessenicha28f7a72019-08-06 07:00:58 -06005627#ifndef GLSLANG_WEB
5628 case glslang::EOpDPdxFine:
5629 unaryOp = spv::OpDPdxFine;
5630 break;
5631 case glslang::EOpDPdyFine:
5632 unaryOp = spv::OpDPdyFine;
5633 break;
5634 case glslang::EOpFwidthFine:
5635 unaryOp = spv::OpFwidthFine;
5636 break;
5637 case glslang::EOpDPdxCoarse:
5638 unaryOp = spv::OpDPdxCoarse;
5639 break;
5640 case glslang::EOpDPdyCoarse:
5641 unaryOp = spv::OpDPdyCoarse;
5642 break;
5643 case glslang::EOpFwidthCoarse:
5644 unaryOp = spv::OpFwidthCoarse;
5645 break;
5646 case glslang::EOpInterpolateAtCentroid:
5647 if (typeProxy == glslang::EbtFloat16)
5648 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5649 libCall = spv::GLSLstd450InterpolateAtCentroid;
5650 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005651 case glslang::EOpAtomicCounterIncrement:
5652 case glslang::EOpAtomicCounterDecrement:
5653 case glslang::EOpAtomicCounter:
5654 {
5655 // Handle all of the atomics in one place, in createAtomicOperation()
5656 std::vector<spv::Id> operands;
5657 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005658 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005659 }
5660
John Kessenichfc51d282015-08-19 13:34:18 -06005661 case glslang::EOpBitFieldReverse:
5662 unaryOp = spv::OpBitReverse;
5663 break;
5664 case glslang::EOpBitCount:
5665 unaryOp = spv::OpBitCount;
5666 break;
5667 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005668 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005669 break;
5670 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005671 if (isUnsigned)
5672 libCall = spv::GLSLstd450FindUMsb;
5673 else
5674 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005675 break;
5676
Rex Xu574ab042016-04-14 16:53:07 +08005677 case glslang::EOpBallot:
5678 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005679 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005680 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005681 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005682 case glslang::EOpMinInvocations:
5683 case glslang::EOpMaxInvocations:
5684 case glslang::EOpAddInvocations:
5685 case glslang::EOpMinInvocationsNonUniform:
5686 case glslang::EOpMaxInvocationsNonUniform:
5687 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005688 case glslang::EOpMinInvocationsInclusiveScan:
5689 case glslang::EOpMaxInvocationsInclusiveScan:
5690 case glslang::EOpAddInvocationsInclusiveScan:
5691 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5692 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5693 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5694 case glslang::EOpMinInvocationsExclusiveScan:
5695 case glslang::EOpMaxInvocationsExclusiveScan:
5696 case glslang::EOpAddInvocationsExclusiveScan:
5697 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5698 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5699 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08005700 {
5701 std::vector<spv::Id> operands;
5702 operands.push_back(operand);
5703 return createInvocationsOperation(op, typeId, operands, typeProxy);
5704 }
John Kessenich66011cb2018-03-06 16:12:04 -07005705 case glslang::EOpSubgroupAll:
5706 case glslang::EOpSubgroupAny:
5707 case glslang::EOpSubgroupAllEqual:
5708 case glslang::EOpSubgroupBroadcastFirst:
5709 case glslang::EOpSubgroupBallot:
5710 case glslang::EOpSubgroupInverseBallot:
5711 case glslang::EOpSubgroupBallotBitCount:
5712 case glslang::EOpSubgroupBallotInclusiveBitCount:
5713 case glslang::EOpSubgroupBallotExclusiveBitCount:
5714 case glslang::EOpSubgroupBallotFindLSB:
5715 case glslang::EOpSubgroupBallotFindMSB:
5716 case glslang::EOpSubgroupAdd:
5717 case glslang::EOpSubgroupMul:
5718 case glslang::EOpSubgroupMin:
5719 case glslang::EOpSubgroupMax:
5720 case glslang::EOpSubgroupAnd:
5721 case glslang::EOpSubgroupOr:
5722 case glslang::EOpSubgroupXor:
5723 case glslang::EOpSubgroupInclusiveAdd:
5724 case glslang::EOpSubgroupInclusiveMul:
5725 case glslang::EOpSubgroupInclusiveMin:
5726 case glslang::EOpSubgroupInclusiveMax:
5727 case glslang::EOpSubgroupInclusiveAnd:
5728 case glslang::EOpSubgroupInclusiveOr:
5729 case glslang::EOpSubgroupInclusiveXor:
5730 case glslang::EOpSubgroupExclusiveAdd:
5731 case glslang::EOpSubgroupExclusiveMul:
5732 case glslang::EOpSubgroupExclusiveMin:
5733 case glslang::EOpSubgroupExclusiveMax:
5734 case glslang::EOpSubgroupExclusiveAnd:
5735 case glslang::EOpSubgroupExclusiveOr:
5736 case glslang::EOpSubgroupExclusiveXor:
5737 case glslang::EOpSubgroupQuadSwapHorizontal:
5738 case glslang::EOpSubgroupQuadSwapVertical:
5739 case glslang::EOpSubgroupQuadSwapDiagonal: {
5740 std::vector<spv::Id> operands;
5741 operands.push_back(operand);
5742 return createSubgroupOperation(op, typeId, operands, typeProxy);
5743 }
Rex Xu9d93a232016-05-05 12:30:44 +08005744 case glslang::EOpMbcnt:
5745 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5746 libCall = spv::MbcntAMD;
5747 break;
5748
5749 case glslang::EOpCubeFaceIndex:
5750 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5751 libCall = spv::CubeFaceIndexAMD;
5752 break;
5753
5754 case glslang::EOpCubeFaceCoord:
5755 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5756 libCall = spv::CubeFaceCoordAMD;
5757 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005758 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005759 unaryOp = spv::OpGroupNonUniformPartitionNV;
5760 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005761 case glslang::EOpConstructReference:
5762 unaryOp = spv::OpBitcast;
5763 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005764#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05005765
5766 case glslang::EOpCopyObject:
5767 unaryOp = spv::OpCopyObject;
5768 break;
5769
John Kessenich140f3df2015-06-26 16:58:36 -06005770 default:
5771 return 0;
5772 }
5773
5774 spv::Id id;
5775 if (libCall >= 0) {
5776 std::vector<spv::Id> args;
5777 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005778 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005779 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005780 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005781 }
John Kessenich140f3df2015-06-26 16:58:36 -06005782
John Kessenichead86222018-03-28 18:01:20 -06005783 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005784 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005785 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005786}
5787
John Kessenich7a53f762016-01-20 11:19:27 -07005788// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005789spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5790 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005791{
5792 // Handle unary operations vector by vector.
5793 // The result type is the same type as the original type.
5794 // The algorithm is to:
5795 // - break the matrix into vectors
5796 // - apply the operation to each vector
5797 // - make a matrix out the vector results
5798
5799 // get the types sorted out
5800 int numCols = builder.getNumColumns(operand);
5801 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005802 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5803 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005804 std::vector<spv::Id> results;
5805
5806 // do each vector op
5807 for (int c = 0; c < numCols; ++c) {
5808 std::vector<unsigned int> indexes;
5809 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005810 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5811 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005812 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005813 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005814 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005815 }
5816
5817 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005818 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005819 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005820 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005821}
5822
John Kessenichad7645f2018-06-04 19:11:25 -06005823// For converting integers where both the bitwidth and the signedness could
5824// change, but only do the width change here. The caller is still responsible
5825// for the signedness conversion.
5826spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005827{
John Kessenichad7645f2018-06-04 19:11:25 -06005828 // Get the result type width, based on the type to convert to.
5829 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005830 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005831 case glslang::EOpConvInt16ToUint8:
5832 case glslang::EOpConvIntToUint8:
5833 case glslang::EOpConvInt64ToUint8:
5834 case glslang::EOpConvUint16ToInt8:
5835 case glslang::EOpConvUintToInt8:
5836 case glslang::EOpConvUint64ToInt8:
5837 width = 8;
5838 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005839 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005840 case glslang::EOpConvIntToUint16:
5841 case glslang::EOpConvInt64ToUint16:
5842 case glslang::EOpConvUint8ToInt16:
5843 case glslang::EOpConvUintToInt16:
5844 case glslang::EOpConvUint64ToInt16:
5845 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005846 break;
5847 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005848 case glslang::EOpConvInt16ToUint:
5849 case glslang::EOpConvInt64ToUint:
5850 case glslang::EOpConvUint8ToInt:
5851 case glslang::EOpConvUint16ToInt:
5852 case glslang::EOpConvUint64ToInt:
5853 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005854 break;
5855 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005856 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005857 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005858 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005859 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005860 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005861 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005862 break;
5863
5864 default:
5865 assert(false && "Default missing");
5866 break;
5867 }
5868
John Kessenichad7645f2018-06-04 19:11:25 -06005869 // Get the conversion operation and result type,
5870 // based on the target width, but the source type.
5871 spv::Id type = spv::NoType;
5872 spv::Op convOp = spv::OpNop;
5873 switch(op) {
5874 case glslang::EOpConvInt8ToUint16:
5875 case glslang::EOpConvInt8ToUint:
5876 case glslang::EOpConvInt8ToUint64:
5877 case glslang::EOpConvInt16ToUint8:
5878 case glslang::EOpConvInt16ToUint:
5879 case glslang::EOpConvInt16ToUint64:
5880 case glslang::EOpConvIntToUint8:
5881 case glslang::EOpConvIntToUint16:
5882 case glslang::EOpConvIntToUint64:
5883 case glslang::EOpConvInt64ToUint8:
5884 case glslang::EOpConvInt64ToUint16:
5885 case glslang::EOpConvInt64ToUint:
5886 convOp = spv::OpSConvert;
5887 type = builder.makeIntType(width);
5888 break;
5889 default:
5890 convOp = spv::OpUConvert;
5891 type = builder.makeUintType(width);
5892 break;
5893 }
5894
John Kessenich66011cb2018-03-06 16:12:04 -07005895 if (vectorSize > 0)
5896 type = builder.makeVectorType(type, vectorSize);
5897
John Kessenichad7645f2018-06-04 19:11:25 -06005898 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005899}
5900
John Kessenichead86222018-03-28 18:01:20 -06005901spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5902 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005903{
5904 spv::Op convOp = spv::OpNop;
5905 spv::Id zero = 0;
5906 spv::Id one = 0;
5907
5908 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5909
5910 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005911 case glslang::EOpConvIntToBool:
5912 case glslang::EOpConvUintToBool:
5913 zero = builder.makeUintConstant(0);
5914 zero = makeSmearedConstant(zero, vectorSize);
5915 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06005916 case glslang::EOpConvFloatToBool:
5917 zero = builder.makeFloatConstant(0.0F);
5918 zero = makeSmearedConstant(zero, vectorSize);
5919 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06005920 case glslang::EOpConvBoolToFloat:
5921 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005922 zero = builder.makeFloatConstant(0.0F);
5923 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005924 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005925
John Kessenich140f3df2015-06-26 16:58:36 -06005926 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005927 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005928 if (op == glslang::EOpConvBoolToInt64)
5929 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005930 else
5931 zero = builder.makeIntConstant(0);
5932
5933 if (op == glslang::EOpConvBoolToInt64)
5934 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005935 else
5936 one = builder.makeIntConstant(1);
5937
John Kessenich140f3df2015-06-26 16:58:36 -06005938 convOp = spv::OpSelect;
5939 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005940
John Kessenich140f3df2015-06-26 16:58:36 -06005941 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005942 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005943 if (op == glslang::EOpConvBoolToUint64)
5944 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005945 else
5946 zero = builder.makeUintConstant(0);
5947
5948 if (op == glslang::EOpConvBoolToUint64)
5949 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005950 else
5951 one = builder.makeUintConstant(1);
5952
John Kessenich140f3df2015-06-26 16:58:36 -06005953 convOp = spv::OpSelect;
5954 break;
5955
John Kessenich66011cb2018-03-06 16:12:04 -07005956 case glslang::EOpConvInt8ToFloat16:
5957 case glslang::EOpConvInt8ToFloat:
5958 case glslang::EOpConvInt8ToDouble:
5959 case glslang::EOpConvInt16ToFloat16:
5960 case glslang::EOpConvInt16ToFloat:
5961 case glslang::EOpConvInt16ToDouble:
5962 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005963 case glslang::EOpConvIntToFloat:
5964 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005965 case glslang::EOpConvInt64ToFloat:
5966 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005967 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005968 convOp = spv::OpConvertSToF;
5969 break;
5970
John Kessenich66011cb2018-03-06 16:12:04 -07005971 case glslang::EOpConvUint8ToFloat16:
5972 case glslang::EOpConvUint8ToFloat:
5973 case glslang::EOpConvUint8ToDouble:
5974 case glslang::EOpConvUint16ToFloat16:
5975 case glslang::EOpConvUint16ToFloat:
5976 case glslang::EOpConvUint16ToDouble:
5977 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005978 case glslang::EOpConvUintToFloat:
5979 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005980 case glslang::EOpConvUint64ToFloat:
5981 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005982 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005983 convOp = spv::OpConvertUToF;
5984 break;
5985
John Kessenich66011cb2018-03-06 16:12:04 -07005986 case glslang::EOpConvFloat16ToInt8:
5987 case glslang::EOpConvFloatToInt8:
5988 case glslang::EOpConvDoubleToInt8:
5989 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005990 case glslang::EOpConvFloatToInt16:
5991 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005992 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005993 case glslang::EOpConvFloatToInt:
5994 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005995 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005996 case glslang::EOpConvFloatToInt64:
5997 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005998 convOp = spv::OpConvertFToS;
5999 break;
6000
John Kessenich66011cb2018-03-06 16:12:04 -07006001 case glslang::EOpConvUint8ToInt8:
6002 case glslang::EOpConvInt8ToUint8:
6003 case glslang::EOpConvUint16ToInt16:
6004 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006005 case glslang::EOpConvUintToInt:
6006 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006007 case glslang::EOpConvUint64ToInt64:
6008 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006009 if (builder.isInSpecConstCodeGenMode()) {
6010 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006011#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006012 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6013 zero = builder.makeUint8Constant(0);
6014 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006015 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006016 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6017 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006018 } else
6019#endif
6020 {
Rex Xucabbb782017-03-24 13:41:14 +08006021 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006022 }
qining189b2032016-04-12 23:16:20 -04006023 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006024 // Use OpIAdd, instead of OpBitcast to do the conversion when
6025 // generating for OpSpecConstantOp instruction.
6026 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6027 }
6028 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006029 convOp = spv::OpBitcast;
6030 break;
6031
John Kessenich66011cb2018-03-06 16:12:04 -07006032 case glslang::EOpConvFloat16ToUint8:
6033 case glslang::EOpConvFloatToUint8:
6034 case glslang::EOpConvDoubleToUint8:
6035 case glslang::EOpConvFloat16ToUint16:
6036 case glslang::EOpConvFloatToUint16:
6037 case glslang::EOpConvDoubleToUint16:
6038 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006039 case glslang::EOpConvFloatToUint:
6040 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006041 case glslang::EOpConvFloatToUint64:
6042 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006043 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006044 convOp = spv::OpConvertFToU;
6045 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006046
John Kessenich39697cd2019-08-08 10:35:51 -06006047#ifndef GLSLANG_WEB
6048 case glslang::EOpConvInt8ToBool:
6049 case glslang::EOpConvUint8ToBool:
6050 zero = builder.makeUint8Constant(0);
6051 zero = makeSmearedConstant(zero, vectorSize);
6052 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6053 case glslang::EOpConvInt16ToBool:
6054 case glslang::EOpConvUint16ToBool:
6055 zero = builder.makeUint16Constant(0);
6056 zero = makeSmearedConstant(zero, vectorSize);
6057 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6058 case glslang::EOpConvInt64ToBool:
6059 case glslang::EOpConvUint64ToBool:
6060 zero = builder.makeUint64Constant(0);
6061 zero = makeSmearedConstant(zero, vectorSize);
6062 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6063 case glslang::EOpConvDoubleToBool:
6064 zero = builder.makeDoubleConstant(0.0);
6065 zero = makeSmearedConstant(zero, vectorSize);
6066 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6067 case glslang::EOpConvFloat16ToBool:
6068 zero = builder.makeFloat16Constant(0.0F);
6069 zero = makeSmearedConstant(zero, vectorSize);
6070 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6071 case glslang::EOpConvBoolToDouble:
6072 convOp = spv::OpSelect;
6073 zero = builder.makeDoubleConstant(0.0);
6074 one = builder.makeDoubleConstant(1.0);
6075 break;
6076 case glslang::EOpConvBoolToFloat16:
6077 convOp = spv::OpSelect;
6078 zero = builder.makeFloat16Constant(0.0F);
6079 one = builder.makeFloat16Constant(1.0F);
6080 break;
6081 case glslang::EOpConvBoolToInt8:
6082 zero = builder.makeInt8Constant(0);
6083 one = builder.makeInt8Constant(1);
6084 convOp = spv::OpSelect;
6085 break;
6086 case glslang::EOpConvBoolToUint8:
6087 zero = builder.makeUint8Constant(0);
6088 one = builder.makeUint8Constant(1);
6089 convOp = spv::OpSelect;
6090 break;
6091 case glslang::EOpConvBoolToInt16:
6092 zero = builder.makeInt16Constant(0);
6093 one = builder.makeInt16Constant(1);
6094 convOp = spv::OpSelect;
6095 break;
6096 case glslang::EOpConvBoolToUint16:
6097 zero = builder.makeUint16Constant(0);
6098 one = builder.makeUint16Constant(1);
6099 convOp = spv::OpSelect;
6100 break;
6101 case glslang::EOpConvDoubleToFloat:
6102 case glslang::EOpConvFloatToDouble:
6103 case glslang::EOpConvDoubleToFloat16:
6104 case glslang::EOpConvFloat16ToDouble:
6105 case glslang::EOpConvFloatToFloat16:
6106 case glslang::EOpConvFloat16ToFloat:
6107 convOp = spv::OpFConvert;
6108 if (builder.isMatrixType(destType))
6109 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6110 break;
6111
John Kessenich66011cb2018-03-06 16:12:04 -07006112 case glslang::EOpConvInt8ToInt16:
6113 case glslang::EOpConvInt8ToInt:
6114 case glslang::EOpConvInt8ToInt64:
6115 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006116 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006117 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006118 case glslang::EOpConvIntToInt8:
6119 case glslang::EOpConvIntToInt16:
6120 case glslang::EOpConvIntToInt64:
6121 case glslang::EOpConvInt64ToInt8:
6122 case glslang::EOpConvInt64ToInt16:
6123 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006124 convOp = spv::OpSConvert;
6125 break;
6126
John Kessenich66011cb2018-03-06 16:12:04 -07006127 case glslang::EOpConvUint8ToUint16:
6128 case glslang::EOpConvUint8ToUint:
6129 case glslang::EOpConvUint8ToUint64:
6130 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006131 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006132 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006133 case glslang::EOpConvUintToUint8:
6134 case glslang::EOpConvUintToUint16:
6135 case glslang::EOpConvUintToUint64:
6136 case glslang::EOpConvUint64ToUint8:
6137 case glslang::EOpConvUint64ToUint16:
6138 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006139 convOp = spv::OpUConvert;
6140 break;
6141
John Kessenich66011cb2018-03-06 16:12:04 -07006142 case glslang::EOpConvInt8ToUint16:
6143 case glslang::EOpConvInt8ToUint:
6144 case glslang::EOpConvInt8ToUint64:
6145 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006146 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006147 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006148 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006149 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006150 case glslang::EOpConvIntToUint64:
6151 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006152 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006153 case glslang::EOpConvInt64ToUint:
6154 case glslang::EOpConvUint8ToInt16:
6155 case glslang::EOpConvUint8ToInt:
6156 case glslang::EOpConvUint8ToInt64:
6157 case glslang::EOpConvUint16ToInt8:
6158 case glslang::EOpConvUint16ToInt:
6159 case glslang::EOpConvUint16ToInt64:
6160 case glslang::EOpConvUintToInt8:
6161 case glslang::EOpConvUintToInt16:
6162 case glslang::EOpConvUintToInt64:
6163 case glslang::EOpConvUint64ToInt8:
6164 case glslang::EOpConvUint64ToInt16:
6165 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006166 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006167 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006168
6169 if (builder.isInSpecConstCodeGenMode()) {
6170 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006171 switch(op) {
6172 case glslang::EOpConvInt16ToUint8:
6173 case glslang::EOpConvIntToUint8:
6174 case glslang::EOpConvInt64ToUint8:
6175 case glslang::EOpConvUint16ToInt8:
6176 case glslang::EOpConvUintToInt8:
6177 case glslang::EOpConvUint64ToInt8:
6178 zero = builder.makeUint8Constant(0);
6179 break;
6180 case glslang::EOpConvInt8ToUint16:
6181 case glslang::EOpConvIntToUint16:
6182 case glslang::EOpConvInt64ToUint16:
6183 case glslang::EOpConvUint8ToInt16:
6184 case glslang::EOpConvUintToInt16:
6185 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006186 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006187 break;
6188 case glslang::EOpConvInt8ToUint:
6189 case glslang::EOpConvInt16ToUint:
6190 case glslang::EOpConvInt64ToUint:
6191 case glslang::EOpConvUint8ToInt:
6192 case glslang::EOpConvUint16ToInt:
6193 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006194 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006195 break;
6196 case glslang::EOpConvInt8ToUint64:
6197 case glslang::EOpConvInt16ToUint64:
6198 case glslang::EOpConvIntToUint64:
6199 case glslang::EOpConvUint8ToInt64:
6200 case glslang::EOpConvUint16ToInt64:
6201 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006202 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006203 break;
6204 default:
6205 assert(false && "Default missing");
6206 break;
6207 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006208 zero = makeSmearedConstant(zero, vectorSize);
6209 // Use OpIAdd, instead of OpBitcast to do the conversion when
6210 // generating for OpSpecConstantOp instruction.
6211 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6212 }
6213 // For normal run-time conversion instruction, use OpBitcast.
6214 convOp = spv::OpBitcast;
6215 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006216 case glslang::EOpConvUint64ToPtr:
6217 convOp = spv::OpConvertUToPtr;
6218 break;
6219 case glslang::EOpConvPtrToUint64:
6220 convOp = spv::OpConvertPtrToU;
6221 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006222#endif
6223
John Kessenich140f3df2015-06-26 16:58:36 -06006224 default:
6225 break;
6226 }
6227
6228 spv::Id result = 0;
6229 if (convOp == spv::OpNop)
6230 return result;
6231
6232 if (convOp == spv::OpSelect) {
6233 zero = makeSmearedConstant(zero, vectorSize);
6234 one = makeSmearedConstant(one, vectorSize);
6235 result = builder.createTriOp(convOp, destType, operand, one, zero);
6236 } else
6237 result = builder.createUnaryOp(convOp, destType, operand);
6238
John Kessenichead86222018-03-28 18:01:20 -06006239 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006240 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006241 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006242}
6243
6244spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6245{
6246 if (vectorSize == 0)
6247 return constant;
6248
6249 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6250 std::vector<spv::Id> components;
6251 for (int c = 0; c < vectorSize; ++c)
6252 components.push_back(constant);
6253 return builder.makeCompositeConstant(vectorTypeId, components);
6254}
6255
John Kessenich426394d2015-07-23 10:22:48 -06006256// For glslang ops that map to SPV atomic opCodes
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006257spv::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 -06006258{
6259 spv::Op opCode = spv::OpNop;
6260
6261 switch (op) {
6262 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006263 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006264 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006265 opCode = spv::OpAtomicIAdd;
6266 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006267 case glslang::EOpAtomicCounterSubtract:
6268 opCode = spv::OpAtomicISub;
6269 break;
John Kessenich426394d2015-07-23 10:22:48 -06006270 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006271 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006272 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006273 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006274 break;
6275 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006276 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006277 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006278 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006279 break;
6280 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006281 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006282 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006283 opCode = spv::OpAtomicAnd;
6284 break;
6285 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006286 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006287 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006288 opCode = spv::OpAtomicOr;
6289 break;
6290 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006291 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006292 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006293 opCode = spv::OpAtomicXor;
6294 break;
6295 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006296 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006297 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006298 opCode = spv::OpAtomicExchange;
6299 break;
6300 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006301 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006302 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006303 opCode = spv::OpAtomicCompareExchange;
6304 break;
6305 case glslang::EOpAtomicCounterIncrement:
6306 opCode = spv::OpAtomicIIncrement;
6307 break;
6308 case glslang::EOpAtomicCounterDecrement:
6309 opCode = spv::OpAtomicIDecrement;
6310 break;
6311 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006312 case glslang::EOpImageAtomicLoad:
6313 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006314 opCode = spv::OpAtomicLoad;
6315 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006316 case glslang::EOpAtomicStore:
6317 case glslang::EOpImageAtomicStore:
6318 opCode = spv::OpAtomicStore;
6319 break;
John Kessenich426394d2015-07-23 10:22:48 -06006320 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006321 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006322 break;
6323 }
6324
Rex Xue8fe8b02017-09-26 15:42:56 +08006325 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6326 builder.addCapability(spv::CapabilityInt64Atomics);
6327
John Kessenich426394d2015-07-23 10:22:48 -06006328 // Sort out the operands
6329 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006330 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006331 // - compare-exchange swaps the value and comparator
6332 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006333 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006334 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6335 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6336 spv::Id scopeId;
6337 if (glslangIntermediate->usingVulkanMemoryModel()) {
6338 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6339 } else {
6340 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6341 }
6342 // semantics default to relaxed
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006343 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.volatil ? spv::MemorySemanticsVolatileMask : spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006344 spv::Id semanticsId2 = semanticsId;
6345
6346 pointerId = operands[0];
6347 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6348 // no additional operands
6349 } else if (opCode == spv::OpAtomicCompareExchange) {
6350 compareId = operands[1];
6351 valueId = operands[2];
6352 if (operands.size() > 3) {
6353 scopeId = operands[3];
6354 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6355 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6356 }
6357 } else if (opCode == spv::OpAtomicLoad) {
6358 if (operands.size() > 1) {
6359 scopeId = operands[1];
6360 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6361 }
6362 } else {
6363 // atomic store or RMW
6364 valueId = operands[1];
6365 if (operands.size() > 2) {
6366 scopeId = operands[2];
6367 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6368 }
Rex Xu04db3f52015-09-16 11:44:02 +08006369 }
John Kessenich426394d2015-07-23 10:22:48 -06006370
Jeff Bolz36831c92018-09-05 10:11:41 -05006371 // Check for capabilities
6372 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006373 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6374 spv::MemorySemanticsMakeVisibleKHRMask |
6375 spv::MemorySemanticsOutputMemoryKHRMask |
6376 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006377 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6378 }
John Kessenich426394d2015-07-23 10:22:48 -06006379
Jeff Bolz36831c92018-09-05 10:11:41 -05006380 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6381 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6382 }
John Kessenich48d6e792017-10-06 21:21:48 -06006383
Jeff Bolz36831c92018-09-05 10:11:41 -05006384 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6385 spvAtomicOperands.push_back(pointerId);
6386 spvAtomicOperands.push_back(scopeId);
6387 spvAtomicOperands.push_back(semanticsId);
6388 if (opCode == spv::OpAtomicCompareExchange) {
6389 spvAtomicOperands.push_back(semanticsId2);
6390 spvAtomicOperands.push_back(valueId);
6391 spvAtomicOperands.push_back(compareId);
6392 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6393 spvAtomicOperands.push_back(valueId);
6394 }
John Kessenich48d6e792017-10-06 21:21:48 -06006395
Jeff Bolz36831c92018-09-05 10:11:41 -05006396 if (opCode == spv::OpAtomicStore) {
6397 builder.createNoResultOp(opCode, spvAtomicOperands);
6398 return 0;
6399 } else {
6400 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6401
6402 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6403 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6404 if (op == glslang::EOpAtomicCounterDecrement)
6405 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6406
6407 return resultId;
6408 }
John Kessenich426394d2015-07-23 10:22:48 -06006409}
6410
John Kessenich91cef522016-05-05 16:45:40 -06006411// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006412spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006413{
John Kessenich66011cb2018-03-06 16:12:04 -07006414 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6415 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006416
Rex Xu51596642016-09-21 18:56:12 +08006417 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006418 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006419 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6420
chaocf200da82016-12-20 12:44:35 -08006421 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6422 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006423 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6424 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006425 } else if (op == glslang::EOpAnyInvocation ||
6426 op == glslang::EOpAllInvocations ||
6427 op == glslang::EOpAllInvocationsEqual) {
6428 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6429 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006430 } else {
6431 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006432 if (op == glslang::EOpMinInvocationsNonUniform ||
6433 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006434 op == glslang::EOpAddInvocationsNonUniform ||
6435 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6436 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6437 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6438 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6439 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6440 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006441 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006442
Rex Xu430ef402016-10-14 17:22:23 +08006443 switch (op) {
6444 case glslang::EOpMinInvocations:
6445 case glslang::EOpMaxInvocations:
6446 case glslang::EOpAddInvocations:
6447 case glslang::EOpMinInvocationsNonUniform:
6448 case glslang::EOpMaxInvocationsNonUniform:
6449 case glslang::EOpAddInvocationsNonUniform:
6450 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006451 break;
6452 case glslang::EOpMinInvocationsInclusiveScan:
6453 case glslang::EOpMaxInvocationsInclusiveScan:
6454 case glslang::EOpAddInvocationsInclusiveScan:
6455 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6456 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6457 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6458 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006459 break;
6460 case glslang::EOpMinInvocationsExclusiveScan:
6461 case glslang::EOpMaxInvocationsExclusiveScan:
6462 case glslang::EOpAddInvocationsExclusiveScan:
6463 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6464 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6465 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6466 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006467 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006468 default:
6469 break;
Rex Xu430ef402016-10-14 17:22:23 +08006470 }
John Kessenich149afc32018-08-14 13:31:43 -06006471 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6472 spvGroupOperands.push_back(scope);
6473 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006474 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006475 spvGroupOperands.push_back(groupOp);
6476 }
Rex Xu51596642016-09-21 18:56:12 +08006477 }
6478
John Kessenich149afc32018-08-14 13:31:43 -06006479 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6480 spv::IdImmediate op = { true, *opIt };
6481 spvGroupOperands.push_back(op);
6482 }
John Kessenich91cef522016-05-05 16:45:40 -06006483
6484 switch (op) {
6485 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006486 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006487 break;
John Kessenich91cef522016-05-05 16:45:40 -06006488 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006489 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006490 break;
John Kessenich91cef522016-05-05 16:45:40 -06006491 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006492 opCode = spv::OpSubgroupAllEqualKHR;
6493 break;
Rex Xu51596642016-09-21 18:56:12 +08006494 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006495 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006496 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006497 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006498 break;
6499 case glslang::EOpReadFirstInvocation:
6500 opCode = spv::OpSubgroupFirstInvocationKHR;
6501 break;
6502 case glslang::EOpBallot:
6503 {
6504 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6505 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6506 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6507 //
6508 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6509 //
6510 spv::Id uintType = builder.makeUintType(32);
6511 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6512 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6513
6514 std::vector<spv::Id> components;
6515 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6516 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6517
6518 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6519 return builder.createUnaryOp(spv::OpBitcast, typeId,
6520 builder.createCompositeConstruct(uvec2Type, components));
6521 }
6522
Rex Xu9d93a232016-05-05 12:30:44 +08006523 case glslang::EOpMinInvocations:
6524 case glslang::EOpMaxInvocations:
6525 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006526 case glslang::EOpMinInvocationsInclusiveScan:
6527 case glslang::EOpMaxInvocationsInclusiveScan:
6528 case glslang::EOpAddInvocationsInclusiveScan:
6529 case glslang::EOpMinInvocationsExclusiveScan:
6530 case glslang::EOpMaxInvocationsExclusiveScan:
6531 case glslang::EOpAddInvocationsExclusiveScan:
6532 if (op == glslang::EOpMinInvocations ||
6533 op == glslang::EOpMinInvocationsInclusiveScan ||
6534 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006535 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006536 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006537 else {
6538 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006539 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006540 else
Rex Xu51596642016-09-21 18:56:12 +08006541 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006542 }
Rex Xu430ef402016-10-14 17:22:23 +08006543 } else if (op == glslang::EOpMaxInvocations ||
6544 op == glslang::EOpMaxInvocationsInclusiveScan ||
6545 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006546 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006547 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006548 else {
6549 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006550 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006551 else
Rex Xu51596642016-09-21 18:56:12 +08006552 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006553 }
6554 } else {
6555 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006556 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006557 else
Rex Xu51596642016-09-21 18:56:12 +08006558 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006559 }
6560
Rex Xu2bbbe062016-08-23 15:41:05 +08006561 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006562 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006563
6564 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006565 case glslang::EOpMinInvocationsNonUniform:
6566 case glslang::EOpMaxInvocationsNonUniform:
6567 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006568 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6569 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6570 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6571 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6572 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6573 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6574 if (op == glslang::EOpMinInvocationsNonUniform ||
6575 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6576 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006577 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006578 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006579 else {
6580 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006581 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006582 else
Rex Xu51596642016-09-21 18:56:12 +08006583 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006584 }
6585 }
Rex Xu430ef402016-10-14 17:22:23 +08006586 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6587 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6588 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006589 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006590 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006591 else {
6592 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006593 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006594 else
Rex Xu51596642016-09-21 18:56:12 +08006595 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006596 }
6597 }
6598 else {
6599 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006600 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006601 else
Rex Xu51596642016-09-21 18:56:12 +08006602 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006603 }
6604
Rex Xu2bbbe062016-08-23 15:41:05 +08006605 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006606 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006607
6608 break;
John Kessenich91cef522016-05-05 16:45:40 -06006609 default:
6610 logger->missingFunctionality("invocation operation");
6611 return spv::NoResult;
6612 }
Rex Xu51596642016-09-21 18:56:12 +08006613
6614 assert(opCode != spv::OpNop);
6615 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006616}
6617
Rex Xu2bbbe062016-08-23 15:41:05 +08006618// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006619spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6620 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006621{
6622 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6623 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006624 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006625 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006626 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6627 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6628 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
6629
6630 // Handle group invocation operations scalar by scalar.
6631 // The result type is the same type as the original type.
6632 // The algorithm is to:
6633 // - break the vector into scalars
6634 // - apply the operation to each scalar
6635 // - make a vector out the scalar results
6636
6637 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006638 int numComponents = builder.getNumComponents(operands[0]);
6639 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006640 std::vector<spv::Id> results;
6641
6642 // do each scalar op
6643 for (int comp = 0; comp < numComponents; ++comp) {
6644 std::vector<unsigned int> indexes;
6645 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006646 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6647 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006648 if (op == spv::OpSubgroupReadInvocationKHR) {
6649 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006650 spv::IdImmediate operand = { true, operands[1] };
6651 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006652 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006653 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6654 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006655 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006656 spv::IdImmediate operand = { true, operands[1] };
6657 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006658 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006659 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6660 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006661 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006662 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006663 spvGroupOperands.push_back(scalar);
6664 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006665
Rex Xub7072052016-09-26 15:53:40 +08006666 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006667 }
6668
6669 // put the pieces together
6670 return builder.createCompositeConstruct(typeId, results);
6671}
Rex Xu2bbbe062016-08-23 15:41:05 +08006672
John Kessenich66011cb2018-03-06 16:12:04 -07006673// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006674spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6675 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006676{
6677 // Add the required capabilities.
6678 switch (op) {
6679 case glslang::EOpSubgroupElect:
6680 builder.addCapability(spv::CapabilityGroupNonUniform);
6681 break;
6682 case glslang::EOpSubgroupAll:
6683 case glslang::EOpSubgroupAny:
6684 case glslang::EOpSubgroupAllEqual:
6685 builder.addCapability(spv::CapabilityGroupNonUniform);
6686 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6687 break;
6688 case glslang::EOpSubgroupBroadcast:
6689 case glslang::EOpSubgroupBroadcastFirst:
6690 case glslang::EOpSubgroupBallot:
6691 case glslang::EOpSubgroupInverseBallot:
6692 case glslang::EOpSubgroupBallotBitExtract:
6693 case glslang::EOpSubgroupBallotBitCount:
6694 case glslang::EOpSubgroupBallotInclusiveBitCount:
6695 case glslang::EOpSubgroupBallotExclusiveBitCount:
6696 case glslang::EOpSubgroupBallotFindLSB:
6697 case glslang::EOpSubgroupBallotFindMSB:
6698 builder.addCapability(spv::CapabilityGroupNonUniform);
6699 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6700 break;
6701 case glslang::EOpSubgroupShuffle:
6702 case glslang::EOpSubgroupShuffleXor:
6703 builder.addCapability(spv::CapabilityGroupNonUniform);
6704 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6705 break;
6706 case glslang::EOpSubgroupShuffleUp:
6707 case glslang::EOpSubgroupShuffleDown:
6708 builder.addCapability(spv::CapabilityGroupNonUniform);
6709 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6710 break;
6711 case glslang::EOpSubgroupAdd:
6712 case glslang::EOpSubgroupMul:
6713 case glslang::EOpSubgroupMin:
6714 case glslang::EOpSubgroupMax:
6715 case glslang::EOpSubgroupAnd:
6716 case glslang::EOpSubgroupOr:
6717 case glslang::EOpSubgroupXor:
6718 case glslang::EOpSubgroupInclusiveAdd:
6719 case glslang::EOpSubgroupInclusiveMul:
6720 case glslang::EOpSubgroupInclusiveMin:
6721 case glslang::EOpSubgroupInclusiveMax:
6722 case glslang::EOpSubgroupInclusiveAnd:
6723 case glslang::EOpSubgroupInclusiveOr:
6724 case glslang::EOpSubgroupInclusiveXor:
6725 case glslang::EOpSubgroupExclusiveAdd:
6726 case glslang::EOpSubgroupExclusiveMul:
6727 case glslang::EOpSubgroupExclusiveMin:
6728 case glslang::EOpSubgroupExclusiveMax:
6729 case glslang::EOpSubgroupExclusiveAnd:
6730 case glslang::EOpSubgroupExclusiveOr:
6731 case glslang::EOpSubgroupExclusiveXor:
6732 builder.addCapability(spv::CapabilityGroupNonUniform);
6733 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6734 break;
6735 case glslang::EOpSubgroupClusteredAdd:
6736 case glslang::EOpSubgroupClusteredMul:
6737 case glslang::EOpSubgroupClusteredMin:
6738 case glslang::EOpSubgroupClusteredMax:
6739 case glslang::EOpSubgroupClusteredAnd:
6740 case glslang::EOpSubgroupClusteredOr:
6741 case glslang::EOpSubgroupClusteredXor:
6742 builder.addCapability(spv::CapabilityGroupNonUniform);
6743 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6744 break;
6745 case glslang::EOpSubgroupQuadBroadcast:
6746 case glslang::EOpSubgroupQuadSwapHorizontal:
6747 case glslang::EOpSubgroupQuadSwapVertical:
6748 case glslang::EOpSubgroupQuadSwapDiagonal:
6749 builder.addCapability(spv::CapabilityGroupNonUniform);
6750 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6751 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006752 case glslang::EOpSubgroupPartitionedAdd:
6753 case glslang::EOpSubgroupPartitionedMul:
6754 case glslang::EOpSubgroupPartitionedMin:
6755 case glslang::EOpSubgroupPartitionedMax:
6756 case glslang::EOpSubgroupPartitionedAnd:
6757 case glslang::EOpSubgroupPartitionedOr:
6758 case glslang::EOpSubgroupPartitionedXor:
6759 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6760 case glslang::EOpSubgroupPartitionedInclusiveMul:
6761 case glslang::EOpSubgroupPartitionedInclusiveMin:
6762 case glslang::EOpSubgroupPartitionedInclusiveMax:
6763 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6764 case glslang::EOpSubgroupPartitionedInclusiveOr:
6765 case glslang::EOpSubgroupPartitionedInclusiveXor:
6766 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6767 case glslang::EOpSubgroupPartitionedExclusiveMul:
6768 case glslang::EOpSubgroupPartitionedExclusiveMin:
6769 case glslang::EOpSubgroupPartitionedExclusiveMax:
6770 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6771 case glslang::EOpSubgroupPartitionedExclusiveOr:
6772 case glslang::EOpSubgroupPartitionedExclusiveXor:
6773 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6774 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6775 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006776 default: assert(0 && "Unhandled subgroup operation!");
6777 }
6778
6779 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6780 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6781 const bool isBool = typeProxy == glslang::EbtBool;
6782
6783 spv::Op opCode = spv::OpNop;
6784
6785 // Figure out which opcode to use.
6786 switch (op) {
6787 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6788 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6789 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6790 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6791 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6792 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6793 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6794 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6795 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6796 case glslang::EOpSubgroupBallotBitCount:
6797 case glslang::EOpSubgroupBallotInclusiveBitCount:
6798 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6799 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6800 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6801 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6802 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6803 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6804 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6805 case glslang::EOpSubgroupAdd:
6806 case glslang::EOpSubgroupInclusiveAdd:
6807 case glslang::EOpSubgroupExclusiveAdd:
6808 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006809 case glslang::EOpSubgroupPartitionedAdd:
6810 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6811 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07006812 if (isFloat) {
6813 opCode = spv::OpGroupNonUniformFAdd;
6814 } else {
6815 opCode = spv::OpGroupNonUniformIAdd;
6816 }
6817 break;
6818 case glslang::EOpSubgroupMul:
6819 case glslang::EOpSubgroupInclusiveMul:
6820 case glslang::EOpSubgroupExclusiveMul:
6821 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006822 case glslang::EOpSubgroupPartitionedMul:
6823 case glslang::EOpSubgroupPartitionedInclusiveMul:
6824 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07006825 if (isFloat) {
6826 opCode = spv::OpGroupNonUniformFMul;
6827 } else {
6828 opCode = spv::OpGroupNonUniformIMul;
6829 }
6830 break;
6831 case glslang::EOpSubgroupMin:
6832 case glslang::EOpSubgroupInclusiveMin:
6833 case glslang::EOpSubgroupExclusiveMin:
6834 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006835 case glslang::EOpSubgroupPartitionedMin:
6836 case glslang::EOpSubgroupPartitionedInclusiveMin:
6837 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07006838 if (isFloat) {
6839 opCode = spv::OpGroupNonUniformFMin;
6840 } else if (isUnsigned) {
6841 opCode = spv::OpGroupNonUniformUMin;
6842 } else {
6843 opCode = spv::OpGroupNonUniformSMin;
6844 }
6845 break;
6846 case glslang::EOpSubgroupMax:
6847 case glslang::EOpSubgroupInclusiveMax:
6848 case glslang::EOpSubgroupExclusiveMax:
6849 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006850 case glslang::EOpSubgroupPartitionedMax:
6851 case glslang::EOpSubgroupPartitionedInclusiveMax:
6852 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07006853 if (isFloat) {
6854 opCode = spv::OpGroupNonUniformFMax;
6855 } else if (isUnsigned) {
6856 opCode = spv::OpGroupNonUniformUMax;
6857 } else {
6858 opCode = spv::OpGroupNonUniformSMax;
6859 }
6860 break;
6861 case glslang::EOpSubgroupAnd:
6862 case glslang::EOpSubgroupInclusiveAnd:
6863 case glslang::EOpSubgroupExclusiveAnd:
6864 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006865 case glslang::EOpSubgroupPartitionedAnd:
6866 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6867 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07006868 if (isBool) {
6869 opCode = spv::OpGroupNonUniformLogicalAnd;
6870 } else {
6871 opCode = spv::OpGroupNonUniformBitwiseAnd;
6872 }
6873 break;
6874 case glslang::EOpSubgroupOr:
6875 case glslang::EOpSubgroupInclusiveOr:
6876 case glslang::EOpSubgroupExclusiveOr:
6877 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006878 case glslang::EOpSubgroupPartitionedOr:
6879 case glslang::EOpSubgroupPartitionedInclusiveOr:
6880 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07006881 if (isBool) {
6882 opCode = spv::OpGroupNonUniformLogicalOr;
6883 } else {
6884 opCode = spv::OpGroupNonUniformBitwiseOr;
6885 }
6886 break;
6887 case glslang::EOpSubgroupXor:
6888 case glslang::EOpSubgroupInclusiveXor:
6889 case glslang::EOpSubgroupExclusiveXor:
6890 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006891 case glslang::EOpSubgroupPartitionedXor:
6892 case glslang::EOpSubgroupPartitionedInclusiveXor:
6893 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07006894 if (isBool) {
6895 opCode = spv::OpGroupNonUniformLogicalXor;
6896 } else {
6897 opCode = spv::OpGroupNonUniformBitwiseXor;
6898 }
6899 break;
6900 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6901 case glslang::EOpSubgroupQuadSwapHorizontal:
6902 case glslang::EOpSubgroupQuadSwapVertical:
6903 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6904 default: assert(0 && "Unhandled subgroup operation!");
6905 }
6906
John Kessenich149afc32018-08-14 13:31:43 -06006907 // get the right Group Operation
6908 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006909 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006910 default:
6911 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006912 case glslang::EOpSubgroupBallotBitCount:
6913 case glslang::EOpSubgroupAdd:
6914 case glslang::EOpSubgroupMul:
6915 case glslang::EOpSubgroupMin:
6916 case glslang::EOpSubgroupMax:
6917 case glslang::EOpSubgroupAnd:
6918 case glslang::EOpSubgroupOr:
6919 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006920 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006921 break;
6922 case glslang::EOpSubgroupBallotInclusiveBitCount:
6923 case glslang::EOpSubgroupInclusiveAdd:
6924 case glslang::EOpSubgroupInclusiveMul:
6925 case glslang::EOpSubgroupInclusiveMin:
6926 case glslang::EOpSubgroupInclusiveMax:
6927 case glslang::EOpSubgroupInclusiveAnd:
6928 case glslang::EOpSubgroupInclusiveOr:
6929 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006930 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006931 break;
6932 case glslang::EOpSubgroupBallotExclusiveBitCount:
6933 case glslang::EOpSubgroupExclusiveAdd:
6934 case glslang::EOpSubgroupExclusiveMul:
6935 case glslang::EOpSubgroupExclusiveMin:
6936 case glslang::EOpSubgroupExclusiveMax:
6937 case glslang::EOpSubgroupExclusiveAnd:
6938 case glslang::EOpSubgroupExclusiveOr:
6939 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006940 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006941 break;
6942 case glslang::EOpSubgroupClusteredAdd:
6943 case glslang::EOpSubgroupClusteredMul:
6944 case glslang::EOpSubgroupClusteredMin:
6945 case glslang::EOpSubgroupClusteredMax:
6946 case glslang::EOpSubgroupClusteredAnd:
6947 case glslang::EOpSubgroupClusteredOr:
6948 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006949 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006950 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006951 case glslang::EOpSubgroupPartitionedAdd:
6952 case glslang::EOpSubgroupPartitionedMul:
6953 case glslang::EOpSubgroupPartitionedMin:
6954 case glslang::EOpSubgroupPartitionedMax:
6955 case glslang::EOpSubgroupPartitionedAnd:
6956 case glslang::EOpSubgroupPartitionedOr:
6957 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006958 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006959 break;
6960 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6961 case glslang::EOpSubgroupPartitionedInclusiveMul:
6962 case glslang::EOpSubgroupPartitionedInclusiveMin:
6963 case glslang::EOpSubgroupPartitionedInclusiveMax:
6964 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6965 case glslang::EOpSubgroupPartitionedInclusiveOr:
6966 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006967 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006968 break;
6969 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6970 case glslang::EOpSubgroupPartitionedExclusiveMul:
6971 case glslang::EOpSubgroupPartitionedExclusiveMin:
6972 case glslang::EOpSubgroupPartitionedExclusiveMax:
6973 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6974 case glslang::EOpSubgroupPartitionedExclusiveOr:
6975 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006976 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006977 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006978 }
6979
John Kessenich149afc32018-08-14 13:31:43 -06006980 // build the instruction
6981 std::vector<spv::IdImmediate> spvGroupOperands;
6982
6983 // Every operation begins with the Execution Scope operand.
6984 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6985 spvGroupOperands.push_back(executionScope);
6986
6987 // Next, for all operations that use a Group Operation, push that as an operand.
6988 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006989 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006990 spvGroupOperands.push_back(groupOperand);
6991 }
6992
John Kessenich66011cb2018-03-06 16:12:04 -07006993 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006994 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6995 spv::IdImmediate operand = { true, *opIt };
6996 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006997 }
6998
6999 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007000 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007001 switch (op) {
7002 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007003 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7004 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7005 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7006 }
7007 if (directionId != spv::NoResult) {
7008 spv::IdImmediate direction = { true, directionId };
7009 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007010 }
7011
7012 return builder.createOp(opCode, typeId, spvGroupOperands);
7013}
7014
John Kessenich5e4b1242015-08-06 22:53:06 -06007015spv::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 -06007016{
John Kessenich66011cb2018-03-06 16:12:04 -07007017 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7018 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007019
John Kessenich140f3df2015-06-26 16:58:36 -06007020 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007021 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007022 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007023 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007024 spv::Id typeId0 = 0;
7025 if (consumedOperands > 0)
7026 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007027 spv::Id typeId1 = 0;
7028 if (consumedOperands > 1)
7029 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007030 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007031
7032 switch (op) {
7033 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007034 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007035 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007036 else if (isUnsigned)
7037 libCall = spv::GLSLstd450UMin;
7038 else
7039 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007040 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007041 break;
7042 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007043 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007044 break;
7045 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007046 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007047 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007048 else if (isUnsigned)
7049 libCall = spv::GLSLstd450UMax;
7050 else
7051 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007052 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007053 break;
7054 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007055 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007056 break;
7057 case glslang::EOpDot:
7058 opCode = spv::OpDot;
7059 break;
7060 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007061 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007062 break;
7063
7064 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007065 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007066 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007067 else if (isUnsigned)
7068 libCall = spv::GLSLstd450UClamp;
7069 else
7070 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007071 builder.promoteScalar(precision, operands.front(), operands[1]);
7072 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007073 break;
7074 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007075 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7076 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007077 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007078 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007079 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007080 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007081 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007082 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007083 break;
7084 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007085 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007086 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007087 break;
7088 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007089 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007090 builder.promoteScalar(precision, operands[0], operands[2]);
7091 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007092 break;
7093
7094 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007095 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007096 break;
7097 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007098 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007099 break;
7100 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007101 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007102 break;
7103 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007104 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007105 break;
7106 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007107 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007108 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007109#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007110 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007111 if (typeProxy == glslang::EbtFloat16)
7112 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007113 libCall = spv::GLSLstd450InterpolateAtSample;
7114 break;
7115 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007116 if (typeProxy == glslang::EbtFloat16)
7117 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007118 libCall = spv::GLSLstd450InterpolateAtOffset;
7119 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007120 case glslang::EOpAddCarry:
7121 opCode = spv::OpIAddCarry;
7122 typeId = builder.makeStructResultType(typeId0, typeId0);
7123 consumedOperands = 2;
7124 break;
7125 case glslang::EOpSubBorrow:
7126 opCode = spv::OpISubBorrow;
7127 typeId = builder.makeStructResultType(typeId0, typeId0);
7128 consumedOperands = 2;
7129 break;
7130 case glslang::EOpUMulExtended:
7131 opCode = spv::OpUMulExtended;
7132 typeId = builder.makeStructResultType(typeId0, typeId0);
7133 consumedOperands = 2;
7134 break;
7135 case glslang::EOpIMulExtended:
7136 opCode = spv::OpSMulExtended;
7137 typeId = builder.makeStructResultType(typeId0, typeId0);
7138 consumedOperands = 2;
7139 break;
7140 case glslang::EOpBitfieldExtract:
7141 if (isUnsigned)
7142 opCode = spv::OpBitFieldUExtract;
7143 else
7144 opCode = spv::OpBitFieldSExtract;
7145 break;
7146 case glslang::EOpBitfieldInsert:
7147 opCode = spv::OpBitFieldInsert;
7148 break;
7149
7150 case glslang::EOpFma:
7151 libCall = spv::GLSLstd450Fma;
7152 break;
7153 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007154 {
7155 libCall = spv::GLSLstd450FrexpStruct;
7156 assert(builder.isPointerType(typeId1));
7157 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007158 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007159 if (width == 16)
7160 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7161 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007162 if (builder.getNumComponents(operands[0]) == 1)
7163 frexpIntType = builder.makeIntegerType(width, true);
7164 else
7165 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7166 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7167 consumedOperands = 1;
7168 }
John Kessenich55e7d112015-11-15 21:33:39 -07007169 break;
7170 case glslang::EOpLdexp:
7171 libCall = spv::GLSLstd450Ldexp;
7172 break;
7173
Rex Xu574ab042016-04-14 16:53:07 +08007174 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007175 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007176
John Kessenich66011cb2018-03-06 16:12:04 -07007177 case glslang::EOpSubgroupBroadcast:
7178 case glslang::EOpSubgroupBallotBitExtract:
7179 case glslang::EOpSubgroupShuffle:
7180 case glslang::EOpSubgroupShuffleXor:
7181 case glslang::EOpSubgroupShuffleUp:
7182 case glslang::EOpSubgroupShuffleDown:
7183 case glslang::EOpSubgroupClusteredAdd:
7184 case glslang::EOpSubgroupClusteredMul:
7185 case glslang::EOpSubgroupClusteredMin:
7186 case glslang::EOpSubgroupClusteredMax:
7187 case glslang::EOpSubgroupClusteredAnd:
7188 case glslang::EOpSubgroupClusteredOr:
7189 case glslang::EOpSubgroupClusteredXor:
7190 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007191 case glslang::EOpSubgroupPartitionedAdd:
7192 case glslang::EOpSubgroupPartitionedMul:
7193 case glslang::EOpSubgroupPartitionedMin:
7194 case glslang::EOpSubgroupPartitionedMax:
7195 case glslang::EOpSubgroupPartitionedAnd:
7196 case glslang::EOpSubgroupPartitionedOr:
7197 case glslang::EOpSubgroupPartitionedXor:
7198 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7199 case glslang::EOpSubgroupPartitionedInclusiveMul:
7200 case glslang::EOpSubgroupPartitionedInclusiveMin:
7201 case glslang::EOpSubgroupPartitionedInclusiveMax:
7202 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7203 case glslang::EOpSubgroupPartitionedInclusiveOr:
7204 case glslang::EOpSubgroupPartitionedInclusiveXor:
7205 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7206 case glslang::EOpSubgroupPartitionedExclusiveMul:
7207 case glslang::EOpSubgroupPartitionedExclusiveMin:
7208 case glslang::EOpSubgroupPartitionedExclusiveMax:
7209 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7210 case glslang::EOpSubgroupPartitionedExclusiveOr:
7211 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007212 return createSubgroupOperation(op, typeId, operands, typeProxy);
7213
Rex Xu9d93a232016-05-05 12:30:44 +08007214 case glslang::EOpSwizzleInvocations:
7215 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7216 libCall = spv::SwizzleInvocationsAMD;
7217 break;
7218 case glslang::EOpSwizzleInvocationsMasked:
7219 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7220 libCall = spv::SwizzleInvocationsMaskedAMD;
7221 break;
7222 case glslang::EOpWriteInvocation:
7223 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7224 libCall = spv::WriteInvocationAMD;
7225 break;
7226
7227 case glslang::EOpMin3:
7228 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7229 if (isFloat)
7230 libCall = spv::FMin3AMD;
7231 else {
7232 if (isUnsigned)
7233 libCall = spv::UMin3AMD;
7234 else
7235 libCall = spv::SMin3AMD;
7236 }
7237 break;
7238 case glslang::EOpMax3:
7239 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7240 if (isFloat)
7241 libCall = spv::FMax3AMD;
7242 else {
7243 if (isUnsigned)
7244 libCall = spv::UMax3AMD;
7245 else
7246 libCall = spv::SMax3AMD;
7247 }
7248 break;
7249 case glslang::EOpMid3:
7250 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7251 if (isFloat)
7252 libCall = spv::FMid3AMD;
7253 else {
7254 if (isUnsigned)
7255 libCall = spv::UMid3AMD;
7256 else
7257 libCall = spv::SMid3AMD;
7258 }
7259 break;
7260
7261 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007262 if (typeProxy == glslang::EbtFloat16)
7263 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007264 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7265 libCall = spv::InterpolateAtVertexAMD;
7266 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05007267 case glslang::EOpBarrier:
7268 {
7269 // This is for the extended controlBarrier function, with four operands.
7270 // The unextended barrier() goes through createNoArgOperation.
7271 assert(operands.size() == 4);
7272 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7273 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7274 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7275 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007276 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7277 spv::MemorySemanticsMakeVisibleKHRMask |
7278 spv::MemorySemanticsOutputMemoryKHRMask |
7279 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007280 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7281 }
7282 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7283 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7284 }
7285 return 0;
7286 }
7287 break;
7288 case glslang::EOpMemoryBarrier:
7289 {
7290 // This is for the extended memoryBarrier function, with three operands.
7291 // The unextended memoryBarrier() goes through createNoArgOperation.
7292 assert(operands.size() == 3);
7293 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7294 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7295 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007296 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7297 spv::MemorySemanticsMakeVisibleKHRMask |
7298 spv::MemorySemanticsOutputMemoryKHRMask |
7299 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007300 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7301 }
7302 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7303 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7304 }
7305 return 0;
7306 }
7307 break;
Chao Chen3c366992018-09-19 11:41:59 -07007308
Chao Chenb50c02e2018-09-19 11:42:24 -07007309 case glslang::EOpReportIntersectionNV:
7310 {
7311 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007312 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007313 }
7314 break;
7315 case glslang::EOpTraceNV:
7316 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007317 builder.createNoResultOp(spv::OpTraceNV, operands);
7318 return 0;
7319 }
7320 break;
7321 case glslang::EOpExecuteCallableNV:
7322 {
7323 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007324 return 0;
7325 }
7326 break;
Chao Chen3c366992018-09-19 11:41:59 -07007327 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7328 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7329 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007330 case glslang::EOpCooperativeMatrixMulAdd:
7331 opCode = spv::OpCooperativeMatrixMulAddNV;
7332 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007333#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007334 default:
7335 return 0;
7336 }
7337
7338 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007339 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007340 // Use an extended instruction from the standard library.
7341 // Construct the call arguments, without modifying the original operands vector.
7342 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7343 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007344 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007345 } else if (opCode == spv::OpDot && !isFloat) {
7346 // int dot(int, int)
7347 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7348 const int componentCount = builder.getNumComponents(operands[0]);
7349 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7350 builder.setPrecision(mulOp, precision);
7351 id = builder.createCompositeExtract(mulOp, typeId, 0);
7352 for (int i = 1; i < componentCount; ++i) {
7353 builder.setPrecision(id, precision);
7354 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7355 }
John Kessenich2359bd02015-12-06 19:29:11 -07007356 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007357 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007358 case 0:
7359 // should all be handled by visitAggregate and createNoArgOperation
7360 assert(0);
7361 return 0;
7362 case 1:
7363 // should all be handled by createUnaryOperation
7364 assert(0);
7365 return 0;
7366 case 2:
7367 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7368 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007369 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007370 // anything 3 or over doesn't have l-value operands, so all should be consumed
7371 assert(consumedOperands == operands.size());
7372 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007373 break;
7374 }
7375 }
7376
John Kessenich55e7d112015-11-15 21:33:39 -07007377 // Decode the return types that were structures
7378 switch (op) {
7379 case glslang::EOpAddCarry:
7380 case glslang::EOpSubBorrow:
7381 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7382 id = builder.createCompositeExtract(id, typeId0, 0);
7383 break;
7384 case glslang::EOpUMulExtended:
7385 case glslang::EOpIMulExtended:
7386 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7387 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7388 break;
7389 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007390 {
7391 assert(operands.size() == 2);
7392 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7393 // "exp" is floating-point type (from HLSL intrinsic)
7394 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7395 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7396 builder.createStore(member1, operands[1]);
7397 } else
7398 // "exp" is integer type (from GLSL built-in function)
7399 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7400 id = builder.createCompositeExtract(id, typeId0, 0);
7401 }
John Kessenich55e7d112015-11-15 21:33:39 -07007402 break;
7403 default:
7404 break;
7405 }
7406
John Kessenich32cfd492016-02-02 12:37:46 -07007407 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007408}
7409
Rex Xu9d93a232016-05-05 12:30:44 +08007410// Intrinsics with no arguments (or no return value, and no precision).
7411spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007412{
John Kessenich155d3512019-08-08 23:29:20 -06007413#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05007414 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7415 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007416
7417 switch (op) {
7418 case glslang::EOpEmitVertex:
7419 builder.createNoResultOp(spv::OpEmitVertex);
7420 return 0;
7421 case glslang::EOpEndPrimitive:
7422 builder.createNoResultOp(spv::OpEndPrimitive);
7423 return 0;
7424 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007425 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007426 if (glslangIntermediate->usingVulkanMemoryModel()) {
7427 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7428 spv::MemorySemanticsOutputMemoryKHRMask |
7429 spv::MemorySemanticsAcquireReleaseMask);
7430 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7431 } else {
7432 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7433 }
John Kessenich82979362017-12-11 04:02:24 -07007434 } else {
7435 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7436 spv::MemorySemanticsWorkgroupMemoryMask |
7437 spv::MemorySemanticsAcquireReleaseMask);
7438 }
John Kessenich140f3df2015-06-26 16:58:36 -06007439 return 0;
7440 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007441 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7442 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007443 return 0;
7444 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007445 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7446 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007447 return 0;
7448 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007449 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7450 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007451 return 0;
7452 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007453 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7454 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007455 return 0;
7456 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007457 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7458 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007459 return 0;
7460 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007461 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7462 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007463 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007464 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007465 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007466 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007467 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007468 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007469 case glslang::EOpDeviceMemoryBarrier:
7470 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7471 spv::MemorySemanticsImageMemoryMask |
7472 spv::MemorySemanticsAcquireReleaseMask);
7473 return 0;
7474 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7475 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7476 spv::MemorySemanticsImageMemoryMask |
7477 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007478 return 0;
7479 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007480 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7481 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007482 return 0;
7483 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007484 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7485 spv::MemorySemanticsWorkgroupMemoryMask |
7486 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007487 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007488 case glslang::EOpSubgroupBarrier:
7489 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7490 spv::MemorySemanticsAcquireReleaseMask);
7491 return spv::NoResult;
7492 case glslang::EOpSubgroupMemoryBarrier:
7493 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7494 spv::MemorySemanticsAcquireReleaseMask);
7495 return spv::NoResult;
7496 case glslang::EOpSubgroupMemoryBarrierBuffer:
7497 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7498 spv::MemorySemanticsAcquireReleaseMask);
7499 return spv::NoResult;
7500 case glslang::EOpSubgroupMemoryBarrierImage:
7501 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7502 spv::MemorySemanticsAcquireReleaseMask);
7503 return spv::NoResult;
7504 case glslang::EOpSubgroupMemoryBarrierShared:
7505 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7506 spv::MemorySemanticsAcquireReleaseMask);
7507 return spv::NoResult;
7508 case glslang::EOpSubgroupElect: {
7509 std::vector<spv::Id> operands;
7510 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7511 }
Rex Xu9d93a232016-05-05 12:30:44 +08007512 case glslang::EOpTime:
7513 {
7514 std::vector<spv::Id> args; // Dummy arguments
7515 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7516 return builder.setPrecision(id, precision);
7517 }
Chao Chenb50c02e2018-09-19 11:42:24 -07007518 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007519 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007520 return 0;
7521 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007522 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007523 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007524
7525 case glslang::EOpBeginInvocationInterlock:
7526 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7527 return 0;
7528 case glslang::EOpEndInvocationInterlock:
7529 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7530 return 0;
7531
Jeff Bolzba6170b2019-07-01 09:23:23 -05007532 case glslang::EOpIsHelperInvocation:
7533 {
7534 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08007535 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
7536 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
7537 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05007538 }
7539
amhagan91fb0092019-07-10 21:14:38 -04007540 case glslang::EOpReadClockSubgroupKHR: {
7541 std::vector<spv::Id> args;
7542 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
7543 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7544 builder.addCapability(spv::CapabilityShaderClockKHR);
7545 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7546 }
7547
7548 case glslang::EOpReadClockDeviceKHR: {
7549 std::vector<spv::Id> args;
7550 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
7551 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7552 builder.addCapability(spv::CapabilityShaderClockKHR);
7553 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7554 }
John Kessenich140f3df2015-06-26 16:58:36 -06007555 default:
John Kessenich155d3512019-08-08 23:29:20 -06007556 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007557 }
John Kessenich155d3512019-08-08 23:29:20 -06007558#endif
7559
7560 logger->missingFunctionality("unknown operation with no arguments");
7561
7562 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007563}
7564
7565spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7566{
John Kessenich2f273362015-07-18 22:34:27 -06007567 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007568 spv::Id id;
7569 if (symbolValues.end() != iter) {
7570 id = iter->second;
7571 return id;
7572 }
7573
7574 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06007575 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
7576 auto forcedType = getForcedType(builtIn, symbol->getType());
7577 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06007578 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06007579 if (forcedType.second != spv::NoType)
7580 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06007581
Rex Xuc884b4a2016-06-29 15:03:44 +08007582 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007583 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7584 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7585 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06007586#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007587 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7588#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007589 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007590 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007591 if (symbol->getQualifier().hasIndex())
7592 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7593 if (symbol->getQualifier().hasComponent())
7594 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007595 // atomic counters use this:
7596 if (symbol->getQualifier().hasOffset())
7597 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007598 }
7599
scygan2c864272016-05-18 18:09:17 +02007600 if (symbol->getQualifier().hasLocation())
7601 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007602 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007603 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007604 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007605 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007606 }
John Kessenich140f3df2015-06-26 16:58:36 -06007607 if (symbol->getQualifier().hasSet())
7608 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007609 else if (IsDescriptorResource(symbol->getType())) {
7610 // default to 0
7611 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7612 }
John Kessenich140f3df2015-06-26 16:58:36 -06007613 if (symbol->getQualifier().hasBinding())
7614 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007615 else if (IsDescriptorResource(symbol->getType())) {
7616 // default to 0
7617 builder.addDecoration(id, spv::DecorationBinding, 0);
7618 }
John Kessenich6c292d32016-02-15 20:58:50 -07007619 if (symbol->getQualifier().hasAttachment())
7620 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich7015bd62019-08-01 03:28:08 -06007621#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007622 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007623 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007624 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007625 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007626 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7627 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7628 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7629 }
7630 if (symbol->getQualifier().hasXfbOffset())
7631 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007632 }
John Kessenich7015bd62019-08-01 03:28:08 -06007633#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007634
Rex Xu1da878f2016-02-21 20:59:01 +08007635 if (symbol->getType().isImage()) {
7636 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007637 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007638 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007639 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007640 }
7641
John Kessenich9c14f772019-06-17 08:38:35 -06007642 // add built-in variable decoration
7643 if (builtIn != spv::BuiltInMax) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007644 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich9c14f772019-06-17 08:38:35 -06007645 }
John Kessenich140f3df2015-06-26 16:58:36 -06007646
John Kessenich5611c6d2018-04-05 11:25:02 -06007647 // nonuniform
7648 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7649
John Kessenicha28f7a72019-08-06 07:00:58 -06007650#ifndef GLSLANG_WEB
chaoc0ad6a4e2016-12-19 16:29:34 -08007651 if (builtIn == spv::BuiltInSampleMask) {
7652 spv::Decoration decoration;
7653 // GL_NV_sample_mask_override_coverage extension
7654 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007655 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007656 else
7657 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007658 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007659 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07007660 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08007661 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7662 }
7663 }
chaoc771d89f2017-01-13 01:10:53 -08007664 else if (builtIn == spv::BuiltInLayer) {
7665 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007666 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007667 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007668 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7669 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7670 }
John Kessenichb41bff62017-08-11 13:07:17 -06007671 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007672 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7673 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007674 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7675 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7676 }
7677 }
7678
chaoc6e5acae2016-12-20 13:28:52 -08007679 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007680 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007681 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007682 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7683 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007684 if (symbol->getQualifier().pervertexNV) {
7685 builder.addDecoration(id, spv::DecorationPerVertexNV);
7686 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7687 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7688 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007689#endif
7690
John Kessenich5d610ee2018-03-07 18:05:55 -07007691 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7692 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7693 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7694 symbol->getType().getQualifier().semanticName);
7695 }
7696
John Kessenich7015bd62019-08-01 03:28:08 -06007697 if (symbol->isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007698 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7699 }
7700
John Kessenich140f3df2015-06-26 16:58:36 -06007701 return id;
7702}
7703
John Kessenicha28f7a72019-08-06 07:00:58 -06007704#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007705// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7706void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7707{
7708 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007709 if (qualifier.perPrimitiveNV) {
7710 // Need to add capability/extension for fragment shader.
7711 // Mesh shader already adds this by default.
7712 if (glslangIntermediate->getStage() == EShLangFragment) {
7713 builder.addCapability(spv::CapabilityMeshShadingNV);
7714 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7715 }
Chao Chen3c366992018-09-19 11:41:59 -07007716 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007717 }
Chao Chen3c366992018-09-19 11:41:59 -07007718 if (qualifier.perViewNV)
7719 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7720 if (qualifier.perTaskNV)
7721 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7722 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007723 if (qualifier.perPrimitiveNV) {
7724 // Need to add capability/extension for fragment shader.
7725 // Mesh shader already adds this by default.
7726 if (glslangIntermediate->getStage() == EShLangFragment) {
7727 builder.addCapability(spv::CapabilityMeshShadingNV);
7728 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7729 }
Chao Chen3c366992018-09-19 11:41:59 -07007730 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007731 }
Chao Chen3c366992018-09-19 11:41:59 -07007732 if (qualifier.perViewNV)
7733 builder.addDecoration(id, spv::DecorationPerViewNV);
7734 if (qualifier.perTaskNV)
7735 builder.addDecoration(id, spv::DecorationPerTaskNV);
7736 }
7737}
7738#endif
7739
John Kessenich55e7d112015-11-15 21:33:39 -07007740// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007741// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007742//
7743// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7744//
7745// Recursively walk the nodes. The nodes form a tree whose leaves are
7746// regular constants, which themselves are trees that createSpvConstant()
7747// recursively walks. So, this function walks the "top" of the tree:
7748// - emit specialization constant-building instructions for specConstant
7749// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007750spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007751{
John Kessenich7cc0e282016-03-20 00:46:02 -06007752 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007753
qining4f4bb812016-04-03 23:55:17 -04007754 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007755 if (! node.getQualifier().specConstant) {
7756 // hand off to the non-spec-constant path
7757 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7758 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007759 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007760 nextConst, false);
7761 }
7762
7763 // We now know we have a specialization constant to build
7764
John Kessenich155d3512019-08-08 23:29:20 -06007765#ifndef GLSLANG_WEB
John Kessenichd94c0032016-05-30 19:29:40 -06007766 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007767 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7768 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7769 std::vector<spv::Id> dimConstId;
7770 for (int dim = 0; dim < 3; ++dim) {
7771 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7772 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007773 if (specConst) {
7774 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7775 glslangIntermediate->getLocalSizeSpecId(dim));
7776 }
qining4f4bb812016-04-03 23:55:17 -04007777 }
7778 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7779 }
John Kessenich155d3512019-08-08 23:29:20 -06007780#endif
qining4f4bb812016-04-03 23:55:17 -04007781
7782 // An AST node labelled as specialization constant should be a symbol node.
7783 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7784 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007785 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007786 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007787 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7788 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7789 // will set the builder into spec constant op instruction generating mode.
7790 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007791 result = accessChainLoad(sub_tree->getType());
7792 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007793 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007794 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007795 } else {
7796 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007797 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007798 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007799 builder.addName(result, sn->getName().c_str());
7800 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007801 }
qining4f4bb812016-04-03 23:55:17 -04007802
7803 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7804 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007805 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007806 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007807}
7808
John Kessenich140f3df2015-06-26 16:58:36 -06007809// Use 'consts' as the flattened glslang source of scalar constants to recursively
7810// build the aggregate SPIR-V constant.
7811//
7812// If there are not enough elements present in 'consts', 0 will be substituted;
7813// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7814//
qining08408382016-03-21 09:51:37 -04007815spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007816{
7817 // vector of constants for SPIR-V
7818 std::vector<spv::Id> spvConsts;
7819
7820 // Type is used for struct and array constants
7821 spv::Id typeId = convertGlslangToSpvType(glslangType);
7822
7823 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007824 glslang::TType elementType(glslangType, 0);
7825 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007826 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007827 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007828 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007829 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007830 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007831 } else if (glslangType.isCoopMat()) {
7832 glslang::TType componentType(glslangType.getBasicType());
7833 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007834 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007835 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7836 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007837 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007838 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007839 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7840 bool zero = nextConst >= consts.size();
7841 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06007842 case glslang::EbtInt:
7843 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7844 break;
7845 case glslang::EbtUint:
7846 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7847 break;
7848 case glslang::EbtFloat:
7849 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7850 break;
7851 case glslang::EbtBool:
7852 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7853 break;
7854#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07007855 case glslang::EbtInt8:
7856 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7857 break;
7858 case glslang::EbtUint8:
7859 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7860 break;
7861 case glslang::EbtInt16:
7862 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7863 break;
7864 case glslang::EbtUint16:
7865 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7866 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007867 case glslang::EbtInt64:
7868 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7869 break;
7870 case glslang::EbtUint64:
7871 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7872 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007873 case glslang::EbtDouble:
7874 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7875 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007876 case glslang::EbtFloat16:
7877 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7878 break;
John Kessenich39697cd2019-08-08 10:35:51 -06007879#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007880 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007881 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007882 break;
7883 }
7884 ++nextConst;
7885 }
7886 } else {
7887 // we have a non-aggregate (scalar) constant
7888 bool zero = nextConst >= consts.size();
7889 spv::Id scalar = 0;
7890 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06007891 case glslang::EbtInt:
7892 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
7893 break;
7894 case glslang::EbtUint:
7895 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
7896 break;
7897 case glslang::EbtFloat:
7898 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7899 break;
7900 case glslang::EbtBool:
7901 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
7902 break;
7903#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07007904 case glslang::EbtInt8:
7905 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7906 break;
7907 case glslang::EbtUint8:
7908 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7909 break;
7910 case glslang::EbtInt16:
7911 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7912 break;
7913 case glslang::EbtUint16:
7914 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7915 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007916 case glslang::EbtInt64:
7917 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7918 break;
7919 case glslang::EbtUint64:
7920 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7921 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007922 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007923 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007924 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007925 case glslang::EbtFloat16:
7926 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7927 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06007928 case glslang::EbtReference:
7929 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7930 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
7931 break;
John Kessenich39697cd2019-08-08 10:35:51 -06007932#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007933 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007934 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007935 break;
7936 }
7937 ++nextConst;
7938 return scalar;
7939 }
7940
7941 return builder.makeCompositeConstant(typeId, spvConsts);
7942}
7943
John Kessenich7c1aa102015-10-15 13:29:11 -06007944// Return true if the node is a constant or symbol whose reading has no
7945// non-trivial observable cost or effect.
7946bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7947{
7948 // don't know what this is
7949 if (node == nullptr)
7950 return false;
7951
7952 // a constant is safe
7953 if (node->getAsConstantUnion() != nullptr)
7954 return true;
7955
7956 // not a symbol means non-trivial
7957 if (node->getAsSymbolNode() == nullptr)
7958 return false;
7959
7960 // a symbol, depends on what's being read
7961 switch (node->getType().getQualifier().storage) {
7962 case glslang::EvqTemporary:
7963 case glslang::EvqGlobal:
7964 case glslang::EvqIn:
7965 case glslang::EvqInOut:
7966 case glslang::EvqConst:
7967 case glslang::EvqConstReadOnly:
7968 case glslang::EvqUniform:
7969 return true;
7970 default:
7971 return false;
7972 }
qining25262b32016-05-06 17:25:16 -04007973}
John Kessenich7c1aa102015-10-15 13:29:11 -06007974
7975// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007976// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007977// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007978// Return true if trivial.
7979bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7980{
7981 if (node == nullptr)
7982 return false;
7983
John Kessenich84cc15f2017-05-24 16:44:47 -06007984 // count non scalars as trivial, as well as anything coming from HLSL
7985 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007986 return true;
7987
John Kessenich7c1aa102015-10-15 13:29:11 -06007988 // symbols and constants are trivial
7989 if (isTrivialLeaf(node))
7990 return true;
7991
7992 // otherwise, it needs to be a simple operation or one or two leaf nodes
7993
7994 // not a simple operation
7995 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7996 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7997 if (binaryNode == nullptr && unaryNode == nullptr)
7998 return false;
7999
8000 // not on leaf nodes
8001 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8002 return false;
8003
8004 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8005 return false;
8006 }
8007
8008 switch (node->getAsOperator()->getOp()) {
8009 case glslang::EOpLogicalNot:
8010 case glslang::EOpConvIntToBool:
8011 case glslang::EOpConvUintToBool:
8012 case glslang::EOpConvFloatToBool:
8013 case glslang::EOpConvDoubleToBool:
8014 case glslang::EOpEqual:
8015 case glslang::EOpNotEqual:
8016 case glslang::EOpLessThan:
8017 case glslang::EOpGreaterThan:
8018 case glslang::EOpLessThanEqual:
8019 case glslang::EOpGreaterThanEqual:
8020 case glslang::EOpIndexDirect:
8021 case glslang::EOpIndexDirectStruct:
8022 case glslang::EOpLogicalXor:
8023 case glslang::EOpAny:
8024 case glslang::EOpAll:
8025 return true;
8026 default:
8027 return false;
8028 }
8029}
8030
8031// Emit short-circuiting code, where 'right' is never evaluated unless
8032// the left side is true (for &&) or false (for ||).
8033spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
8034{
8035 spv::Id boolTypeId = builder.makeBoolType();
8036
8037 // emit left operand
8038 builder.clearAccessChain();
8039 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008040 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008041
8042 // Operands to accumulate OpPhi operands
8043 std::vector<spv::Id> phiOperands;
8044 // accumulate left operand's phi information
8045 phiOperands.push_back(leftId);
8046 phiOperands.push_back(builder.getBuildPoint()->getId());
8047
8048 // Make the two kinds of operation symmetric with a "!"
8049 // || => emit "if (! left) result = right"
8050 // && => emit "if ( left) result = right"
8051 //
8052 // TODO: this runtime "not" for || could be avoided by adding functionality
8053 // to 'builder' to have an "else" without an "then"
8054 if (op == glslang::EOpLogicalOr)
8055 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8056
8057 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008058 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008059
8060 // emit right operand as the "then" part of the "if"
8061 builder.clearAccessChain();
8062 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008063 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008064
8065 // accumulate left operand's phi information
8066 phiOperands.push_back(rightId);
8067 phiOperands.push_back(builder.getBuildPoint()->getId());
8068
8069 // finish the "if"
8070 ifBuilder.makeEndIf();
8071
8072 // phi together the two results
8073 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8074}
8075
John Kessenicha28f7a72019-08-06 07:00:58 -06008076#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008077// Return type Id of the imported set of extended instructions corresponds to the name.
8078// Import this set if it has not been imported yet.
8079spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8080{
8081 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8082 return extBuiltinMap[name];
8083 else {
Rex Xu51596642016-09-21 18:56:12 +08008084 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008085 spv::Id extBuiltins = builder.import(name);
8086 extBuiltinMap[name] = extBuiltins;
8087 return extBuiltins;
8088 }
8089}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008090#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008091
John Kessenich140f3df2015-06-26 16:58:36 -06008092}; // end anonymous namespace
8093
8094namespace glslang {
8095
John Kessenich68d78fd2015-07-12 19:28:10 -06008096void GetSpirvVersion(std::string& version)
8097{
John Kessenich9e55f632015-07-15 10:03:39 -06008098 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008099 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008100 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008101 version = buf;
8102}
8103
John Kessenicha372a3e2017-11-02 22:32:14 -06008104// For low-order part of the generator's magic number. Bump up
8105// when there is a change in the style (e.g., if SSA form changes,
8106// or a different instruction sequence to do something gets used).
8107int GetSpirvGeneratorVersion()
8108{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008109 // return 1; // start
8110 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008111 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008112 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008113 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008114 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8115 // versions 4 and 6 each generate OpArrayLength as it has long been done
8116 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06008117}
8118
John Kessenich140f3df2015-06-26 16:58:36 -06008119// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008120void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008121{
8122 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008123 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008124 if (out.fail())
8125 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008126 for (int i = 0; i < (int)spirv.size(); ++i) {
8127 unsigned int word = spirv[i];
8128 out.write((const char*)&word, 4);
8129 }
8130 out.close();
8131}
8132
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008133// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008134void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008135{
John Kessenich155d3512019-08-08 23:29:20 -06008136#ifndef GLSLANG_WEB
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008137 std::ofstream out;
8138 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008139 if (out.fail())
8140 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008141 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008142 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008143 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008144 if (varName != nullptr) {
8145 out << "\t #pragma once" << std::endl;
8146 out << "const uint32_t " << varName << "[] = {" << std::endl;
8147 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008148 const int WORDS_PER_LINE = 8;
8149 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8150 out << "\t";
8151 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8152 const unsigned int word = spirv[i + j];
8153 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8154 if (i + j + 1 < (int)spirv.size()) {
8155 out << ",";
8156 }
8157 }
8158 out << std::endl;
8159 }
Flavio15017db2017-02-15 14:29:33 -08008160 if (varName != nullptr) {
8161 out << "};";
8162 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008163 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008164#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008165}
8166
John Kessenich140f3df2015-06-26 16:58:36 -06008167//
8168// Set up the glslang traversal
8169//
John Kessenich4e11b612018-08-30 16:56:59 -06008170void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008171{
Lei Zhang17535f72016-05-04 15:55:59 -04008172 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008173 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008174}
8175
John Kessenich4e11b612018-08-30 16:56:59 -06008176void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008177 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008178{
John Kessenich140f3df2015-06-26 16:58:36 -06008179 TIntermNode* root = intermediate.getTreeRoot();
8180
8181 if (root == 0)
8182 return;
8183
John Kessenich4e11b612018-08-30 16:56:59 -06008184 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008185 if (options == nullptr)
8186 options = &defaultOptions;
8187
John Kessenich4e11b612018-08-30 16:56:59 -06008188 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008189
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008190 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008191 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008192 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008193 it.dumpSpv(spirv);
8194
GregFfb03a552018-03-29 11:49:14 -06008195#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008196 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8197 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008198 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8199 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008200 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008201 prelegalization = false;
8202 }
John Kessenich717c80a2018-08-23 15:17:10 -06008203
John Kessenich4e11b612018-08-30 16:56:59 -06008204 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008205 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008206
John Kessenich717c80a2018-08-23 15:17:10 -06008207 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008208 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008209
GregFcd1f1692017-09-21 18:40:22 -06008210#endif
8211
John Kessenich4e11b612018-08-30 16:56:59 -06008212 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008213}
8214
8215}; // end namespace glslang