blob: 33c4db498b299d1e7c8b7874c7f70ca49f56762c [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
John Kessenichfb4f2332019-08-09 03:49:15 -06002078#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002079 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2080 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002081 node->getOp() == glslang::EOpAtomicCounter ||
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002082 node->getOp() == glslang::EOpInterpolateAtCentroid) {
Rex Xufc618912015-09-09 16:42:49 +08002083 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002084 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2085 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2086 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002087#endif
2088 {
John Kessenich32cfd492016-02-02 12:37:46 -07002089 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002090 }
John Kessenich140f3df2015-06-26 16:58:36 -06002091
John Kessenichead86222018-03-28 18:01:20 -06002092 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002093 TranslateNoContractionDecoration(node->getType().getQualifier()),
2094 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002095
2096 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002097 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06002098 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002099
2100 // if not, then possibly an operation
2101 if (! result)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002102 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002103
2104 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002105 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002106 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002107 builder.addDecoration(result, decorations.nonUniform);
2108 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002109
John Kessenich140f3df2015-06-26 16:58:36 -06002110 builder.clearAccessChain();
2111 builder.setAccessChainRValue(result);
2112
2113 return false; // done with this node
2114 }
2115
2116 // it must be a special case, check...
2117 switch (node->getOp()) {
2118 case glslang::EOpPostIncrement:
2119 case glslang::EOpPostDecrement:
2120 case glslang::EOpPreIncrement:
2121 case glslang::EOpPreDecrement:
2122 {
2123 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002124 spv::Id one = 0;
2125 if (node->getBasicType() == glslang::EbtFloat)
2126 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002127#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002128 else if (node->getBasicType() == glslang::EbtDouble)
2129 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002130 else if (node->getBasicType() == glslang::EbtFloat16)
2131 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002132 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2133 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002134 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2135 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002136 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2137 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002138#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002139 else
2140 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002141 glslang::TOperator op;
2142 if (node->getOp() == glslang::EOpPreIncrement ||
2143 node->getOp() == glslang::EOpPostIncrement)
2144 op = glslang::EOpAdd;
2145 else
2146 op = glslang::EOpSub;
2147
John Kessenichead86222018-03-28 18:01:20 -06002148 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002149 convertGlslangToSpvType(node->getType()), operand, one,
2150 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002151 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002152
2153 // The result of operation is always stored, but conditionally the
2154 // consumed result. The consumed result is always an r-value.
2155 builder.accessChainStore(result);
2156 builder.clearAccessChain();
2157 if (node->getOp() == glslang::EOpPreIncrement ||
2158 node->getOp() == glslang::EOpPreDecrement)
2159 builder.setAccessChainRValue(result);
2160 else
2161 builder.setAccessChainRValue(operand);
2162 }
2163
2164 return false;
2165
John Kessenich155d3512019-08-08 23:29:20 -06002166#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002167 case glslang::EOpEmitStreamVertex:
2168 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2169 return false;
2170 case glslang::EOpEndStreamPrimitive:
2171 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2172 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002173#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002174
2175 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002176 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002177 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002178 }
John Kessenich140f3df2015-06-26 16:58:36 -06002179}
2180
Jeff Bolz53134492019-06-25 13:31:10 -05002181// Construct a composite object, recursively copying members if their types don't match
2182spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2183{
2184 for (int c = 0; c < (int)constituents.size(); ++c) {
2185 spv::Id& constituent = constituents[c];
2186 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2187 spv::Id rType = builder.getTypeId(constituent);
2188 if (lType != rType) {
2189 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2190 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2191 } else if (builder.isStructType(rType)) {
2192 std::vector<spv::Id> rTypeConstituents;
2193 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2194 for (int i = 0; i < numrTypeConstituents; ++i) {
2195 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, builder.getContainedTypeId(rType, i), i));
2196 }
2197 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2198 } else {
2199 assert(builder.isArrayType(rType));
2200 std::vector<spv::Id> rTypeConstituents;
2201 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2202
2203 spv::Id elementRType = builder.getContainedTypeId(rType);
2204 for (int i = 0; i < numrTypeConstituents; ++i) {
2205 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2206 }
2207 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2208 }
2209 }
2210 }
2211 return builder.createCompositeConstruct(resultTypeId, constituents);
2212}
2213
John Kessenich140f3df2015-06-26 16:58:36 -06002214bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2215{
qining27e04a02016-04-14 16:40:20 -04002216 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2217 if (node->getType().getQualifier().isSpecConstant())
2218 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2219
John Kessenichfc51d282015-08-19 13:34:18 -06002220 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002221 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2222 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002223
2224 // try texturing
2225 result = createImageTextureFunctionCall(node);
2226 if (result != spv::NoResult) {
2227 builder.clearAccessChain();
2228 builder.setAccessChainRValue(result);
2229
2230 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002231 }
2232#ifndef GLSLANG_WEB
2233 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002234 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002235 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002236 // "imageStore" is a special case, which has no result
2237 return false;
2238 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002239#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002240
John Kessenich140f3df2015-06-26 16:58:36 -06002241 glslang::TOperator binOp = glslang::EOpNull;
2242 bool reduceComparison = true;
2243 bool isMatrix = false;
2244 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002245 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002246
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002247 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2248
John Kessenich140f3df2015-06-26 16:58:36 -06002249 assert(node->getOp());
2250
John Kessenichf6640762016-08-01 19:44:00 -06002251 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002252
2253 switch (node->getOp()) {
2254 case glslang::EOpSequence:
2255 {
2256 if (preVisit)
2257 ++sequenceDepth;
2258 else
2259 --sequenceDepth;
2260
2261 if (sequenceDepth == 1) {
2262 // If this is the parent node of all the functions, we want to see them
2263 // early, so all call points have actual SPIR-V functions to reference.
2264 // In all cases, still let the traverser visit the children for us.
2265 makeFunctions(node->getAsAggregate()->getSequence());
2266
John Kessenich6fccb3c2016-09-19 16:01:41 -06002267 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002268 // anything else gets there, so visit out of order, doing them all now.
2269 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2270
John Kessenich6a60c2f2016-12-08 21:01:59 -07002271 // 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 -06002272 // so do them manually.
2273 visitFunctions(node->getAsAggregate()->getSequence());
2274
2275 return false;
2276 }
2277
2278 return true;
2279 }
2280 case glslang::EOpLinkerObjects:
2281 {
2282 if (visit == glslang::EvPreVisit)
2283 linkageOnly = true;
2284 else
2285 linkageOnly = false;
2286
2287 return true;
2288 }
2289 case glslang::EOpComma:
2290 {
2291 // processing from left to right naturally leaves the right-most
2292 // lying around in the access chain
2293 glslang::TIntermSequence& glslangOperands = node->getSequence();
2294 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2295 glslangOperands[i]->traverse(this);
2296
2297 return false;
2298 }
2299 case glslang::EOpFunction:
2300 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002301 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002302 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002303 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002304 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002305 } else {
2306 handleFunctionEntry(node);
2307 }
2308 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002309 if (inEntryPoint)
2310 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002311 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002312 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002313 }
2314
2315 return true;
2316 case glslang::EOpParameters:
2317 // Parameters will have been consumed by EOpFunction processing, but not
2318 // the body, so we still visited the function node's children, making this
2319 // child redundant.
2320 return false;
2321 case glslang::EOpFunctionCall:
2322 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002323 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002324 if (node->isUserDefined())
2325 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002326 // 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 -07002327 if (result) {
2328 builder.clearAccessChain();
2329 builder.setAccessChainRValue(result);
2330 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002331 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002332
2333 return false;
2334 }
2335 case glslang::EOpConstructMat2x2:
2336 case glslang::EOpConstructMat2x3:
2337 case glslang::EOpConstructMat2x4:
2338 case glslang::EOpConstructMat3x2:
2339 case glslang::EOpConstructMat3x3:
2340 case glslang::EOpConstructMat3x4:
2341 case glslang::EOpConstructMat4x2:
2342 case glslang::EOpConstructMat4x3:
2343 case glslang::EOpConstructMat4x4:
2344 case glslang::EOpConstructDMat2x2:
2345 case glslang::EOpConstructDMat2x3:
2346 case glslang::EOpConstructDMat2x4:
2347 case glslang::EOpConstructDMat3x2:
2348 case glslang::EOpConstructDMat3x3:
2349 case glslang::EOpConstructDMat3x4:
2350 case glslang::EOpConstructDMat4x2:
2351 case glslang::EOpConstructDMat4x3:
2352 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002353 case glslang::EOpConstructIMat2x2:
2354 case glslang::EOpConstructIMat2x3:
2355 case glslang::EOpConstructIMat2x4:
2356 case glslang::EOpConstructIMat3x2:
2357 case glslang::EOpConstructIMat3x3:
2358 case glslang::EOpConstructIMat3x4:
2359 case glslang::EOpConstructIMat4x2:
2360 case glslang::EOpConstructIMat4x3:
2361 case glslang::EOpConstructIMat4x4:
2362 case glslang::EOpConstructUMat2x2:
2363 case glslang::EOpConstructUMat2x3:
2364 case glslang::EOpConstructUMat2x4:
2365 case glslang::EOpConstructUMat3x2:
2366 case glslang::EOpConstructUMat3x3:
2367 case glslang::EOpConstructUMat3x4:
2368 case glslang::EOpConstructUMat4x2:
2369 case glslang::EOpConstructUMat4x3:
2370 case glslang::EOpConstructUMat4x4:
2371 case glslang::EOpConstructBMat2x2:
2372 case glslang::EOpConstructBMat2x3:
2373 case glslang::EOpConstructBMat2x4:
2374 case glslang::EOpConstructBMat3x2:
2375 case glslang::EOpConstructBMat3x3:
2376 case glslang::EOpConstructBMat3x4:
2377 case glslang::EOpConstructBMat4x2:
2378 case glslang::EOpConstructBMat4x3:
2379 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002380 case glslang::EOpConstructF16Mat2x2:
2381 case glslang::EOpConstructF16Mat2x3:
2382 case glslang::EOpConstructF16Mat2x4:
2383 case glslang::EOpConstructF16Mat3x2:
2384 case glslang::EOpConstructF16Mat3x3:
2385 case glslang::EOpConstructF16Mat3x4:
2386 case glslang::EOpConstructF16Mat4x2:
2387 case glslang::EOpConstructF16Mat4x3:
2388 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002389 isMatrix = true;
2390 // fall through
2391 case glslang::EOpConstructFloat:
2392 case glslang::EOpConstructVec2:
2393 case glslang::EOpConstructVec3:
2394 case glslang::EOpConstructVec4:
2395 case glslang::EOpConstructDouble:
2396 case glslang::EOpConstructDVec2:
2397 case glslang::EOpConstructDVec3:
2398 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002399 case glslang::EOpConstructFloat16:
2400 case glslang::EOpConstructF16Vec2:
2401 case glslang::EOpConstructF16Vec3:
2402 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002403 case glslang::EOpConstructBool:
2404 case glslang::EOpConstructBVec2:
2405 case glslang::EOpConstructBVec3:
2406 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002407 case glslang::EOpConstructInt8:
2408 case glslang::EOpConstructI8Vec2:
2409 case glslang::EOpConstructI8Vec3:
2410 case glslang::EOpConstructI8Vec4:
2411 case glslang::EOpConstructUint8:
2412 case glslang::EOpConstructU8Vec2:
2413 case glslang::EOpConstructU8Vec3:
2414 case glslang::EOpConstructU8Vec4:
2415 case glslang::EOpConstructInt16:
2416 case glslang::EOpConstructI16Vec2:
2417 case glslang::EOpConstructI16Vec3:
2418 case glslang::EOpConstructI16Vec4:
2419 case glslang::EOpConstructUint16:
2420 case glslang::EOpConstructU16Vec2:
2421 case glslang::EOpConstructU16Vec3:
2422 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002423 case glslang::EOpConstructInt:
2424 case glslang::EOpConstructIVec2:
2425 case glslang::EOpConstructIVec3:
2426 case glslang::EOpConstructIVec4:
2427 case glslang::EOpConstructUint:
2428 case glslang::EOpConstructUVec2:
2429 case glslang::EOpConstructUVec3:
2430 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002431 case glslang::EOpConstructInt64:
2432 case glslang::EOpConstructI64Vec2:
2433 case glslang::EOpConstructI64Vec3:
2434 case glslang::EOpConstructI64Vec4:
2435 case glslang::EOpConstructUint64:
2436 case glslang::EOpConstructU64Vec2:
2437 case glslang::EOpConstructU64Vec3:
2438 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002439 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002440 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002441 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002442 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002443 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002444 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002445 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002446 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002447 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002448 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002449 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002450 else if (node->getOp() == glslang::EOpConstructStruct ||
2451 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2452 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002453 std::vector<spv::Id> constituents;
2454 for (int c = 0; c < (int)arguments.size(); ++c)
2455 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002456 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002457 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002458 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002459 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002460 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002461
2462 builder.clearAccessChain();
2463 builder.setAccessChainRValue(constructed);
2464
2465 return false;
2466 }
2467
2468 // These six are component-wise compares with component-wise results.
2469 // Forward on to createBinaryOperation(), requesting a vector result.
2470 case glslang::EOpLessThan:
2471 case glslang::EOpGreaterThan:
2472 case glslang::EOpLessThanEqual:
2473 case glslang::EOpGreaterThanEqual:
2474 case glslang::EOpVectorEqual:
2475 case glslang::EOpVectorNotEqual:
2476 {
2477 // Map the operation to a binary
2478 binOp = node->getOp();
2479 reduceComparison = false;
2480 switch (node->getOp()) {
2481 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2482 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2483 default: binOp = node->getOp(); break;
2484 }
2485
2486 break;
2487 }
2488 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002489 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002490 binOp = glslang::EOpMul;
2491 break;
2492 case glslang::EOpOuterProduct:
2493 // two vectors multiplied to make a matrix
2494 binOp = glslang::EOpOuterProduct;
2495 break;
2496 case glslang::EOpDot:
2497 {
qining25262b32016-05-06 17:25:16 -04002498 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002499 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002500 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002501 binOp = glslang::EOpMul;
2502 break;
2503 }
2504 case glslang::EOpMod:
2505 // when an aggregate, this is the floating-point mod built-in function,
2506 // which can be emitted by the one in createBinaryOperation()
2507 binOp = glslang::EOpMod;
2508 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002509
2510#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002511 case glslang::EOpEmitVertex:
2512 case glslang::EOpEndPrimitive:
2513 case glslang::EOpBarrier:
2514 case glslang::EOpMemoryBarrier:
2515 case glslang::EOpMemoryBarrierAtomicCounter:
2516 case glslang::EOpMemoryBarrierBuffer:
2517 case glslang::EOpMemoryBarrierImage:
2518 case glslang::EOpMemoryBarrierShared:
2519 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002520 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002521 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002522 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002523 case glslang::EOpWorkgroupMemoryBarrier:
2524 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002525 case glslang::EOpSubgroupBarrier:
2526 case glslang::EOpSubgroupMemoryBarrier:
2527 case glslang::EOpSubgroupMemoryBarrierBuffer:
2528 case glslang::EOpSubgroupMemoryBarrierImage:
2529 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002530 noReturnValue = true;
2531 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2532 break;
2533
Jeff Bolz36831c92018-09-05 10:11:41 -05002534 case glslang::EOpAtomicStore:
2535 noReturnValue = true;
2536 // fallthrough
2537 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002538 case glslang::EOpAtomicAdd:
2539 case glslang::EOpAtomicMin:
2540 case glslang::EOpAtomicMax:
2541 case glslang::EOpAtomicAnd:
2542 case glslang::EOpAtomicOr:
2543 case glslang::EOpAtomicXor:
2544 case glslang::EOpAtomicExchange:
2545 case glslang::EOpAtomicCompSwap:
2546 atomic = true;
2547 break;
2548
John Kessenich0d0c6d32017-07-23 16:08:26 -06002549 case glslang::EOpAtomicCounterAdd:
2550 case glslang::EOpAtomicCounterSubtract:
2551 case glslang::EOpAtomicCounterMin:
2552 case glslang::EOpAtomicCounterMax:
2553 case glslang::EOpAtomicCounterAnd:
2554 case glslang::EOpAtomicCounterOr:
2555 case glslang::EOpAtomicCounterXor:
2556 case glslang::EOpAtomicCounterExchange:
2557 case glslang::EOpAtomicCounterCompSwap:
2558 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2559 builder.addCapability(spv::CapabilityAtomicStorageOps);
2560 atomic = true;
2561 break;
2562
Chao Chenb50c02e2018-09-19 11:42:24 -07002563 case glslang::EOpIgnoreIntersectionNV:
2564 case glslang::EOpTerminateRayNV:
2565 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002566 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002567 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2568 noReturnValue = true;
2569 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002570 case glslang::EOpCooperativeMatrixLoad:
2571 case glslang::EOpCooperativeMatrixStore:
2572 noReturnValue = true;
2573 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002574 case glslang::EOpBeginInvocationInterlock:
2575 case glslang::EOpEndInvocationInterlock:
2576 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2577 noReturnValue = true;
2578 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002579#endif
Chao Chen3c366992018-09-19 11:41:59 -07002580
John Kessenich140f3df2015-06-26 16:58:36 -06002581 default:
2582 break;
2583 }
2584
2585 //
2586 // See if it maps to a regular operation.
2587 //
John Kessenich140f3df2015-06-26 16:58:36 -06002588 if (binOp != glslang::EOpNull) {
2589 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2590 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2591 assert(left && right);
2592
2593 builder.clearAccessChain();
2594 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002595 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002596
2597 builder.clearAccessChain();
2598 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002599 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002600
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002601 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002602 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002603 TranslateNoContractionDecoration(node->getType().getQualifier()),
2604 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002605 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002606 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002607 left->getType().getBasicType(), reduceComparison);
2608
2609 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002610 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002611 builder.clearAccessChain();
2612 builder.setAccessChainRValue(result);
2613
2614 return false;
2615 }
2616
John Kessenich426394d2015-07-23 10:22:48 -06002617 //
2618 // Create the list of operands.
2619 //
John Kessenich140f3df2015-06-26 16:58:36 -06002620 glslang::TIntermSequence& glslangOperands = node->getSequence();
2621 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002622 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002623 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002624 // special case l-value operands; there are just a few
2625 bool lvalue = false;
2626 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002627 case glslang::EOpModf:
2628 if (arg == 1)
2629 lvalue = true;
2630 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002631#ifndef GLSLANG_WEB
2632 case glslang::EOpFrexp:
2633 if (arg == 1)
2634 lvalue = true;
2635 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002636 case glslang::EOpInterpolateAtSample:
2637 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002638 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002639 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002640 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002641
2642 // Does it need a swizzle inversion? If so, evaluation is inverted;
2643 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002644 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002645 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2646 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2647 }
Rex Xu7a26c172015-12-08 17:12:09 +08002648 break;
Rex Xud4782c12015-09-06 16:30:11 +08002649 case glslang::EOpAtomicAdd:
2650 case glslang::EOpAtomicMin:
2651 case glslang::EOpAtomicMax:
2652 case glslang::EOpAtomicAnd:
2653 case glslang::EOpAtomicOr:
2654 case glslang::EOpAtomicXor:
2655 case glslang::EOpAtomicExchange:
2656 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002657 case glslang::EOpAtomicLoad:
2658 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002659 case glslang::EOpAtomicCounterAdd:
2660 case glslang::EOpAtomicCounterSubtract:
2661 case glslang::EOpAtomicCounterMin:
2662 case glslang::EOpAtomicCounterMax:
2663 case glslang::EOpAtomicCounterAnd:
2664 case glslang::EOpAtomicCounterOr:
2665 case glslang::EOpAtomicCounterXor:
2666 case glslang::EOpAtomicCounterExchange:
2667 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002668 if (arg == 0)
2669 lvalue = true;
2670 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002671 case glslang::EOpAddCarry:
2672 case glslang::EOpSubBorrow:
2673 if (arg == 2)
2674 lvalue = true;
2675 break;
2676 case glslang::EOpUMulExtended:
2677 case glslang::EOpIMulExtended:
2678 if (arg >= 2)
2679 lvalue = true;
2680 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002681 case glslang::EOpCooperativeMatrixLoad:
2682 if (arg == 0 || arg == 1)
2683 lvalue = true;
2684 break;
2685 case glslang::EOpCooperativeMatrixStore:
2686 if (arg == 1)
2687 lvalue = true;
2688 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002689#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002690 default:
2691 break;
2692 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002693 builder.clearAccessChain();
2694 if (invertedType != spv::NoType && arg == 0)
2695 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2696 else
2697 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002698
2699 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2700 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2701
2702 if (arg == 1) {
2703 // fold "element" parameter into the access chain
2704 spv::Builder::AccessChain save = builder.getAccessChain();
2705 builder.clearAccessChain();
2706 glslangOperands[2]->traverse(this);
2707
2708 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2709
2710 builder.setAccessChain(save);
2711
2712 // Point to the first element of the array.
2713 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002714 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002715
2716 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2717 unsigned int alignment = builder.getAccessChain().alignment;
2718
2719 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2720 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2721 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2722 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2723 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2724 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2725 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2726 }
2727
2728 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2729
2730 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2731 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2732 }
2733
2734 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2735 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2736 }
2737 } else if (arg == 2) {
2738 continue;
2739 }
2740 }
2741
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002742 if (lvalue) {
John Kessenich140f3df2015-06-26 16:58:36 -06002743 operands.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002744 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2745 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2746 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002747 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002748 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002749 }
John Kessenich140f3df2015-06-26 16:58:36 -06002750 }
John Kessenich426394d2015-07-23 10:22:48 -06002751
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002752 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002753 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2754 std::vector<spv::IdImmediate> idImmOps;
2755
2756 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2757 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2758 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2759 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2760 // get the pointee type
2761 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2762 assert(builder.isCooperativeMatrixType(typeId));
2763 // do the op
2764 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2765 // store the result to the pointer (out param 'm')
2766 builder.createStore(result, operands[0]);
2767 result = 0;
2768 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2769 std::vector<spv::IdImmediate> idImmOps;
2770
2771 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2772 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2773 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2774 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2775 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2776
2777 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2778 result = 0;
2779 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002780 // Handle all atomics
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002781 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
John Kessenich426394d2015-07-23 10:22:48 -06002782 } else {
2783 // Pass through to generic operations.
2784 switch (glslangOperands.size()) {
2785 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002786 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002787 break;
2788 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002789 {
2790 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002791 TranslateNoContractionDecoration(node->getType().getQualifier()),
2792 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002793 result = createUnaryOperation(
2794 node->getOp(), decorations,
2795 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002796 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06002797 }
John Kessenich426394d2015-07-23 10:22:48 -06002798 break;
2799 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002800 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002801 break;
2802 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002803 if (invertedType)
2804 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002805 }
2806
2807 if (noReturnValue)
2808 return false;
2809
2810 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002811 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002812 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002813 } else {
2814 builder.clearAccessChain();
2815 builder.setAccessChainRValue(result);
2816 return false;
2817 }
2818}
2819
John Kessenich433e9ff2017-01-26 20:31:11 -07002820// This path handles both if-then-else and ?:
2821// The if-then-else has a node type of void, while
2822// ?: has either a void or a non-void node type
2823//
2824// Leaving the result, when not void:
2825// GLSL only has r-values as the result of a :?, but
2826// if we have an l-value, that can be more efficient if it will
2827// become the base of a complex r-value expression, because the
2828// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002829bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2830{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002831 // see if OpSelect can handle it
2832 const auto isOpSelectable = [&]() {
2833 if (node->getBasicType() == glslang::EbtVoid)
2834 return false;
2835 // OpSelect can do all other types starting with SPV 1.4
2836 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2837 // pre-1.4, only scalars and vectors can be handled
2838 if ((!node->getType().isScalar() && !node->getType().isVector()))
2839 return false;
2840 }
2841 return true;
2842 };
2843
John Kessenich4bee5312018-02-20 21:29:05 -07002844 // See if it simple and safe, or required, to execute both sides.
2845 // Crucially, side effects must be either semantically required or avoided,
2846 // and there are performance trade-offs.
2847 // Return true if required or a good idea (and safe) to execute both sides,
2848 // false otherwise.
2849 const auto bothSidesPolicy = [&]() -> bool {
2850 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002851 if (node->getTrueBlock() == nullptr ||
2852 node->getFalseBlock() == nullptr)
2853 return false;
2854
John Kessenich4bee5312018-02-20 21:29:05 -07002855 // required? (unless we write additional code to look for side effects
2856 // and make performance trade-offs if none are present)
2857 if (!node->getShortCircuit())
2858 return true;
2859
2860 // if not required to execute both, decide based on performance/practicality...
2861
John Kessenich0c1e71a2019-01-10 18:23:06 +07002862 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002863 return false;
2864
John Kessenich433e9ff2017-01-26 20:31:11 -07002865 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2866 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2867
2868 // return true if a single operand to ? : is okay for OpSelect
2869 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002870 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002871 };
2872
2873 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2874 operandOkay(node->getFalseBlock()->getAsTyped());
2875 };
2876
John Kessenich4bee5312018-02-20 21:29:05 -07002877 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2878 // emit the condition before doing anything with selection
2879 node->getCondition()->traverse(this);
2880 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2881
2882 // Find a way of executing both sides and selecting the right result.
2883 const auto executeBothSides = [&]() -> void {
2884 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002885 node->getTrueBlock()->traverse(this);
2886 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2887 node->getFalseBlock()->traverse(this);
2888 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2889
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002890 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002891
John Kessenich4bee5312018-02-20 21:29:05 -07002892 // done if void
2893 if (node->getBasicType() == glslang::EbtVoid)
2894 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002895
John Kessenich4bee5312018-02-20 21:29:05 -07002896 // emit code to select between trueValue and falseValue
2897
2898 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002899 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002900 // Emit OpSelect for this selection.
2901
2902 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002903 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2904 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002905 condition = builder.smearScalar(spv::NoPrecision, condition,
2906 builder.makeVectorType(builder.makeBoolType(),
2907 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002908 }
John Kessenich4bee5312018-02-20 21:29:05 -07002909
2910 // OpSelect
2911 result = builder.createTriOp(spv::OpSelect,
2912 convertGlslangToSpvType(node->getType()), condition,
2913 trueValue, falseValue);
2914
2915 builder.clearAccessChain();
2916 builder.setAccessChainRValue(result);
2917 } else {
2918 // We need control flow to select the result.
2919 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2920 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2921
2922 // Selection control:
2923 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2924
2925 // make an "if" based on the value created by the condition
2926 spv::Builder::If ifBuilder(condition, control, builder);
2927
2928 // emit the "then" statement
2929 builder.createStore(trueValue, result);
2930 ifBuilder.makeBeginElse();
2931 // emit the "else" statement
2932 builder.createStore(falseValue, result);
2933
2934 // finish off the control flow
2935 ifBuilder.makeEndIf();
2936
2937 builder.clearAccessChain();
2938 builder.setAccessChainLValue(result);
2939 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002940 };
2941
John Kessenich4bee5312018-02-20 21:29:05 -07002942 // Execute the one side needed, as per the condition
2943 const auto executeOneSide = [&]() {
2944 // Always emit control flow.
2945 if (node->getBasicType() != glslang::EbtVoid)
2946 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002947
John Kessenich4bee5312018-02-20 21:29:05 -07002948 // Selection control:
2949 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2950
2951 // make an "if" based on the value created by the condition
2952 spv::Builder::If ifBuilder(condition, control, builder);
2953
2954 // emit the "then" statement
2955 if (node->getTrueBlock() != nullptr) {
2956 node->getTrueBlock()->traverse(this);
2957 if (result != spv::NoResult)
2958 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2959 }
2960
2961 if (node->getFalseBlock() != nullptr) {
2962 ifBuilder.makeBeginElse();
2963 // emit the "else" statement
2964 node->getFalseBlock()->traverse(this);
2965 if (result != spv::NoResult)
2966 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2967 }
2968
2969 // finish off the control flow
2970 ifBuilder.makeEndIf();
2971
2972 if (result != spv::NoResult) {
2973 builder.clearAccessChain();
2974 builder.setAccessChainLValue(result);
2975 }
2976 };
2977
2978 // Try for OpSelect (or a requirement to execute both sides)
2979 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002980 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2981 if (node->getType().getQualifier().isSpecConstant())
2982 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002983 executeBothSides();
2984 } else
2985 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002986
2987 return false;
2988}
2989
2990bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2991{
2992 // emit and get the condition before doing anything with switch
2993 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002994 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002995
Rex Xu57e65922017-07-04 23:23:40 +08002996 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002997 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002998
John Kessenich140f3df2015-06-26 16:58:36 -06002999 // browse the children to sort out code segments
3000 int defaultSegment = -1;
3001 std::vector<TIntermNode*> codeSegments;
3002 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3003 std::vector<int> caseValues;
3004 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3005 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3006 TIntermNode* child = *c;
3007 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003008 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003009 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003010 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003011 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
3012 } else
3013 codeSegments.push_back(child);
3014 }
3015
qining25262b32016-05-06 17:25:16 -04003016 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003017 // statements between the last case and the end of the switch statement
3018 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3019 (int)codeSegments.size() == defaultSegment)
3020 codeSegments.push_back(nullptr);
3021
3022 // make the switch statement
3023 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08003024 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003025
3026 // emit all the code in the segments
3027 breakForLoop.push(false);
3028 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3029 builder.nextSwitchSegment(segmentBlocks, s);
3030 if (codeSegments[s])
3031 codeSegments[s]->traverse(this);
3032 else
3033 builder.addSwitchBreak();
3034 }
3035 breakForLoop.pop();
3036
3037 builder.endSwitch(segmentBlocks);
3038
3039 return false;
3040}
3041
3042void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3043{
3044 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003045 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003046
3047 builder.clearAccessChain();
3048 builder.setAccessChainRValue(constant);
3049}
3050
3051bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3052{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003053 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003054 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003055
3056 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003057 std::vector<unsigned int> operands;
3058 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003059
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003060 // Spec requires back edges to target header blocks, and every header block
3061 // must dominate its merge block. Make a header block first to ensure these
3062 // conditions are met. By definition, it will contain OpLoopMerge, followed
3063 // by a block-ending branch. But we don't want to put any other body/test
3064 // instructions in it, since the body/test may have arbitrary instructions,
3065 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003066 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003067 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003068 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003069 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003070 spv::Block& test = builder.makeNewBlock();
3071 builder.createBranch(&test);
3072
3073 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003074 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003075 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003076 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3077
3078 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003079 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003080 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003081 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003082 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003083 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003084
3085 builder.setBuildPoint(&blocks.continue_target);
3086 if (node->getTerminal())
3087 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003088 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003089 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003090 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003091 builder.createBranch(&blocks.body);
3092
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003093 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003094 builder.setBuildPoint(&blocks.body);
3095 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003096 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003097 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003098 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003099
3100 builder.setBuildPoint(&blocks.continue_target);
3101 if (node->getTerminal())
3102 node->getTerminal()->traverse(this);
3103 if (node->getTest()) {
3104 node->getTest()->traverse(this);
3105 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003106 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003107 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003108 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003109 // TODO: unless there was a break/return/discard instruction
3110 // somewhere in the body, this is an infinite loop, so we should
3111 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003112 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003113 }
John Kessenich140f3df2015-06-26 16:58:36 -06003114 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003115 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003116 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003117 return false;
3118}
3119
3120bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3121{
3122 if (node->getExpression())
3123 node->getExpression()->traverse(this);
3124
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003125 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003126
John Kessenich140f3df2015-06-26 16:58:36 -06003127 switch (node->getFlowOp()) {
3128 case glslang::EOpKill:
3129 builder.makeDiscard();
3130 break;
3131 case glslang::EOpBreak:
3132 if (breakForLoop.top())
3133 builder.createLoopExit();
3134 else
3135 builder.addSwitchBreak();
3136 break;
3137 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003138 builder.createLoopContinue();
3139 break;
3140 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003141 if (node->getExpression()) {
3142 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3143 spv::Id returnId = accessChainLoad(glslangReturnType);
3144 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3145 builder.clearAccessChain();
3146 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3147 builder.setAccessChainLValue(copyId);
3148 multiTypeStore(glslangReturnType, returnId);
3149 returnId = builder.createLoad(copyId);
3150 }
3151 builder.makeReturn(false, returnId);
3152 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003153 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003154
3155 builder.clearAccessChain();
3156 break;
3157
Jeff Bolzba6170b2019-07-01 09:23:23 -05003158 case glslang::EOpDemote:
3159 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3160 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3161 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3162 break;
3163
John Kessenich140f3df2015-06-26 16:58:36 -06003164 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003165 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003166 break;
3167 }
3168
3169 return false;
3170}
3171
John Kessenich9c14f772019-06-17 08:38:35 -06003172spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003173{
qining25262b32016-05-06 17:25:16 -04003174 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003175 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003176 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003177 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003178 spv::Id result = createSpvConstant(*node);
3179 if (result != spv::NoResult)
3180 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003181 }
3182
3183 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003184 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003185 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3186 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003187
Rex Xucabbb782017-03-24 13:41:14 +08003188 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
3189 node->getType().containsBasicType(glslang::EbtInt16) ||
3190 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08003191 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003192 switch (storageClass) {
3193 case spv::StorageClassInput:
3194 case spv::StorageClassOutput:
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::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003197 break;
3198 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07003199 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003200 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06003201 break;
3202 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07003203 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003204 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3205 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003206 else
3207 builder.addCapability(spv::CapabilityStorageUniform16);
3208 break;
3209 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003210 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06003211 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
3212 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3213 break;
3214 default:
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003215 if (node->getType().containsBasicType(glslang::EbtFloat16))
3216 builder.addCapability(spv::CapabilityFloat16);
3217 if (node->getType().containsBasicType(glslang::EbtInt16) ||
3218 node->getType().containsBasicType(glslang::EbtUint16))
3219 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003220 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003221 }
3222 }
Rex Xuf89ad982017-04-07 23:22:33 +08003223
John Kessenich312dcfb2018-07-03 13:19:51 -06003224 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
3225 node->getType().containsBasicType(glslang::EbtUint8);
3226 if (contains8BitType) {
3227 if (storageClass == spv::StorageClassPushConstant) {
3228 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3229 builder.addCapability(spv::CapabilityStoragePushConstant8);
3230 } else if (storageClass == spv::StorageClassUniform) {
3231 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3232 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003233 } else if (storageClass == spv::StorageClassStorageBuffer) {
3234 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3235 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003236 } else {
3237 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003238 }
3239 }
3240
John Kessenich140f3df2015-06-26 16:58:36 -06003241 const char* name = node->getName().c_str();
3242 if (glslang::IsAnonymous(name))
3243 name = "";
3244
3245 return builder.createVariable(storageClass, spvType, name);
3246}
3247
3248// Return type Id of the sampled type.
3249spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3250{
3251 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003252 case glslang::EbtInt: return builder.makeIntType(32);
3253 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003254 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003255#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003256 case glslang::EbtFloat16:
3257 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3258 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3259 return builder.makeFloatType(16);
3260#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003261 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003262 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003263 return builder.makeFloatType(32);
3264 }
3265}
3266
John Kessenich8c8505c2016-07-26 12:50:38 -06003267// If node is a swizzle operation, return the type that should be used if
3268// the swizzle base is first consumed by another operation, before the swizzle
3269// is applied.
3270spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3271{
John Kessenichecba76f2017-01-06 00:34:48 -07003272 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003273 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3274 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3275 else
3276 return spv::NoType;
3277}
3278
3279// When inverting a swizzle with a parent op, this function
3280// will apply the swizzle operation to a completed parent operation.
3281spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3282{
3283 std::vector<unsigned> swizzle;
3284 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3285 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3286}
3287
John Kessenich8c8505c2016-07-26 12:50:38 -06003288// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3289void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3290{
3291 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3292 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3293 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3294}
3295
John Kessenich3ac051e2015-12-20 11:29:16 -07003296// Convert from a glslang type to an SPV type, by calling into a
3297// recursive version of this function. This establishes the inherited
3298// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003299spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003300{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003301 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003302}
3303
3304// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003305// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003306// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003307spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003308 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3309 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003310{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003311 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003312
3313 switch (type.getBasicType()) {
3314 case glslang::EbtVoid:
3315 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003316 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003317 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003318 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003319 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3320 // a 32-bit int where non-0 means true.
3321 if (explicitLayout != glslang::ElpNone)
3322 spvType = builder.makeUintType(32);
3323 else
3324 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003325 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003326 case glslang::EbtInt:
3327 spvType = builder.makeIntType(32);
3328 break;
3329 case glslang::EbtUint:
3330 spvType = builder.makeUintType(32);
3331 break;
3332 case glslang::EbtFloat:
3333 spvType = builder.makeFloatType(32);
3334 break;
3335#ifndef GLSLANG_WEB
3336 case glslang::EbtDouble:
3337 spvType = builder.makeFloatType(64);
3338 break;
3339 case glslang::EbtFloat16:
3340 spvType = builder.makeFloatType(16);
3341 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003342 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003343 spvType = builder.makeIntType(8);
3344 break;
3345 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003346 spvType = builder.makeUintType(8);
3347 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003348 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003349 spvType = builder.makeIntType(16);
3350 break;
3351 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003352 spvType = builder.makeUintType(16);
3353 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003354 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003355 spvType = builder.makeIntType(64);
3356 break;
3357 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003358 spvType = builder.makeUintType(64);
3359 break;
John Kessenich426394d2015-07-23 10:22:48 -06003360 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003361 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003362 spvType = builder.makeUintType(32);
3363 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003364 case glslang::EbtAccStructNV:
3365 spvType = builder.makeAccelerationStructureNVType();
3366 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003367 case glslang::EbtReference:
3368 {
3369 // Make the forward pointer, then recurse to convert the structure type, then
3370 // patch up the forward pointer with a real pointer type.
3371 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3372 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3373 forwardPointers[type.getReferentType()] = forwardId;
3374 }
3375 spvType = forwardPointers[type.getReferentType()];
3376 if (!forwardReferenceOnly) {
3377 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3378 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3379 forwardPointers[type.getReferentType()],
3380 referentType);
3381 }
3382 }
3383 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003384#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003385 case glslang::EbtSampler:
3386 {
3387 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003388 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003389 spvType = builder.makeSamplerType();
3390 } else {
3391 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003392 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3393 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3394 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3395 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003396 // already has both image and sampler, make the combined type
3397 spvType = builder.makeSampledImageType(spvType);
3398 }
John Kessenich55e7d112015-11-15 21:33:39 -07003399 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003400 }
John Kessenich140f3df2015-06-26 16:58:36 -06003401 break;
3402 case glslang::EbtStruct:
3403 case glslang::EbtBlock:
3404 {
3405 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003406 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003407
3408 // Try to share structs for different layouts, but not yet for other
3409 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003410 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003411 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003412 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003413 break;
3414
3415 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003416 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003417 memberRemapper[glslangMembers].resize(glslangMembers->size());
3418 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003419 }
3420 break;
3421 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003422 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003423 break;
3424 }
3425
3426 if (type.isMatrix())
3427 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3428 else {
3429 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3430 if (type.getVectorSize() > 1)
3431 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3432 }
3433
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003434 if (type.isCoopMat()) {
3435 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3436 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3437 if (type.getBasicType() == glslang::EbtFloat16)
3438 builder.addCapability(spv::CapabilityFloat16);
3439
3440 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3441 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3442 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3443
3444 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3445 }
3446
John Kessenich140f3df2015-06-26 16:58:36 -06003447 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003448 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3449
John Kessenichc9a80832015-09-12 12:17:44 -06003450 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003451 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003452 // We need to decorate array strides for types needing explicit layout, except blocks.
3453 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003454 // Use a dummy glslang type for querying internal strides of
3455 // arrays of arrays, but using just a one-dimensional array.
3456 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003457 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3458 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003459
3460 // Will compute the higher-order strides here, rather than making a whole
3461 // pile of types and doing repetitive recursion on their contents.
3462 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3463 }
John Kessenichf8842e52016-01-04 19:22:56 -07003464
3465 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003466 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003467 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003468 if (stride > 0)
3469 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003470 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003471 }
3472 } else {
3473 // single-dimensional array, and don't yet have stride
3474
John Kessenichf8842e52016-01-04 19:22:56 -07003475 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003476 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3477 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003478 }
John Kessenich31ed4832015-09-09 17:51:38 -06003479
John Kessenichead86222018-03-28 18:01:20 -06003480 // Do the outer dimension, which might not be known for a runtime-sized array.
3481 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3482 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003483 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003484 else {
3485 if (!lastBufferBlockMember) {
3486 builder.addExtension("SPV_EXT_descriptor_indexing");
3487 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3488 }
John Kessenichead86222018-03-28 18:01:20 -06003489 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003490 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003491 if (stride > 0)
3492 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003493 }
3494
3495 return spvType;
3496}
3497
John Kessenich0e737842017-03-24 18:38:16 -06003498// TODO: this functionality should exist at a higher level, in creating the AST
3499//
3500// Identify interface members that don't have their required extension turned on.
3501//
3502bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3503{
John Kessenicha28f7a72019-08-06 07:00:58 -06003504#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003505 auto& extensions = glslangIntermediate->getRequestedExtensions();
3506
Rex Xubcf291a2017-03-29 23:01:36 +08003507 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3508 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3509 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003510 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3511 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3512 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003513
3514 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3515 if (member.getFieldName() == "gl_ViewportMask" &&
3516 extensions.find("GL_NV_viewport_array2") == extensions.end())
3517 return true;
3518 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3519 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3520 return true;
3521 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3522 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3523 return true;
3524 }
3525#endif
John Kessenich0e737842017-03-24 18:38:16 -06003526
3527 return false;
3528};
3529
John Kessenich6090df02016-06-30 21:18:02 -06003530// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3531// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3532// Mutually recursive with convertGlslangToSpvType().
3533spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3534 const glslang::TTypeList* glslangMembers,
3535 glslang::TLayoutPacking explicitLayout,
3536 const glslang::TQualifier& qualifier)
3537{
3538 // Create a vector of struct types for SPIR-V to consume
3539 std::vector<spv::Id> spvMembers;
3540 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 -06003541 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003542 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3543 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3544 if (glslangMember.hiddenMember()) {
3545 ++memberDelta;
3546 if (type.getBasicType() == glslang::EbtBlock)
3547 memberRemapper[glslangMembers][i] = -1;
3548 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003549 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003550 if (filterMember(glslangMember)) {
3551 memberDelta++;
3552 memberRemapper[glslangMembers][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003553 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003554 }
3555 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003556 }
John Kessenich6090df02016-06-30 21:18:02 -06003557 // modify just this child's view of the qualifier
3558 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3559 InheritQualifiers(memberQualifier, qualifier);
3560
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003561 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003562 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003563 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003564
3565 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003566 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3567 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003568
3569 // Make forward pointers for any pointer members, and create a list of members to
3570 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003571 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003572 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3573 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3574 }
3575 spvMembers.push_back(
3576 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3577 } else {
3578 spvMembers.push_back(
3579 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3580 }
John Kessenich6090df02016-06-30 21:18:02 -06003581 }
3582 }
3583
3584 // Make the SPIR-V type
3585 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003586 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003587 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3588
3589 // Decorate it
3590 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3591
John Kessenichd72f4882019-01-16 14:55:37 +07003592 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003593 auto it = deferredForwardPointers[i];
3594 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3595 }
3596
John Kessenich6090df02016-06-30 21:18:02 -06003597 return spvType;
3598}
3599
3600void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3601 const glslang::TTypeList* glslangMembers,
3602 glslang::TLayoutPacking explicitLayout,
3603 const glslang::TQualifier& qualifier,
3604 spv::Id spvType)
3605{
3606 // Name and decorate the non-hidden members
3607 int offset = -1;
3608 int locationOffset = 0; // for use within the members of this struct
3609 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3610 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3611 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003612 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003613 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003614 if (filterMember(glslangMember))
3615 continue;
3616 }
John Kessenich6090df02016-06-30 21:18:02 -06003617
3618 // modify just this child's view of the qualifier
3619 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3620 InheritQualifiers(memberQualifier, qualifier);
3621
3622 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003623 if (member < 0)
3624 continue;
3625
3626 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3627 builder.addMemberDecoration(spvType, member,
3628 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3629 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3630 // Add interpolation and auxiliary storage decorations only to
3631 // top-level members of Input and Output storage classes
3632 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3633 type.getQualifier().storage == glslang::EvqVaryingOut) {
3634 if (type.getBasicType() == glslang::EbtBlock ||
3635 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3636 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3637 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003638#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003639 addMeshNVDecoration(spvType, member, memberQualifier);
3640#endif
John Kessenich6090df02016-06-30 21:18:02 -06003641 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003642 }
3643 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003644
John Kessenich5d610ee2018-03-07 18:05:55 -07003645 if (type.getBasicType() == glslang::EbtBlock &&
3646 qualifier.storage == glslang::EvqBuffer) {
3647 // Add memory decorations only to top-level members of shader storage block
3648 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003649 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003650 for (unsigned int i = 0; i < memory.size(); ++i)
3651 builder.addMemberDecoration(spvType, member, memory[i]);
3652 }
John Kessenich6090df02016-06-30 21:18:02 -06003653
John Kessenich5d610ee2018-03-07 18:05:55 -07003654 // Location assignment was already completed correctly by the front end,
3655 // just track whether a member needs to be decorated.
3656 // Ignore member locations if the container is an array, as that's
3657 // ill-specified and decisions have been made to not allow this.
3658 if (! type.isArray() && memberQualifier.hasLocation())
3659 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003660
John Kessenich5d610ee2018-03-07 18:05:55 -07003661 if (qualifier.hasLocation()) // track for upcoming inheritance
3662 locationOffset += glslangIntermediate->computeTypeLocationSize(
3663 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003664
John Kessenich5d610ee2018-03-07 18:05:55 -07003665 // component, XFB, others
3666 if (glslangMember.getQualifier().hasComponent())
3667 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3668 glslangMember.getQualifier().layoutComponent);
3669 if (glslangMember.getQualifier().hasXfbOffset())
3670 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3671 glslangMember.getQualifier().layoutXfbOffset);
3672 else if (explicitLayout != glslang::ElpNone) {
3673 // figure out what to do with offset, which is accumulating
3674 int nextOffset;
3675 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3676 if (offset >= 0)
3677 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3678 offset = nextOffset;
3679 }
John Kessenich6090df02016-06-30 21:18:02 -06003680
John Kessenich5d610ee2018-03-07 18:05:55 -07003681 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3682 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3683 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003684
John Kessenich5d610ee2018-03-07 18:05:55 -07003685 // built-in variable decorations
3686 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3687 if (builtIn != spv::BuiltInMax)
3688 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003689
John Kessenich5611c6d2018-04-05 11:25:02 -06003690 // nonuniform
3691 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3692
John Kessenichead86222018-03-28 18:01:20 -06003693 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3694 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3695 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3696 memberQualifier.semanticName);
3697 }
3698
John Kessenicha28f7a72019-08-06 07:00:58 -06003699#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003700 if (builtIn == spv::BuiltInLayer) {
3701 // SPV_NV_viewport_array2 extension
3702 if (glslangMember.getQualifier().layoutViewportRelative){
3703 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3704 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3705 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003706 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003707 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3708 builder.addMemberDecoration(spvType, member,
3709 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3710 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3711 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3712 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003713 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003714 }
3715 if (glslangMember.getQualifier().layoutPassthrough) {
3716 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3717 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3718 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3719 }
chaoc771d89f2017-01-13 01:10:53 -08003720#endif
John Kessenich6090df02016-06-30 21:18:02 -06003721 }
3722
3723 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003724 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3725 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003726}
3727
John Kessenich6c292d32016-02-15 20:58:50 -07003728// Turn the expression forming the array size into an id.
3729// This is not quite trivial, because of specialization constants.
3730// Sometimes, a raw constant is turned into an Id, and sometimes
3731// a specialization constant expression is.
3732spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3733{
3734 // First, see if this is sized with a node, meaning a specialization constant:
3735 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3736 if (specNode != nullptr) {
3737 builder.clearAccessChain();
3738 specNode->traverse(this);
3739 return accessChainLoad(specNode->getAsTyped()->getType());
3740 }
qining25262b32016-05-06 17:25:16 -04003741
John Kessenich6c292d32016-02-15 20:58:50 -07003742 // Otherwise, need a compile-time (front end) size, get it:
3743 int size = arraySizes.getDimSize(dim);
3744 assert(size > 0);
3745 return builder.makeUintConstant(size);
3746}
3747
John Kessenich103bef92016-02-08 21:38:15 -07003748// Wrap the builder's accessChainLoad to:
3749// - localize handling of RelaxedPrecision
3750// - use the SPIR-V inferred type instead of another conversion of the glslang type
3751// (avoids unnecessary work and possible type punning for structures)
3752// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003753spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3754{
John Kessenich103bef92016-02-08 21:38:15 -07003755 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003756
3757 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3758 coherentFlags |= TranslateCoherent(type);
3759
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003760 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003761 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003762
John Kessenich5611c6d2018-04-05 11:25:02 -06003763 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003764 TranslateNonUniformDecoration(type.getQualifier()),
3765 nominalTypeId,
3766 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003767 TranslateMemoryScope(coherentFlags),
3768 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003769
3770 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003771 if (type.getBasicType() == glslang::EbtBool) {
3772 if (builder.isScalarType(nominalTypeId)) {
3773 // Conversion for bool
3774 spv::Id boolType = builder.makeBoolType();
3775 if (nominalTypeId != boolType)
3776 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3777 } else if (builder.isVectorType(nominalTypeId)) {
3778 // Conversion for bvec
3779 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3780 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3781 if (nominalTypeId != bvecType)
3782 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3783 }
3784 }
John Kessenich103bef92016-02-08 21:38:15 -07003785
3786 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003787}
3788
Rex Xu27253232016-02-23 17:51:09 +08003789// Wrap the builder's accessChainStore to:
3790// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003791//
3792// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003793void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3794{
3795 // Need to convert to abstract types when necessary
3796 if (type.getBasicType() == glslang::EbtBool) {
3797 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3798
3799 if (builder.isScalarType(nominalTypeId)) {
3800 // Conversion for bool
3801 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003802 if (nominalTypeId != boolType) {
3803 // keep these outside arguments, for determinant order-of-evaluation
3804 spv::Id one = builder.makeUintConstant(1);
3805 spv::Id zero = builder.makeUintConstant(0);
3806 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3807 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003808 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003809 } else if (builder.isVectorType(nominalTypeId)) {
3810 // Conversion for bvec
3811 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3812 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003813 if (nominalTypeId != bvecType) {
3814 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003815 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3816 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3817 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003818 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003819 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3820 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003821 }
3822 }
3823
Jeff Bolz36831c92018-09-05 10:11:41 -05003824 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3825 coherentFlags |= TranslateCoherent(type);
3826
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003827 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003828 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003829
Jeff Bolz36831c92018-09-05 10:11:41 -05003830 builder.accessChainStore(rvalue,
3831 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003832 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003833}
3834
John Kessenich4bf71552016-09-02 11:20:21 -06003835// For storing when types match at the glslang level, but not might match at the
3836// SPIR-V level.
3837//
3838// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003839// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003840// as in a member-decorated way.
3841//
3842// NOTE: This function can handle any store request; if it's not special it
3843// simplifies to a simple OpStore.
3844//
3845// Implicitly uses the existing builder.accessChain as the storage target.
3846void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3847{
John Kessenichb3e24e42016-09-11 12:33:43 -06003848 // we only do the complex path here if it's an aggregate
3849 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003850 accessChainStore(type, rValue);
3851 return;
3852 }
3853
John Kessenichb3e24e42016-09-11 12:33:43 -06003854 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003855 spv::Id rType = builder.getTypeId(rValue);
3856 spv::Id lValue = builder.accessChainGetLValue();
3857 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3858 if (lType == rType) {
3859 accessChainStore(type, rValue);
3860 return;
3861 }
3862
John Kessenichb3e24e42016-09-11 12:33:43 -06003863 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003864 // where the two types were the same type in GLSL. This requires member
3865 // by member copy, recursively.
3866
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003867 // SPIR-V 1.4 added an instruction to do help do this.
3868 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3869 // However, bool in uniform space is changed to int, so
3870 // OpCopyLogical does not work for that.
3871 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3872 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3873 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3874 if (lBool == rBool) {
3875 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3876 accessChainStore(type, logicalCopy);
3877 return;
3878 }
3879 }
3880
John Kessenichb3e24e42016-09-11 12:33:43 -06003881 // If an array, copy element by element.
3882 if (type.isArray()) {
3883 glslang::TType glslangElementType(type, 0);
3884 spv::Id elementRType = builder.getContainedTypeId(rType);
3885 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3886 // get the source member
3887 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003888
John Kessenichb3e24e42016-09-11 12:33:43 -06003889 // set up the target storage
3890 builder.clearAccessChain();
3891 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003892 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003893
John Kessenichb3e24e42016-09-11 12:33:43 -06003894 // store the member
3895 multiTypeStore(glslangElementType, elementRValue);
3896 }
3897 } else {
3898 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003899
John Kessenichb3e24e42016-09-11 12:33:43 -06003900 // loop over structure members
3901 const glslang::TTypeList& members = *type.getStruct();
3902 for (int m = 0; m < (int)members.size(); ++m) {
3903 const glslang::TType& glslangMemberType = *members[m].type;
3904
3905 // get the source member
3906 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3907 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3908
3909 // set up the target storage
3910 builder.clearAccessChain();
3911 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003912 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003913
3914 // store the member
3915 multiTypeStore(glslangMemberType, memberRValue);
3916 }
John Kessenich4bf71552016-09-02 11:20:21 -06003917 }
3918}
3919
John Kessenichf85e8062015-12-19 13:57:10 -07003920// Decide whether or not this type should be
3921// decorated with offsets and strides, and if so
3922// whether std140 or std430 rules should be applied.
3923glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003924{
John Kessenichf85e8062015-12-19 13:57:10 -07003925 // has to be a block
3926 if (type.getBasicType() != glslang::EbtBlock)
3927 return glslang::ElpNone;
3928
Chao Chen3c366992018-09-19 11:41:59 -07003929 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003930 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003931 type.getQualifier().storage != glslang::EvqBuffer &&
3932 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003933 return glslang::ElpNone;
3934
3935 // return the layout to use
3936 switch (type.getQualifier().layoutPacking) {
3937 case glslang::ElpStd140:
3938 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003939 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003940 return type.getQualifier().layoutPacking;
3941 default:
3942 return glslang::ElpNone;
3943 }
John Kessenich31ed4832015-09-09 17:51:38 -06003944}
3945
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003946// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003947int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003948{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003949 int size;
John Kessenich49987892015-12-29 17:11:44 -07003950 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003951 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003952
3953 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003954}
3955
John Kessenich49987892015-12-29 17:11:44 -07003956// 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 -07003957// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003958int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003959{
John Kessenich49987892015-12-29 17:11:44 -07003960 glslang::TType elementType;
3961 elementType.shallowCopy(matrixType);
3962 elementType.clearArraySizes();
3963
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003964 int size;
John Kessenich49987892015-12-29 17:11:44 -07003965 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003966 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003967
3968 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003969}
3970
John Kessenich5e4b1242015-08-06 22:53:06 -06003971// Given a member type of a struct, realign the current offset for it, and compute
3972// the next (not yet aligned) offset for the next member, which will get aligned
3973// on the next call.
3974// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3975// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3976// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003977void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003978 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003979{
3980 // this will get a positive value when deemed necessary
3981 nextOffset = -1;
3982
John Kessenich5e4b1242015-08-06 22:53:06 -06003983 // override anything in currentOffset with user-set offset
3984 if (memberType.getQualifier().hasOffset())
3985 currentOffset = memberType.getQualifier().layoutOffset;
3986
3987 // It could be that current linker usage in glslang updated all the layoutOffset,
3988 // in which case the following code does not matter. But, that's not quite right
3989 // once cross-compilation unit GLSL validation is done, as the original user
3990 // settings are needed in layoutOffset, and then the following will come into play.
3991
John Kessenichf85e8062015-12-19 13:57:10 -07003992 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003993 if (! memberType.getQualifier().hasOffset())
3994 currentOffset = -1;
3995
3996 return;
3997 }
3998
John Kessenichf85e8062015-12-19 13:57:10 -07003999 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004000 if (currentOffset < 0)
4001 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004002
John Kessenich5e4b1242015-08-06 22:53:06 -06004003 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4004 // but possibly not yet correctly aligned.
4005
4006 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004007 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004008 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004009
4010 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004011 // TODO: make this consistent in early phases of code:
4012 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4013 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4014 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004015 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004016 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004017 int dummySize;
4018 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4019 if (componentAlignment <= 4)
4020 memberAlignment = componentAlignment;
4021 }
4022
4023 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004024 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004025
4026 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004027 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004028 glslang::RoundToPow2(currentOffset, 16);
4029
John Kessenich5e4b1242015-08-06 22:53:06 -06004030 nextOffset = currentOffset + memberSize;
4031}
4032
David Netoa901ffe2016-06-08 14:11:40 +01004033void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004034{
David Netoa901ffe2016-06-08 14:11:40 +01004035 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4036 switch (glslangBuiltIn)
4037 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004038 case glslang::EbvPointSize:
4039#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004040 case glslang::EbvClipDistance:
4041 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004042 case glslang::EbvViewportMaskNV:
4043 case glslang::EbvSecondaryPositionNV:
4044 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004045 case glslang::EbvPositionPerViewNV:
4046 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004047 case glslang::EbvTaskCountNV:
4048 case glslang::EbvPrimitiveCountNV:
4049 case glslang::EbvPrimitiveIndicesNV:
4050 case glslang::EbvClipDistancePerViewNV:
4051 case glslang::EbvCullDistancePerViewNV:
4052 case glslang::EbvLayerPerViewNV:
4053 case glslang::EbvMeshViewCountNV:
4054 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004055#endif
David Netoa901ffe2016-06-08 14:11:40 +01004056 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4057 // Alternately, we could just call this for any glslang built-in, since the
4058 // capability already guards against duplicates.
4059 TranslateBuiltInDecoration(glslangBuiltIn, false);
4060 break;
4061 default:
4062 // Capabilities were already generated when the struct was declared.
4063 break;
4064 }
John Kessenichebb50532016-05-16 19:22:05 -06004065}
4066
John Kessenich6fccb3c2016-09-19 16:01:41 -06004067bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004068{
John Kessenicheee9d532016-09-19 18:09:30 -06004069 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004070}
4071
John Kessenichd41993d2017-09-10 15:21:05 -06004072// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004073// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4074// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004075bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004076{
John Kessenich6a14f782017-12-04 02:48:10 -07004077 assert(qualifier == glslang::EvqIn ||
4078 qualifier == glslang::EvqOut ||
4079 qualifier == glslang::EvqInOut ||
4080 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004081 return qualifier != glslang::EvqConstReadOnly;
4082}
4083
4084// Is parameter pass-by-original?
4085bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4086 bool implicitThisParam)
4087{
4088 if (implicitThisParam) // implicit this
4089 return true;
4090 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004091 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004092 return paramType.containsOpaque() || // sampler, etc.
4093 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4094}
4095
John Kessenich140f3df2015-06-26 16:58:36 -06004096// Make all the functions, skeletally, without actually visiting their bodies.
4097void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4098{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004099 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004100 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4101 if (paramPrecision != spv::NoPrecision)
4102 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004103 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004104 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004105 // Original and non-writable params pass the pointer directly and
4106 // use restrict/aliased, others are stored to a pointer in Function
4107 // memory and use RestrictPointer/AliasedPointer.
4108 if (originalParam(type.getQualifier().storage, type, false) ||
4109 !writableParam(type.getQualifier().storage)) {
4110 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
4111 } else {
4112 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
4113 }
4114 }
John Kessenichfad62972017-07-18 02:35:46 -06004115 };
4116
John Kessenich140f3df2015-06-26 16:58:36 -06004117 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4118 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004119 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004120 continue;
4121
4122 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004123 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004124 //
qining25262b32016-05-06 17:25:16 -04004125 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004126 // function. What it is an address of varies:
4127 //
John Kessenich4bf71552016-09-02 11:20:21 -06004128 // - "in" parameters not marked as "const" can be written to without modifying the calling
4129 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004130 //
4131 // - "const in" parameters can just be the r-value, as no writes need occur.
4132 //
John Kessenich4bf71552016-09-02 11:20:21 -06004133 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4134 // 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 -06004135
4136 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004137 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004138 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4139
John Kessenich155d3512019-08-08 23:29:20 -06004140#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004141 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4142 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004143#else
4144 bool implicitThis = false;
4145#endif
John Kessenich37789792017-03-21 23:56:40 -06004146
John Kessenichfad62972017-07-18 02:35:46 -06004147 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004148 for (int p = 0; p < (int)parameters.size(); ++p) {
4149 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4150 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004151 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004152 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004153 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004154 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4155 else
John Kessenich4bf71552016-09-02 11:20:21 -06004156 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004157 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004158 paramTypes.push_back(typeId);
4159 }
4160
4161 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004162 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4163 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004164 glslFunction->getName().c_str(), paramTypes,
4165 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004166 if (implicitThis)
4167 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004168
4169 // Track function to emit/call later
4170 functionMap[glslFunction->getName().c_str()] = function;
4171
4172 // Set the parameter id's
4173 for (int p = 0; p < (int)parameters.size(); ++p) {
4174 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4175 // give a name too
4176 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004177
4178 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4179 if (paramType.containsBasicType(glslang::EbtInt8) ||
4180 paramType.containsBasicType(glslang::EbtUint8))
4181 builder.addCapability(spv::CapabilityInt8);
4182 if (paramType.containsBasicType(glslang::EbtInt16) ||
4183 paramType.containsBasicType(glslang::EbtUint16))
4184 builder.addCapability(spv::CapabilityInt16);
4185 if (paramType.containsBasicType(glslang::EbtFloat16))
4186 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004187 }
4188 }
4189}
4190
4191// Process all the initializers, while skipping the functions and link objects
4192void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4193{
4194 builder.setBuildPoint(shaderEntry->getLastBlock());
4195 for (int i = 0; i < (int)initializers.size(); ++i) {
4196 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
4197 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
4198
4199 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004200 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004201 initializer->traverse(this);
4202 }
4203 }
4204}
4205
4206// Process all the functions, while skipping initializers.
4207void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4208{
4209 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4210 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004211 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004212 node->traverse(this);
4213 }
4214}
4215
4216void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4217{
qining25262b32016-05-06 17:25:16 -04004218 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004219 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004220 currentFunction = functionMap[node->getName().c_str()];
4221 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004222 builder.setBuildPoint(functionBlock);
4223}
4224
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004225void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004226{
Rex Xufc618912015-09-09 16:42:49 +08004227 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004228
4229 glslang::TSampler sampler = {};
4230 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004231#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004232 bool f16ShadowCompare = false;
4233#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004234 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004235 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4236 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004237#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004238 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4239#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004240 }
4241
John Kessenich140f3df2015-06-26 16:58:36 -06004242 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4243 builder.clearAccessChain();
4244 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004245
John Kessenicha28f7a72019-08-06 07:00:58 -06004246#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004247 // Special case l-value operands
4248 bool lvalue = false;
4249 switch (node.getOp()) {
4250 case glslang::EOpImageAtomicAdd:
4251 case glslang::EOpImageAtomicMin:
4252 case glslang::EOpImageAtomicMax:
4253 case glslang::EOpImageAtomicAnd:
4254 case glslang::EOpImageAtomicOr:
4255 case glslang::EOpImageAtomicXor:
4256 case glslang::EOpImageAtomicExchange:
4257 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004258 case glslang::EOpImageAtomicLoad:
4259 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004260 if (i == 0)
4261 lvalue = true;
4262 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004263 case glslang::EOpSparseImageLoad:
4264 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4265 lvalue = true;
4266 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004267 case glslang::EOpSparseTexture:
4268 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4269 lvalue = true;
4270 break;
4271 case glslang::EOpSparseTextureClamp:
4272 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4273 lvalue = true;
4274 break;
4275 case glslang::EOpSparseTextureLod:
4276 case glslang::EOpSparseTextureOffset:
4277 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4278 lvalue = true;
4279 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004280 case glslang::EOpSparseTextureFetch:
4281 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4282 lvalue = true;
4283 break;
4284 case glslang::EOpSparseTextureFetchOffset:
4285 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4286 lvalue = true;
4287 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004288 case glslang::EOpSparseTextureLodOffset:
4289 case glslang::EOpSparseTextureGrad:
4290 case glslang::EOpSparseTextureOffsetClamp:
4291 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4292 lvalue = true;
4293 break;
4294 case glslang::EOpSparseTextureGradOffset:
4295 case glslang::EOpSparseTextureGradClamp:
4296 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4297 lvalue = true;
4298 break;
4299 case glslang::EOpSparseTextureGradOffsetClamp:
4300 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4301 lvalue = true;
4302 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004303 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004304 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4305 lvalue = true;
4306 break;
4307 case glslang::EOpSparseTextureGatherOffset:
4308 case glslang::EOpSparseTextureGatherOffsets:
4309 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4310 lvalue = true;
4311 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004312 case glslang::EOpSparseTextureGatherLod:
4313 if (i == 3)
4314 lvalue = true;
4315 break;
4316 case glslang::EOpSparseTextureGatherLodOffset:
4317 case glslang::EOpSparseTextureGatherLodOffsets:
4318 if (i == 4)
4319 lvalue = true;
4320 break;
Rex Xu129799a2017-07-05 17:23:28 +08004321 case glslang::EOpSparseImageLoadLod:
4322 if (i == 3)
4323 lvalue = true;
4324 break;
Chao Chen3a137962018-09-19 11:41:27 -07004325 case glslang::EOpImageSampleFootprintNV:
4326 if (i == 4)
4327 lvalue = true;
4328 break;
4329 case glslang::EOpImageSampleFootprintClampNV:
4330 case glslang::EOpImageSampleFootprintLodNV:
4331 if (i == 5)
4332 lvalue = true;
4333 break;
4334 case glslang::EOpImageSampleFootprintGradNV:
4335 if (i == 6)
4336 lvalue = true;
4337 break;
4338 case glslang::EOpImageSampleFootprintGradClampNV:
4339 if (i == 7)
4340 lvalue = true;
4341 break;
Rex Xufc618912015-09-09 16:42:49 +08004342 default:
4343 break;
4344 }
4345
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004346 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004347 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004348 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4349 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4350 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004351#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004352 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004353 }
4354}
4355
John Kessenichfc51d282015-08-19 13:34:18 -06004356void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004357{
John Kessenichfc51d282015-08-19 13:34:18 -06004358 builder.clearAccessChain();
4359 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004360 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004361}
John Kessenich140f3df2015-06-26 16:58:36 -06004362
John Kessenichfc51d282015-08-19 13:34:18 -06004363spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4364{
John Kesseniche485c7a2017-05-31 18:50:53 -06004365 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004366 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004367
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004368 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004369
John Kessenichfc51d282015-08-19 13:34:18 -06004370 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004371
John Kessenichf43c7392019-03-31 10:51:57 -06004372 const glslang::TType &imageType = node->getAsAggregate()
4373 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4374 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004375 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004376#ifdef GLSLANG_WEB
4377 const bool f16ShadowCompare = false;
4378#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004379 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004380 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4381 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004382#endif
4383
John Kessenichf43c7392019-03-31 10:51:57 -06004384 const auto signExtensionMask = [&]() {
4385 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4386 if (sampler.type == glslang::EbtUint)
4387 return spv::ImageOperandsZeroExtendMask;
4388 else if (sampler.type == glslang::EbtInt)
4389 return spv::ImageOperandsSignExtendMask;
4390 }
4391 return spv::ImageOperandsMaskNone;
4392 };
4393
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004394 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4395
John Kessenichfc51d282015-08-19 13:34:18 -06004396 std::vector<spv::Id> arguments;
4397 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004398 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004399 else
4400 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004401 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004402
4403 spv::Builder::TextureParameters params = { };
4404 params.sampler = arguments[0];
4405
Rex Xu04db3f52015-09-16 11:44:02 +08004406 glslang::TCrackedTextureOp cracked;
4407 node->crackTexture(sampler, cracked);
4408
amhagan05506bb2017-06-13 16:53:02 -04004409 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004410
John Kessenichfc51d282015-08-19 13:34:18 -06004411 // Check for queries
4412 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004413 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4414 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004415 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004416
John Kessenichfc51d282015-08-19 13:34:18 -06004417 switch (node->getOp()) {
4418 case glslang::EOpImageQuerySize:
4419 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004420 if (arguments.size() > 1) {
4421 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004422 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004423 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004424 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004425#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004426 case glslang::EOpImageQuerySamples:
4427 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004428 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004429 case glslang::EOpTextureQueryLod:
4430 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004431 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004432 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004433 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004434 case glslang::EOpSparseTexelsResident:
4435 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004436#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004437 default:
4438 assert(0);
4439 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004440 }
John Kessenich140f3df2015-06-26 16:58:36 -06004441 }
4442
LoopDawg4425f242018-02-18 11:40:01 -07004443 int components = node->getType().getVectorSize();
4444
4445 if (node->getOp() == glslang::EOpTextureFetch) {
4446 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4447 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4448 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4449 // here around e.g. which ones return scalars or other types.
4450 components = 4;
4451 }
4452
4453 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4454
4455 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4456
Rex Xufc618912015-09-09 16:42:49 +08004457 // Check for image functions other than queries
4458 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004459 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004460 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004461 spv::IdImmediate image = { true, *(opIt++) };
4462 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004463
4464 // Handle subpass operations
4465 // TODO: GLSL should change to have the "MS" only on the type rather than the
4466 // built-in function.
4467 if (cracked.subpass) {
4468 // add on the (0,0) coordinate
4469 spv::Id zero = builder.makeIntConstant(0);
4470 std::vector<spv::Id> comps;
4471 comps.push_back(zero);
4472 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004473 spv::IdImmediate coord = { true,
4474 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4475 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004476 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4477 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004478 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004479 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4480 }
4481 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004482 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004483 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004484 spv::IdImmediate imageOperand = { true, *(opIt++) };
4485 operands.push_back(imageOperand);
4486 }
John Kessenich6c292d32016-02-15 20:58:50 -07004487 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004488 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4489 builder.setPrecision(result, precision);
4490 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004491 }
4492
John Kessenich149afc32018-08-14 13:31:43 -06004493 spv::IdImmediate coord = { true, *(opIt++) };
4494 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004495 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004496 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004497 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004498 mask = mask | spv::ImageOperandsSampleMask;
4499 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004500 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004501 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4502 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004503 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004504 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004505 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4506 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004507 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004508 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004509 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4510 operands.push_back(imageOperands);
4511 }
4512 if (mask & spv::ImageOperandsSampleMask) {
4513 spv::IdImmediate imageOperand = { true, *opIt++ };
4514 operands.push_back(imageOperand);
4515 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004516 if (mask & spv::ImageOperandsLodMask) {
4517 spv::IdImmediate imageOperand = { true, *opIt++ };
4518 operands.push_back(imageOperand);
4519 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004520 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004521 spv::IdImmediate imageOperand = { true,
4522 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004523 operands.push_back(imageOperand);
4524 }
4525
John Kessenich149afc32018-08-14 13:31:43 -06004526 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004527 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004528
John Kessenich149afc32018-08-14 13:31:43 -06004529 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004530 builder.setPrecision(result[0], precision);
4531
4532 // If needed, add a conversion constructor to the proper size.
4533 if (components != node->getType().getVectorSize())
4534 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4535
4536 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004537 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004538
Jeff Bolz36831c92018-09-05 10:11:41 -05004539 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004540 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004541 spv::IdImmediate texel = { true, *(opIt + 1) };
4542 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004543 } else {
4544 spv::IdImmediate texel = { true, *opIt };
4545 operands.push_back(texel);
4546 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004547
4548 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004549 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004550 mask = mask | spv::ImageOperandsSampleMask;
4551 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004552 if (cracked.lod) {
4553 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4554 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4555 mask = mask | spv::ImageOperandsLodMask;
4556 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004557 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4558 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004559 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004560 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004561 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4562 operands.push_back(imageOperands);
4563 }
4564 if (mask & spv::ImageOperandsSampleMask) {
4565 spv::IdImmediate imageOperand = { true, *opIt++ };
4566 operands.push_back(imageOperand);
4567 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004568 if (mask & spv::ImageOperandsLodMask) {
4569 spv::IdImmediate imageOperand = { true, *opIt++ };
4570 operands.push_back(imageOperand);
4571 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004572 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004573 spv::IdImmediate imageOperand = { true,
4574 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004575 operands.push_back(imageOperand);
4576 }
4577
John Kessenich56bab042015-09-16 10:54:31 -06004578 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004579 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004580 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004581 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004582 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4583 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004584 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004585 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004586 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4587
Jeff Bolz36831c92018-09-05 10:11:41 -05004588 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004589 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004590 mask = mask | spv::ImageOperandsSampleMask;
4591 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004592 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004593 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4594 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4595
Jeff Bolz36831c92018-09-05 10:11:41 -05004596 mask = mask | spv::ImageOperandsLodMask;
4597 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004598 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4599 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004600 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004601 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004602 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004603 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004604 }
4605 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004606 spv::IdImmediate imageOperand = { true, *opIt++ };
4607 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004608 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004609 if (mask & spv::ImageOperandsLodMask) {
4610 spv::IdImmediate imageOperand = { true, *opIt++ };
4611 operands.push_back(imageOperand);
4612 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004613 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4614 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4615 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004616 }
4617
4618 // Create the return type that was a special structure
4619 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004620 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004621 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4622 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4623
4624 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4625
4626 // Decode the return type
4627 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4628 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004629 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004630 // Process image atomic operations
4631
4632 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4633 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004634 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004635 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004636 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004637
Jeff Bolz36831c92018-09-05 10:11:41 -05004638 spv::Id resultTypeId;
4639 // imageAtomicStore has a void return type so base the pointer type on
4640 // the type of the value operand.
4641 if (node->getOp() == glslang::EOpImageAtomicStore) {
4642 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4643 } else {
4644 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4645 }
John Kessenich56bab042015-09-16 10:54:31 -06004646 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004647
4648 std::vector<spv::Id> operands;
4649 operands.push_back(pointer);
4650 for (; opIt != arguments.end(); ++opIt)
4651 operands.push_back(*opIt);
4652
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004653 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004654 }
4655 }
4656
John Kessenicha28f7a72019-08-06 07:00:58 -06004657#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004658 // Check for fragment mask functions other than queries
4659 if (cracked.fragMask) {
4660 assert(sampler.ms);
4661
4662 auto opIt = arguments.begin();
4663 std::vector<spv::Id> operands;
4664
4665 // Extract the image if necessary
4666 if (builder.isSampledImage(params.sampler))
4667 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4668
4669 operands.push_back(params.sampler);
4670 ++opIt;
4671
4672 if (sampler.isSubpass()) {
4673 // add on the (0,0) coordinate
4674 spv::Id zero = builder.makeIntConstant(0);
4675 std::vector<spv::Id> comps;
4676 comps.push_back(zero);
4677 comps.push_back(zero);
4678 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4679 }
4680
4681 for (; opIt != arguments.end(); ++opIt)
4682 operands.push_back(*opIt);
4683
4684 spv::Op fragMaskOp = spv::OpNop;
4685 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4686 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4687 else if (node->getOp() == glslang::EOpFragmentFetch)
4688 fragMaskOp = spv::OpFragmentFetchAMD;
4689
4690 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4691 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4692 return builder.createOp(fragMaskOp, resultType(), operands);
4693 }
4694#endif
4695
Rex Xufc618912015-09-09 16:42:49 +08004696 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004697 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004698 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004699 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08004700
John Kessenichfc51d282015-08-19 13:34:18 -06004701 // check for bias argument
4702 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004703 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004704 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004705 if (cracked.gather)
4706 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004707
4708 if (f16ShadowCompare)
4709 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004710 if (cracked.offset)
4711 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004712 else if (cracked.offsets)
4713 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004714 if (cracked.grad)
4715 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004716 if (cracked.lodClamp)
4717 ++nonBiasArgCount;
4718 if (sparse)
4719 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004720 if (imageFootprint)
4721 //Following three extra arguments
4722 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4723 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06004724 if ((int)arguments.size() > nonBiasArgCount)
4725 bias = true;
4726 }
4727
John Kessenicha5c33d62016-06-02 23:45:21 -06004728 // See if the sampler param should really be just the SPV image part
4729 if (cracked.fetch) {
4730 // a fetch needs to have the image extracted first
4731 if (builder.isSampledImage(params.sampler))
4732 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4733 }
4734
John Kessenicha28f7a72019-08-06 07:00:58 -06004735#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08004736 if (cracked.gather) {
4737 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4738 if (bias || cracked.lod ||
4739 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4740 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004741 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004742 }
4743 }
4744#endif
4745
John Kessenichfc51d282015-08-19 13:34:18 -06004746 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004747
John Kessenichfc51d282015-08-19 13:34:18 -06004748 params.coords = arguments[1];
4749 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004750 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004751
4752 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004753 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06004754 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004755 ++extraArgs;
4756 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004757 params.Dref = arguments[2];
4758 ++extraArgs;
4759 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004760 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004761 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004762 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004763 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004764 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004765 dRefComp = builder.getNumComponents(params.coords) - 1;
4766 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004767 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4768 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004769
4770 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004771 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004772 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004773 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004774 } else if (glslangIntermediate->getStage() != EShLangFragment
John Kessenicha28f7a72019-08-06 07:00:58 -06004775#ifndef GLSLANG_WEB
Chao Chenbeae2252018-09-19 11:40:45 -07004776 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4777 && !(glslangIntermediate->getStage() == EShLangCompute &&
4778 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4779#endif
4780 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004781 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4782 noImplicitLod = true;
4783 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004784
4785 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004786 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004787 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004788 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004789 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004790
4791 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004792 if (cracked.grad) {
4793 params.gradX = arguments[2 + extraArgs];
4794 params.gradY = arguments[3 + extraArgs];
4795 extraArgs += 2;
4796 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004797
4798 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004799 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004800 params.offset = arguments[2 + extraArgs];
4801 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004802 } else if (cracked.offsets) {
4803 params.offsets = arguments[2 + extraArgs];
4804 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004805 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004806
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004807#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06004808 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004809 if (cracked.lodClamp) {
4810 params.lodClamp = arguments[2 + extraArgs];
4811 ++extraArgs;
4812 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004813 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004814 if (sparse) {
4815 params.texelOut = arguments[2 + extraArgs];
4816 ++extraArgs;
4817 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004818 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004819 if (cracked.gather && ! sampler.shadow) {
4820 // default component is 0, if missing, otherwise an argument
4821 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004822 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004823 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004824 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004825 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004826 }
Chao Chen3a137962018-09-19 11:41:27 -07004827 spv::Id resultStruct = spv::NoResult;
4828 if (imageFootprint) {
4829 //Following three extra arguments
4830 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4831 params.granularity = arguments[2 + extraArgs];
4832 params.coarse = arguments[3 + extraArgs];
4833 resultStruct = arguments[4 + extraArgs];
4834 extraArgs += 3;
4835 }
4836#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004837 // bias
4838 if (bias) {
4839 params.bias = arguments[2 + extraArgs];
4840 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004841 }
John Kessenichfc51d282015-08-19 13:34:18 -06004842
John Kessenicha28f7a72019-08-06 07:00:58 -06004843#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07004844 if (imageFootprint) {
4845 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4846 builder.addCapability(spv::CapabilityImageFootprintNV);
4847
4848
4849 //resultStructType(OpenGL type) contains 5 elements:
4850 //struct gl_TextureFootprint2DNV {
4851 // uvec2 anchor;
4852 // uvec2 offset;
4853 // uvec2 mask;
4854 // uint lod;
4855 // uint granularity;
4856 //};
4857 //or
4858 //struct gl_TextureFootprint3DNV {
4859 // uvec3 anchor;
4860 // uvec3 offset;
4861 // uvec2 mask;
4862 // uint lod;
4863 // uint granularity;
4864 //};
4865 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4866 assert(builder.isStructType(resultStructType));
4867
4868 //resType (SPIR-V type) contains 6 elements:
4869 //Member 0 must be a Boolean type scalar(LOD),
4870 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4871 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4872 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4873 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4874 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4875 std::vector<spv::Id> members;
4876 members.push_back(resultType());
4877 for (int i = 0; i < 5; i++) {
4878 members.push_back(builder.getContainedTypeId(resultStructType, i));
4879 }
4880 spv::Id resType = builder.makeStructType(members, "ResType");
4881
4882 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06004883 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
4884 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07004885
4886 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4887 for (int i = 0; i < 5; i++) {
4888 builder.clearAccessChain();
4889 builder.setAccessChainLValue(resultStruct);
4890
4891 //Accessing to a struct we created, no coherent flag is set
4892 spv::Builder::AccessChain::CoherentFlags flags;
4893 flags.clear();
4894
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004895 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004896 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4897 }
4898 return builder.createCompositeExtract(res, resultType(), 0);
4899 }
4900#endif
4901
John Kessenich65336482016-06-16 14:06:26 -06004902 // projective component (might not to move)
4903 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4904 // are divided by the last component of P."
4905 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4906 // unused components will appear after all used components."
4907 if (cracked.proj) {
4908 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4909 int projTargetComp;
4910 switch (sampler.dim) {
4911 case glslang::Esd1D: projTargetComp = 1; break;
4912 case glslang::Esd2D: projTargetComp = 2; break;
4913 case glslang::EsdRect: projTargetComp = 2; break;
4914 default: projTargetComp = projSourceComp; break;
4915 }
4916 // copy the projective coordinate if we have to
4917 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004918 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004919 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4920 projSourceComp);
4921 params.coords = builder.createCompositeInsert(projComp, params.coords,
4922 builder.getTypeId(params.coords), projTargetComp);
4923 }
4924 }
4925
Jeff Bolz36831c92018-09-05 10:11:41 -05004926 // nonprivate
4927 if (imageType.getQualifier().nonprivate) {
4928 params.nonprivate = true;
4929 }
4930
4931 // volatile
4932 if (imageType.getQualifier().volatil) {
4933 params.volatil = true;
4934 }
4935
St0fFa1184dd2018-04-09 21:08:14 +02004936 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06004937 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
4938 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02004939 );
LoopDawg4425f242018-02-18 11:40:01 -07004940
4941 if (components != node->getType().getVectorSize())
4942 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4943
4944 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004945}
4946
4947spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4948{
4949 // Grab the function's pointer from the previously created function
4950 spv::Function* function = functionMap[node->getName().c_str()];
4951 if (! function)
4952 return 0;
4953
4954 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4955 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4956
4957 // See comments in makeFunctions() for details about the semantics for parameter passing.
4958 //
4959 // These imply we need a four step process:
4960 // 1. Evaluate the arguments
4961 // 2. Allocate and make copies of in, out, and inout arguments
4962 // 3. Make the call
4963 // 4. Copy back the results
4964
John Kessenichd3ed90b2018-05-04 11:43:03 -06004965 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004966 std::vector<spv::Builder::AccessChain> lValues;
4967 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004968 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004969 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004970 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004971 // build l-value
4972 builder.clearAccessChain();
4973 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004974 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004975 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004976 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004977 // save l-value
4978 lValues.push_back(builder.getAccessChain());
4979 } else {
4980 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004981 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004982 }
4983 }
4984
4985 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4986 // copy the original into that space.
4987 //
4988 // Also, build up the list of actual arguments to pass in for the call
4989 int lValueCount = 0;
4990 int rValueCount = 0;
4991 std::vector<spv::Id> spvArgs;
4992 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4993 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004994 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004995 builder.setAccessChain(lValues[lValueCount]);
4996 arg = builder.accessChainGetLValue();
4997 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004998 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004999 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06005000 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005001 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5002 // need to copy the input into output space
5003 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005004 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005005 builder.clearAccessChain();
5006 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005007 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005008 }
5009 ++lValueCount;
5010 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005011 // process r-value, which involves a copy for a type mismatch
5012 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5013 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5014 builder.clearAccessChain();
5015 builder.setAccessChainLValue(argCopy);
5016 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5017 arg = builder.createLoad(argCopy);
5018 } else
5019 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005020 ++rValueCount;
5021 }
5022 spvArgs.push_back(arg);
5023 }
5024
5025 // 3. Make the call.
5026 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005027 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005028
5029 // 4. Copy back out an "out" arguments.
5030 lValueCount = 0;
5031 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005032 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005033 ++lValueCount;
5034 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005035 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5036 spv::Id copy = builder.createLoad(spvArgs[a]);
5037 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005038 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005039 }
5040 ++lValueCount;
5041 }
5042 }
5043
5044 return result;
5045}
5046
5047// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005048spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005049 spv::Id typeId, spv::Id left, spv::Id right,
5050 glslang::TBasicType typeProxy, bool reduceComparison)
5051{
John Kessenich66011cb2018-03-06 16:12:04 -07005052 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5053 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005054 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005055
5056 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005057 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005058 bool comparison = false;
5059
5060 switch (op) {
5061 case glslang::EOpAdd:
5062 case glslang::EOpAddAssign:
5063 if (isFloat)
5064 binOp = spv::OpFAdd;
5065 else
5066 binOp = spv::OpIAdd;
5067 break;
5068 case glslang::EOpSub:
5069 case glslang::EOpSubAssign:
5070 if (isFloat)
5071 binOp = spv::OpFSub;
5072 else
5073 binOp = spv::OpISub;
5074 break;
5075 case glslang::EOpMul:
5076 case glslang::EOpMulAssign:
5077 if (isFloat)
5078 binOp = spv::OpFMul;
5079 else
5080 binOp = spv::OpIMul;
5081 break;
5082 case glslang::EOpVectorTimesScalar:
5083 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005084 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005085 if (builder.isVector(right))
5086 std::swap(left, right);
5087 assert(builder.isScalar(right));
5088 needMatchingVectors = false;
5089 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005090 } else if (isFloat)
5091 binOp = spv::OpFMul;
5092 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005093 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005094 break;
5095 case glslang::EOpVectorTimesMatrix:
5096 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005097 binOp = spv::OpVectorTimesMatrix;
5098 break;
5099 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005100 binOp = spv::OpMatrixTimesVector;
5101 break;
5102 case glslang::EOpMatrixTimesScalar:
5103 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005104 binOp = spv::OpMatrixTimesScalar;
5105 break;
5106 case glslang::EOpMatrixTimesMatrix:
5107 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005108 binOp = spv::OpMatrixTimesMatrix;
5109 break;
5110 case glslang::EOpOuterProduct:
5111 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005112 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005113 break;
5114
5115 case glslang::EOpDiv:
5116 case glslang::EOpDivAssign:
5117 if (isFloat)
5118 binOp = spv::OpFDiv;
5119 else if (isUnsigned)
5120 binOp = spv::OpUDiv;
5121 else
5122 binOp = spv::OpSDiv;
5123 break;
5124 case glslang::EOpMod:
5125 case glslang::EOpModAssign:
5126 if (isFloat)
5127 binOp = spv::OpFMod;
5128 else if (isUnsigned)
5129 binOp = spv::OpUMod;
5130 else
5131 binOp = spv::OpSMod;
5132 break;
5133 case glslang::EOpRightShift:
5134 case glslang::EOpRightShiftAssign:
5135 if (isUnsigned)
5136 binOp = spv::OpShiftRightLogical;
5137 else
5138 binOp = spv::OpShiftRightArithmetic;
5139 break;
5140 case glslang::EOpLeftShift:
5141 case glslang::EOpLeftShiftAssign:
5142 binOp = spv::OpShiftLeftLogical;
5143 break;
5144 case glslang::EOpAnd:
5145 case glslang::EOpAndAssign:
5146 binOp = spv::OpBitwiseAnd;
5147 break;
5148 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005149 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005150 binOp = spv::OpLogicalAnd;
5151 break;
5152 case glslang::EOpInclusiveOr:
5153 case glslang::EOpInclusiveOrAssign:
5154 binOp = spv::OpBitwiseOr;
5155 break;
5156 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005157 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005158 binOp = spv::OpLogicalOr;
5159 break;
5160 case glslang::EOpExclusiveOr:
5161 case glslang::EOpExclusiveOrAssign:
5162 binOp = spv::OpBitwiseXor;
5163 break;
5164 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005165 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005166 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005167 break;
5168
5169 case glslang::EOpLessThan:
5170 case glslang::EOpGreaterThan:
5171 case glslang::EOpLessThanEqual:
5172 case glslang::EOpGreaterThanEqual:
5173 case glslang::EOpEqual:
5174 case glslang::EOpNotEqual:
5175 case glslang::EOpVectorEqual:
5176 case glslang::EOpVectorNotEqual:
5177 comparison = true;
5178 break;
5179 default:
5180 break;
5181 }
5182
John Kessenich7c1aa102015-10-15 13:29:11 -06005183 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005184 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005185 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005186 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5187 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005188 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005189
5190 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005191 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005192 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005193
qining25262b32016-05-06 17:25:16 -04005194 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005195 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005196 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005197 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005198 }
5199
5200 if (! comparison)
5201 return 0;
5202
John Kessenich7c1aa102015-10-15 13:29:11 -06005203 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005204
John Kessenich4583b612016-08-07 19:14:22 -06005205 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005206 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5207 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06005208 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005209 return result;
5210 }
John Kessenich140f3df2015-06-26 16:58:36 -06005211
5212 switch (op) {
5213 case glslang::EOpLessThan:
5214 if (isFloat)
5215 binOp = spv::OpFOrdLessThan;
5216 else if (isUnsigned)
5217 binOp = spv::OpULessThan;
5218 else
5219 binOp = spv::OpSLessThan;
5220 break;
5221 case glslang::EOpGreaterThan:
5222 if (isFloat)
5223 binOp = spv::OpFOrdGreaterThan;
5224 else if (isUnsigned)
5225 binOp = spv::OpUGreaterThan;
5226 else
5227 binOp = spv::OpSGreaterThan;
5228 break;
5229 case glslang::EOpLessThanEqual:
5230 if (isFloat)
5231 binOp = spv::OpFOrdLessThanEqual;
5232 else if (isUnsigned)
5233 binOp = spv::OpULessThanEqual;
5234 else
5235 binOp = spv::OpSLessThanEqual;
5236 break;
5237 case glslang::EOpGreaterThanEqual:
5238 if (isFloat)
5239 binOp = spv::OpFOrdGreaterThanEqual;
5240 else if (isUnsigned)
5241 binOp = spv::OpUGreaterThanEqual;
5242 else
5243 binOp = spv::OpSGreaterThanEqual;
5244 break;
5245 case glslang::EOpEqual:
5246 case glslang::EOpVectorEqual:
5247 if (isFloat)
5248 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005249 else if (isBool)
5250 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005251 else
5252 binOp = spv::OpIEqual;
5253 break;
5254 case glslang::EOpNotEqual:
5255 case glslang::EOpVectorNotEqual:
5256 if (isFloat)
5257 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005258 else if (isBool)
5259 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005260 else
5261 binOp = spv::OpINotEqual;
5262 break;
5263 default:
5264 break;
5265 }
5266
qining25262b32016-05-06 17:25:16 -04005267 if (binOp != spv::OpNop) {
5268 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005269 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005270 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005271 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005272 }
John Kessenich140f3df2015-06-26 16:58:36 -06005273
5274 return 0;
5275}
5276
John Kessenich04bb8a02015-12-12 12:28:14 -07005277//
5278// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5279// These can be any of:
5280//
5281// matrix * scalar
5282// scalar * matrix
5283// matrix * matrix linear algebraic
5284// matrix * vector
5285// vector * matrix
5286// matrix * matrix componentwise
5287// matrix op matrix op in {+, -, /}
5288// matrix op scalar op in {+, -, /}
5289// scalar op matrix op in {+, -, /}
5290//
John Kessenichead86222018-03-28 18:01:20 -06005291spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5292 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005293{
5294 bool firstClass = true;
5295
5296 // First, handle first-class matrix operations (* and matrix/scalar)
5297 switch (op) {
5298 case spv::OpFDiv:
5299 if (builder.isMatrix(left) && builder.isScalar(right)) {
5300 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005301 spv::Id resultType = builder.getTypeId(right);
5302 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005303 op = spv::OpMatrixTimesScalar;
5304 } else
5305 firstClass = false;
5306 break;
5307 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005308 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005309 std::swap(left, right);
5310 assert(builder.isScalar(right));
5311 break;
5312 case spv::OpVectorTimesMatrix:
5313 assert(builder.isVector(left));
5314 assert(builder.isMatrix(right));
5315 break;
5316 case spv::OpMatrixTimesVector:
5317 assert(builder.isMatrix(left));
5318 assert(builder.isVector(right));
5319 break;
5320 case spv::OpMatrixTimesMatrix:
5321 assert(builder.isMatrix(left));
5322 assert(builder.isMatrix(right));
5323 break;
5324 default:
5325 firstClass = false;
5326 break;
5327 }
5328
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005329 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5330 firstClass = true;
5331
qining25262b32016-05-06 17:25:16 -04005332 if (firstClass) {
5333 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005334 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005335 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005336 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005337 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005338
LoopDawg592860c2016-06-09 08:57:35 -06005339 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005340 // The result type of all of them is the same type as the (a) matrix operand.
5341 // The algorithm is to:
5342 // - break the matrix(es) into vectors
5343 // - smear any scalar to a vector
5344 // - do vector operations
5345 // - make a matrix out the vector results
5346 switch (op) {
5347 case spv::OpFAdd:
5348 case spv::OpFSub:
5349 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005350 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005351 case spv::OpFMul:
5352 {
5353 // one time set up...
5354 bool leftMat = builder.isMatrix(left);
5355 bool rightMat = builder.isMatrix(right);
5356 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5357 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5358 spv::Id scalarType = builder.getScalarTypeId(typeId);
5359 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5360 std::vector<spv::Id> results;
5361 spv::Id smearVec = spv::NoResult;
5362 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005363 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005364 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005365 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005366
5367 // do each vector op
5368 for (unsigned int c = 0; c < numCols; ++c) {
5369 std::vector<unsigned int> indexes;
5370 indexes.push_back(c);
5371 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5372 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005373 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005374 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005375 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005376 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005377 }
5378
5379 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005380 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005381 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005382 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005383 }
5384 default:
5385 assert(0);
5386 return spv::NoResult;
5387 }
5388}
5389
John Kessenichead86222018-03-28 18:01:20 -06005390spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005391 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005392{
5393 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005394 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005395 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005396 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5397 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005398
5399 switch (op) {
5400 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005401 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005402 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005403 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005404 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005405 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005406 unaryOp = spv::OpSNegate;
5407 break;
5408
5409 case glslang::EOpLogicalNot:
5410 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005411 unaryOp = spv::OpLogicalNot;
5412 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005413 case glslang::EOpBitwiseNot:
5414 unaryOp = spv::OpNot;
5415 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005416
John Kessenich140f3df2015-06-26 16:58:36 -06005417 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005418 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005419 break;
5420 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005421 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005422 break;
5423 case glslang::EOpTranspose:
5424 unaryOp = spv::OpTranspose;
5425 break;
5426
5427 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005428 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005429 break;
5430 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005431 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005432 break;
5433 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005434 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005435 break;
5436 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005437 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005438 break;
5439 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005440 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005441 break;
5442 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005443 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005444 break;
5445 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005446 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005447 break;
5448 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005449 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005450 break;
5451
5452 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005453 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005454 break;
5455 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005456 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005457 break;
5458 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005459 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005460 break;
5461 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005462 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005463 break;
5464 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005465 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005466 break;
5467 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005468 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005469 break;
5470
5471 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005472 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005473 break;
5474 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005475 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005476 break;
5477
5478 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005479 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005480 break;
5481 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005482 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005483 break;
5484 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005485 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005486 break;
5487 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005488 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005489 break;
5490 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005491 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005492 break;
5493 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005494 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005495 break;
5496
5497 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005498 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005499 break;
5500 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005501 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005502 break;
5503 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005504 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005505 break;
5506 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005507 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005508 break;
5509 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005510 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005511 break;
5512 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005513 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005514 break;
5515
5516 case glslang::EOpIsNan:
5517 unaryOp = spv::OpIsNan;
5518 break;
5519 case glslang::EOpIsInf:
5520 unaryOp = spv::OpIsInf;
5521 break;
LoopDawg592860c2016-06-09 08:57:35 -06005522 case glslang::EOpIsFinite:
5523 unaryOp = spv::OpIsFinite;
5524 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005525
Rex Xucbc426e2015-12-15 16:03:10 +08005526 case glslang::EOpFloatBitsToInt:
5527 case glslang::EOpFloatBitsToUint:
5528 case glslang::EOpIntBitsToFloat:
5529 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005530 case glslang::EOpDoubleBitsToInt64:
5531 case glslang::EOpDoubleBitsToUint64:
5532 case glslang::EOpInt64BitsToDouble:
5533 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005534 case glslang::EOpFloat16BitsToInt16:
5535 case glslang::EOpFloat16BitsToUint16:
5536 case glslang::EOpInt16BitsToFloat16:
5537 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005538 unaryOp = spv::OpBitcast;
5539 break;
5540
John Kessenich140f3df2015-06-26 16:58:36 -06005541 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005542 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005543 break;
5544 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005545 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005546 break;
5547 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005548 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005549 break;
5550 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005551 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005552 break;
5553 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005554 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005555 break;
5556 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005557 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005558 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005559 case glslang::EOpPackSnorm4x8:
5560 libCall = spv::GLSLstd450PackSnorm4x8;
5561 break;
5562 case glslang::EOpUnpackSnorm4x8:
5563 libCall = spv::GLSLstd450UnpackSnorm4x8;
5564 break;
5565 case glslang::EOpPackUnorm4x8:
5566 libCall = spv::GLSLstd450PackUnorm4x8;
5567 break;
5568 case glslang::EOpUnpackUnorm4x8:
5569 libCall = spv::GLSLstd450UnpackUnorm4x8;
5570 break;
5571 case glslang::EOpPackDouble2x32:
5572 libCall = spv::GLSLstd450PackDouble2x32;
5573 break;
5574 case glslang::EOpUnpackDouble2x32:
5575 libCall = spv::GLSLstd450UnpackDouble2x32;
5576 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005577
Rex Xu8ff43de2016-04-22 16:51:45 +08005578 case glslang::EOpPackInt2x32:
5579 case glslang::EOpUnpackInt2x32:
5580 case glslang::EOpPackUint2x32:
5581 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005582 case glslang::EOpPack16:
5583 case glslang::EOpPack32:
5584 case glslang::EOpPack64:
5585 case glslang::EOpUnpack32:
5586 case glslang::EOpUnpack16:
5587 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005588 case glslang::EOpPackInt2x16:
5589 case glslang::EOpUnpackInt2x16:
5590 case glslang::EOpPackUint2x16:
5591 case glslang::EOpUnpackUint2x16:
5592 case glslang::EOpPackInt4x16:
5593 case glslang::EOpUnpackInt4x16:
5594 case glslang::EOpPackUint4x16:
5595 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005596 case glslang::EOpPackFloat2x16:
5597 case glslang::EOpUnpackFloat2x16:
5598 unaryOp = spv::OpBitcast;
5599 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005600
John Kessenich140f3df2015-06-26 16:58:36 -06005601 case glslang::EOpDPdx:
5602 unaryOp = spv::OpDPdx;
5603 break;
5604 case glslang::EOpDPdy:
5605 unaryOp = spv::OpDPdy;
5606 break;
5607 case glslang::EOpFwidth:
5608 unaryOp = spv::OpFwidth;
5609 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005610
John Kessenich140f3df2015-06-26 16:58:36 -06005611 case glslang::EOpAny:
5612 unaryOp = spv::OpAny;
5613 break;
5614 case glslang::EOpAll:
5615 unaryOp = spv::OpAll;
5616 break;
5617
5618 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005619 if (isFloat)
5620 libCall = spv::GLSLstd450FAbs;
5621 else
5622 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005623 break;
5624 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005625 if (isFloat)
5626 libCall = spv::GLSLstd450FSign;
5627 else
5628 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005629 break;
5630
John Kessenicha28f7a72019-08-06 07:00:58 -06005631#ifndef GLSLANG_WEB
5632 case glslang::EOpDPdxFine:
5633 unaryOp = spv::OpDPdxFine;
5634 break;
5635 case glslang::EOpDPdyFine:
5636 unaryOp = spv::OpDPdyFine;
5637 break;
5638 case glslang::EOpFwidthFine:
5639 unaryOp = spv::OpFwidthFine;
5640 break;
5641 case glslang::EOpDPdxCoarse:
5642 unaryOp = spv::OpDPdxCoarse;
5643 break;
5644 case glslang::EOpDPdyCoarse:
5645 unaryOp = spv::OpDPdyCoarse;
5646 break;
5647 case glslang::EOpFwidthCoarse:
5648 unaryOp = spv::OpFwidthCoarse;
5649 break;
5650 case glslang::EOpInterpolateAtCentroid:
5651 if (typeProxy == glslang::EbtFloat16)
5652 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5653 libCall = spv::GLSLstd450InterpolateAtCentroid;
5654 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005655 case glslang::EOpAtomicCounterIncrement:
5656 case glslang::EOpAtomicCounterDecrement:
5657 case glslang::EOpAtomicCounter:
5658 {
5659 // Handle all of the atomics in one place, in createAtomicOperation()
5660 std::vector<spv::Id> operands;
5661 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005662 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005663 }
5664
John Kessenichfc51d282015-08-19 13:34:18 -06005665 case glslang::EOpBitFieldReverse:
5666 unaryOp = spv::OpBitReverse;
5667 break;
5668 case glslang::EOpBitCount:
5669 unaryOp = spv::OpBitCount;
5670 break;
5671 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005672 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005673 break;
5674 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005675 if (isUnsigned)
5676 libCall = spv::GLSLstd450FindUMsb;
5677 else
5678 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005679 break;
5680
Rex Xu574ab042016-04-14 16:53:07 +08005681 case glslang::EOpBallot:
5682 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005683 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005684 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005685 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005686 case glslang::EOpMinInvocations:
5687 case glslang::EOpMaxInvocations:
5688 case glslang::EOpAddInvocations:
5689 case glslang::EOpMinInvocationsNonUniform:
5690 case glslang::EOpMaxInvocationsNonUniform:
5691 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005692 case glslang::EOpMinInvocationsInclusiveScan:
5693 case glslang::EOpMaxInvocationsInclusiveScan:
5694 case glslang::EOpAddInvocationsInclusiveScan:
5695 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5696 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5697 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5698 case glslang::EOpMinInvocationsExclusiveScan:
5699 case glslang::EOpMaxInvocationsExclusiveScan:
5700 case glslang::EOpAddInvocationsExclusiveScan:
5701 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5702 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5703 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08005704 {
5705 std::vector<spv::Id> operands;
5706 operands.push_back(operand);
5707 return createInvocationsOperation(op, typeId, operands, typeProxy);
5708 }
John Kessenich66011cb2018-03-06 16:12:04 -07005709 case glslang::EOpSubgroupAll:
5710 case glslang::EOpSubgroupAny:
5711 case glslang::EOpSubgroupAllEqual:
5712 case glslang::EOpSubgroupBroadcastFirst:
5713 case glslang::EOpSubgroupBallot:
5714 case glslang::EOpSubgroupInverseBallot:
5715 case glslang::EOpSubgroupBallotBitCount:
5716 case glslang::EOpSubgroupBallotInclusiveBitCount:
5717 case glslang::EOpSubgroupBallotExclusiveBitCount:
5718 case glslang::EOpSubgroupBallotFindLSB:
5719 case glslang::EOpSubgroupBallotFindMSB:
5720 case glslang::EOpSubgroupAdd:
5721 case glslang::EOpSubgroupMul:
5722 case glslang::EOpSubgroupMin:
5723 case glslang::EOpSubgroupMax:
5724 case glslang::EOpSubgroupAnd:
5725 case glslang::EOpSubgroupOr:
5726 case glslang::EOpSubgroupXor:
5727 case glslang::EOpSubgroupInclusiveAdd:
5728 case glslang::EOpSubgroupInclusiveMul:
5729 case glslang::EOpSubgroupInclusiveMin:
5730 case glslang::EOpSubgroupInclusiveMax:
5731 case glslang::EOpSubgroupInclusiveAnd:
5732 case glslang::EOpSubgroupInclusiveOr:
5733 case glslang::EOpSubgroupInclusiveXor:
5734 case glslang::EOpSubgroupExclusiveAdd:
5735 case glslang::EOpSubgroupExclusiveMul:
5736 case glslang::EOpSubgroupExclusiveMin:
5737 case glslang::EOpSubgroupExclusiveMax:
5738 case glslang::EOpSubgroupExclusiveAnd:
5739 case glslang::EOpSubgroupExclusiveOr:
5740 case glslang::EOpSubgroupExclusiveXor:
5741 case glslang::EOpSubgroupQuadSwapHorizontal:
5742 case glslang::EOpSubgroupQuadSwapVertical:
5743 case glslang::EOpSubgroupQuadSwapDiagonal: {
5744 std::vector<spv::Id> operands;
5745 operands.push_back(operand);
5746 return createSubgroupOperation(op, typeId, operands, typeProxy);
5747 }
Rex Xu9d93a232016-05-05 12:30:44 +08005748 case glslang::EOpMbcnt:
5749 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5750 libCall = spv::MbcntAMD;
5751 break;
5752
5753 case glslang::EOpCubeFaceIndex:
5754 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5755 libCall = spv::CubeFaceIndexAMD;
5756 break;
5757
5758 case glslang::EOpCubeFaceCoord:
5759 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5760 libCall = spv::CubeFaceCoordAMD;
5761 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005762 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005763 unaryOp = spv::OpGroupNonUniformPartitionNV;
5764 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005765 case glslang::EOpConstructReference:
5766 unaryOp = spv::OpBitcast;
5767 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005768#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05005769
5770 case glslang::EOpCopyObject:
5771 unaryOp = spv::OpCopyObject;
5772 break;
5773
John Kessenich140f3df2015-06-26 16:58:36 -06005774 default:
5775 return 0;
5776 }
5777
5778 spv::Id id;
5779 if (libCall >= 0) {
5780 std::vector<spv::Id> args;
5781 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005782 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005783 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005784 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005785 }
John Kessenich140f3df2015-06-26 16:58:36 -06005786
John Kessenichead86222018-03-28 18:01:20 -06005787 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005788 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005789 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005790}
5791
John Kessenich7a53f762016-01-20 11:19:27 -07005792// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005793spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5794 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005795{
5796 // Handle unary operations vector by vector.
5797 // The result type is the same type as the original type.
5798 // The algorithm is to:
5799 // - break the matrix into vectors
5800 // - apply the operation to each vector
5801 // - make a matrix out the vector results
5802
5803 // get the types sorted out
5804 int numCols = builder.getNumColumns(operand);
5805 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005806 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5807 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005808 std::vector<spv::Id> results;
5809
5810 // do each vector op
5811 for (int c = 0; c < numCols; ++c) {
5812 std::vector<unsigned int> indexes;
5813 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005814 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5815 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005816 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005817 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005818 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005819 }
5820
5821 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005822 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005823 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005824 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005825}
5826
John Kessenichad7645f2018-06-04 19:11:25 -06005827// For converting integers where both the bitwidth and the signedness could
5828// change, but only do the width change here. The caller is still responsible
5829// for the signedness conversion.
5830spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005831{
John Kessenichad7645f2018-06-04 19:11:25 -06005832 // Get the result type width, based on the type to convert to.
5833 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005834 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005835 case glslang::EOpConvInt16ToUint8:
5836 case glslang::EOpConvIntToUint8:
5837 case glslang::EOpConvInt64ToUint8:
5838 case glslang::EOpConvUint16ToInt8:
5839 case glslang::EOpConvUintToInt8:
5840 case glslang::EOpConvUint64ToInt8:
5841 width = 8;
5842 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005843 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005844 case glslang::EOpConvIntToUint16:
5845 case glslang::EOpConvInt64ToUint16:
5846 case glslang::EOpConvUint8ToInt16:
5847 case glslang::EOpConvUintToInt16:
5848 case glslang::EOpConvUint64ToInt16:
5849 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005850 break;
5851 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005852 case glslang::EOpConvInt16ToUint:
5853 case glslang::EOpConvInt64ToUint:
5854 case glslang::EOpConvUint8ToInt:
5855 case glslang::EOpConvUint16ToInt:
5856 case glslang::EOpConvUint64ToInt:
5857 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005858 break;
5859 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005860 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005861 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005862 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005863 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005864 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005865 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005866 break;
5867
5868 default:
5869 assert(false && "Default missing");
5870 break;
5871 }
5872
John Kessenichad7645f2018-06-04 19:11:25 -06005873 // Get the conversion operation and result type,
5874 // based on the target width, but the source type.
5875 spv::Id type = spv::NoType;
5876 spv::Op convOp = spv::OpNop;
5877 switch(op) {
5878 case glslang::EOpConvInt8ToUint16:
5879 case glslang::EOpConvInt8ToUint:
5880 case glslang::EOpConvInt8ToUint64:
5881 case glslang::EOpConvInt16ToUint8:
5882 case glslang::EOpConvInt16ToUint:
5883 case glslang::EOpConvInt16ToUint64:
5884 case glslang::EOpConvIntToUint8:
5885 case glslang::EOpConvIntToUint16:
5886 case glslang::EOpConvIntToUint64:
5887 case glslang::EOpConvInt64ToUint8:
5888 case glslang::EOpConvInt64ToUint16:
5889 case glslang::EOpConvInt64ToUint:
5890 convOp = spv::OpSConvert;
5891 type = builder.makeIntType(width);
5892 break;
5893 default:
5894 convOp = spv::OpUConvert;
5895 type = builder.makeUintType(width);
5896 break;
5897 }
5898
John Kessenich66011cb2018-03-06 16:12:04 -07005899 if (vectorSize > 0)
5900 type = builder.makeVectorType(type, vectorSize);
5901
John Kessenichad7645f2018-06-04 19:11:25 -06005902 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005903}
5904
John Kessenichead86222018-03-28 18:01:20 -06005905spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5906 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005907{
5908 spv::Op convOp = spv::OpNop;
5909 spv::Id zero = 0;
5910 spv::Id one = 0;
5911
5912 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5913
5914 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005915 case glslang::EOpConvIntToBool:
5916 case glslang::EOpConvUintToBool:
5917 zero = builder.makeUintConstant(0);
5918 zero = makeSmearedConstant(zero, vectorSize);
5919 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06005920 case glslang::EOpConvFloatToBool:
5921 zero = builder.makeFloatConstant(0.0F);
5922 zero = makeSmearedConstant(zero, vectorSize);
5923 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06005924 case glslang::EOpConvBoolToFloat:
5925 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005926 zero = builder.makeFloatConstant(0.0F);
5927 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005928 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005929
John Kessenich140f3df2015-06-26 16:58:36 -06005930 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005931 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005932 if (op == glslang::EOpConvBoolToInt64)
5933 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005934 else
5935 zero = builder.makeIntConstant(0);
5936
5937 if (op == glslang::EOpConvBoolToInt64)
5938 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005939 else
5940 one = builder.makeIntConstant(1);
5941
John Kessenich140f3df2015-06-26 16:58:36 -06005942 convOp = spv::OpSelect;
5943 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005944
John Kessenich140f3df2015-06-26 16:58:36 -06005945 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005946 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005947 if (op == glslang::EOpConvBoolToUint64)
5948 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005949 else
5950 zero = builder.makeUintConstant(0);
5951
5952 if (op == glslang::EOpConvBoolToUint64)
5953 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005954 else
5955 one = builder.makeUintConstant(1);
5956
John Kessenich140f3df2015-06-26 16:58:36 -06005957 convOp = spv::OpSelect;
5958 break;
5959
John Kessenich66011cb2018-03-06 16:12:04 -07005960 case glslang::EOpConvInt8ToFloat16:
5961 case glslang::EOpConvInt8ToFloat:
5962 case glslang::EOpConvInt8ToDouble:
5963 case glslang::EOpConvInt16ToFloat16:
5964 case glslang::EOpConvInt16ToFloat:
5965 case glslang::EOpConvInt16ToDouble:
5966 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005967 case glslang::EOpConvIntToFloat:
5968 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005969 case glslang::EOpConvInt64ToFloat:
5970 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005971 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005972 convOp = spv::OpConvertSToF;
5973 break;
5974
John Kessenich66011cb2018-03-06 16:12:04 -07005975 case glslang::EOpConvUint8ToFloat16:
5976 case glslang::EOpConvUint8ToFloat:
5977 case glslang::EOpConvUint8ToDouble:
5978 case glslang::EOpConvUint16ToFloat16:
5979 case glslang::EOpConvUint16ToFloat:
5980 case glslang::EOpConvUint16ToDouble:
5981 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005982 case glslang::EOpConvUintToFloat:
5983 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005984 case glslang::EOpConvUint64ToFloat:
5985 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005986 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005987 convOp = spv::OpConvertUToF;
5988 break;
5989
John Kessenich66011cb2018-03-06 16:12:04 -07005990 case glslang::EOpConvFloat16ToInt8:
5991 case glslang::EOpConvFloatToInt8:
5992 case glslang::EOpConvDoubleToInt8:
5993 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005994 case glslang::EOpConvFloatToInt16:
5995 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005996 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005997 case glslang::EOpConvFloatToInt:
5998 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005999 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006000 case glslang::EOpConvFloatToInt64:
6001 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006002 convOp = spv::OpConvertFToS;
6003 break;
6004
John Kessenich66011cb2018-03-06 16:12:04 -07006005 case glslang::EOpConvUint8ToInt8:
6006 case glslang::EOpConvInt8ToUint8:
6007 case glslang::EOpConvUint16ToInt16:
6008 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006009 case glslang::EOpConvUintToInt:
6010 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006011 case glslang::EOpConvUint64ToInt64:
6012 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006013 if (builder.isInSpecConstCodeGenMode()) {
6014 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006015#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006016 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6017 zero = builder.makeUint8Constant(0);
6018 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006019 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006020 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6021 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006022 } else
6023#endif
6024 {
Rex Xucabbb782017-03-24 13:41:14 +08006025 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006026 }
qining189b2032016-04-12 23:16:20 -04006027 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006028 // Use OpIAdd, instead of OpBitcast to do the conversion when
6029 // generating for OpSpecConstantOp instruction.
6030 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6031 }
6032 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006033 convOp = spv::OpBitcast;
6034 break;
6035
John Kessenich66011cb2018-03-06 16:12:04 -07006036 case glslang::EOpConvFloat16ToUint8:
6037 case glslang::EOpConvFloatToUint8:
6038 case glslang::EOpConvDoubleToUint8:
6039 case glslang::EOpConvFloat16ToUint16:
6040 case glslang::EOpConvFloatToUint16:
6041 case glslang::EOpConvDoubleToUint16:
6042 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006043 case glslang::EOpConvFloatToUint:
6044 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006045 case glslang::EOpConvFloatToUint64:
6046 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006047 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006048 convOp = spv::OpConvertFToU;
6049 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006050
John Kessenich39697cd2019-08-08 10:35:51 -06006051#ifndef GLSLANG_WEB
6052 case glslang::EOpConvInt8ToBool:
6053 case glslang::EOpConvUint8ToBool:
6054 zero = builder.makeUint8Constant(0);
6055 zero = makeSmearedConstant(zero, vectorSize);
6056 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6057 case glslang::EOpConvInt16ToBool:
6058 case glslang::EOpConvUint16ToBool:
6059 zero = builder.makeUint16Constant(0);
6060 zero = makeSmearedConstant(zero, vectorSize);
6061 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6062 case glslang::EOpConvInt64ToBool:
6063 case glslang::EOpConvUint64ToBool:
6064 zero = builder.makeUint64Constant(0);
6065 zero = makeSmearedConstant(zero, vectorSize);
6066 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6067 case glslang::EOpConvDoubleToBool:
6068 zero = builder.makeDoubleConstant(0.0);
6069 zero = makeSmearedConstant(zero, vectorSize);
6070 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6071 case glslang::EOpConvFloat16ToBool:
6072 zero = builder.makeFloat16Constant(0.0F);
6073 zero = makeSmearedConstant(zero, vectorSize);
6074 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6075 case glslang::EOpConvBoolToDouble:
6076 convOp = spv::OpSelect;
6077 zero = builder.makeDoubleConstant(0.0);
6078 one = builder.makeDoubleConstant(1.0);
6079 break;
6080 case glslang::EOpConvBoolToFloat16:
6081 convOp = spv::OpSelect;
6082 zero = builder.makeFloat16Constant(0.0F);
6083 one = builder.makeFloat16Constant(1.0F);
6084 break;
6085 case glslang::EOpConvBoolToInt8:
6086 zero = builder.makeInt8Constant(0);
6087 one = builder.makeInt8Constant(1);
6088 convOp = spv::OpSelect;
6089 break;
6090 case glslang::EOpConvBoolToUint8:
6091 zero = builder.makeUint8Constant(0);
6092 one = builder.makeUint8Constant(1);
6093 convOp = spv::OpSelect;
6094 break;
6095 case glslang::EOpConvBoolToInt16:
6096 zero = builder.makeInt16Constant(0);
6097 one = builder.makeInt16Constant(1);
6098 convOp = spv::OpSelect;
6099 break;
6100 case glslang::EOpConvBoolToUint16:
6101 zero = builder.makeUint16Constant(0);
6102 one = builder.makeUint16Constant(1);
6103 convOp = spv::OpSelect;
6104 break;
6105 case glslang::EOpConvDoubleToFloat:
6106 case glslang::EOpConvFloatToDouble:
6107 case glslang::EOpConvDoubleToFloat16:
6108 case glslang::EOpConvFloat16ToDouble:
6109 case glslang::EOpConvFloatToFloat16:
6110 case glslang::EOpConvFloat16ToFloat:
6111 convOp = spv::OpFConvert;
6112 if (builder.isMatrixType(destType))
6113 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6114 break;
6115
John Kessenich66011cb2018-03-06 16:12:04 -07006116 case glslang::EOpConvInt8ToInt16:
6117 case glslang::EOpConvInt8ToInt:
6118 case glslang::EOpConvInt8ToInt64:
6119 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006120 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006121 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006122 case glslang::EOpConvIntToInt8:
6123 case glslang::EOpConvIntToInt16:
6124 case glslang::EOpConvIntToInt64:
6125 case glslang::EOpConvInt64ToInt8:
6126 case glslang::EOpConvInt64ToInt16:
6127 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006128 convOp = spv::OpSConvert;
6129 break;
6130
John Kessenich66011cb2018-03-06 16:12:04 -07006131 case glslang::EOpConvUint8ToUint16:
6132 case glslang::EOpConvUint8ToUint:
6133 case glslang::EOpConvUint8ToUint64:
6134 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006135 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006136 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006137 case glslang::EOpConvUintToUint8:
6138 case glslang::EOpConvUintToUint16:
6139 case glslang::EOpConvUintToUint64:
6140 case glslang::EOpConvUint64ToUint8:
6141 case glslang::EOpConvUint64ToUint16:
6142 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006143 convOp = spv::OpUConvert;
6144 break;
6145
John Kessenich66011cb2018-03-06 16:12:04 -07006146 case glslang::EOpConvInt8ToUint16:
6147 case glslang::EOpConvInt8ToUint:
6148 case glslang::EOpConvInt8ToUint64:
6149 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006150 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006151 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006152 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006153 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006154 case glslang::EOpConvIntToUint64:
6155 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006156 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006157 case glslang::EOpConvInt64ToUint:
6158 case glslang::EOpConvUint8ToInt16:
6159 case glslang::EOpConvUint8ToInt:
6160 case glslang::EOpConvUint8ToInt64:
6161 case glslang::EOpConvUint16ToInt8:
6162 case glslang::EOpConvUint16ToInt:
6163 case glslang::EOpConvUint16ToInt64:
6164 case glslang::EOpConvUintToInt8:
6165 case glslang::EOpConvUintToInt16:
6166 case glslang::EOpConvUintToInt64:
6167 case glslang::EOpConvUint64ToInt8:
6168 case glslang::EOpConvUint64ToInt16:
6169 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006170 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006171 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006172
6173 if (builder.isInSpecConstCodeGenMode()) {
6174 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006175 switch(op) {
6176 case glslang::EOpConvInt16ToUint8:
6177 case glslang::EOpConvIntToUint8:
6178 case glslang::EOpConvInt64ToUint8:
6179 case glslang::EOpConvUint16ToInt8:
6180 case glslang::EOpConvUintToInt8:
6181 case glslang::EOpConvUint64ToInt8:
6182 zero = builder.makeUint8Constant(0);
6183 break;
6184 case glslang::EOpConvInt8ToUint16:
6185 case glslang::EOpConvIntToUint16:
6186 case glslang::EOpConvInt64ToUint16:
6187 case glslang::EOpConvUint8ToInt16:
6188 case glslang::EOpConvUintToInt16:
6189 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006190 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006191 break;
6192 case glslang::EOpConvInt8ToUint:
6193 case glslang::EOpConvInt16ToUint:
6194 case glslang::EOpConvInt64ToUint:
6195 case glslang::EOpConvUint8ToInt:
6196 case glslang::EOpConvUint16ToInt:
6197 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006198 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006199 break;
6200 case glslang::EOpConvInt8ToUint64:
6201 case glslang::EOpConvInt16ToUint64:
6202 case glslang::EOpConvIntToUint64:
6203 case glslang::EOpConvUint8ToInt64:
6204 case glslang::EOpConvUint16ToInt64:
6205 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006206 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006207 break;
6208 default:
6209 assert(false && "Default missing");
6210 break;
6211 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006212 zero = makeSmearedConstant(zero, vectorSize);
6213 // Use OpIAdd, instead of OpBitcast to do the conversion when
6214 // generating for OpSpecConstantOp instruction.
6215 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6216 }
6217 // For normal run-time conversion instruction, use OpBitcast.
6218 convOp = spv::OpBitcast;
6219 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006220 case glslang::EOpConvUint64ToPtr:
6221 convOp = spv::OpConvertUToPtr;
6222 break;
6223 case glslang::EOpConvPtrToUint64:
6224 convOp = spv::OpConvertPtrToU;
6225 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006226#endif
6227
John Kessenich140f3df2015-06-26 16:58:36 -06006228 default:
6229 break;
6230 }
6231
6232 spv::Id result = 0;
6233 if (convOp == spv::OpNop)
6234 return result;
6235
6236 if (convOp == spv::OpSelect) {
6237 zero = makeSmearedConstant(zero, vectorSize);
6238 one = makeSmearedConstant(one, vectorSize);
6239 result = builder.createTriOp(convOp, destType, operand, one, zero);
6240 } else
6241 result = builder.createUnaryOp(convOp, destType, operand);
6242
John Kessenichead86222018-03-28 18:01:20 -06006243 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006244 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006245 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006246}
6247
6248spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6249{
6250 if (vectorSize == 0)
6251 return constant;
6252
6253 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6254 std::vector<spv::Id> components;
6255 for (int c = 0; c < vectorSize; ++c)
6256 components.push_back(constant);
6257 return builder.makeCompositeConstant(vectorTypeId, components);
6258}
6259
John Kessenich426394d2015-07-23 10:22:48 -06006260// For glslang ops that map to SPV atomic opCodes
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006261spv::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 -06006262{
6263 spv::Op opCode = spv::OpNop;
6264
6265 switch (op) {
6266 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006267 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006268 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006269 opCode = spv::OpAtomicIAdd;
6270 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006271 case glslang::EOpAtomicCounterSubtract:
6272 opCode = spv::OpAtomicISub;
6273 break;
John Kessenich426394d2015-07-23 10:22:48 -06006274 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006275 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006276 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006277 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006278 break;
6279 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006280 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006281 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006282 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006283 break;
6284 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006285 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006286 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006287 opCode = spv::OpAtomicAnd;
6288 break;
6289 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006290 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006291 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006292 opCode = spv::OpAtomicOr;
6293 break;
6294 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006295 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006296 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006297 opCode = spv::OpAtomicXor;
6298 break;
6299 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006300 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006301 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006302 opCode = spv::OpAtomicExchange;
6303 break;
6304 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006305 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006306 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006307 opCode = spv::OpAtomicCompareExchange;
6308 break;
6309 case glslang::EOpAtomicCounterIncrement:
6310 opCode = spv::OpAtomicIIncrement;
6311 break;
6312 case glslang::EOpAtomicCounterDecrement:
6313 opCode = spv::OpAtomicIDecrement;
6314 break;
6315 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006316 case glslang::EOpImageAtomicLoad:
6317 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006318 opCode = spv::OpAtomicLoad;
6319 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006320 case glslang::EOpAtomicStore:
6321 case glslang::EOpImageAtomicStore:
6322 opCode = spv::OpAtomicStore;
6323 break;
John Kessenich426394d2015-07-23 10:22:48 -06006324 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006325 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006326 break;
6327 }
6328
Rex Xue8fe8b02017-09-26 15:42:56 +08006329 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6330 builder.addCapability(spv::CapabilityInt64Atomics);
6331
John Kessenich426394d2015-07-23 10:22:48 -06006332 // Sort out the operands
6333 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006334 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006335 // - compare-exchange swaps the value and comparator
6336 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006337 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006338 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6339 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6340 spv::Id scopeId;
6341 if (glslangIntermediate->usingVulkanMemoryModel()) {
6342 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6343 } else {
6344 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6345 }
6346 // semantics default to relaxed
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006347 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.volatil ? spv::MemorySemanticsVolatileMask : spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006348 spv::Id semanticsId2 = semanticsId;
6349
6350 pointerId = operands[0];
6351 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6352 // no additional operands
6353 } else if (opCode == spv::OpAtomicCompareExchange) {
6354 compareId = operands[1];
6355 valueId = operands[2];
6356 if (operands.size() > 3) {
6357 scopeId = operands[3];
6358 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6359 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6360 }
6361 } else if (opCode == spv::OpAtomicLoad) {
6362 if (operands.size() > 1) {
6363 scopeId = operands[1];
6364 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6365 }
6366 } else {
6367 // atomic store or RMW
6368 valueId = operands[1];
6369 if (operands.size() > 2) {
6370 scopeId = operands[2];
6371 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6372 }
Rex Xu04db3f52015-09-16 11:44:02 +08006373 }
John Kessenich426394d2015-07-23 10:22:48 -06006374
Jeff Bolz36831c92018-09-05 10:11:41 -05006375 // Check for capabilities
6376 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006377 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6378 spv::MemorySemanticsMakeVisibleKHRMask |
6379 spv::MemorySemanticsOutputMemoryKHRMask |
6380 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006381 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6382 }
John Kessenich426394d2015-07-23 10:22:48 -06006383
Jeff Bolz36831c92018-09-05 10:11:41 -05006384 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6385 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6386 }
John Kessenich48d6e792017-10-06 21:21:48 -06006387
Jeff Bolz36831c92018-09-05 10:11:41 -05006388 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6389 spvAtomicOperands.push_back(pointerId);
6390 spvAtomicOperands.push_back(scopeId);
6391 spvAtomicOperands.push_back(semanticsId);
6392 if (opCode == spv::OpAtomicCompareExchange) {
6393 spvAtomicOperands.push_back(semanticsId2);
6394 spvAtomicOperands.push_back(valueId);
6395 spvAtomicOperands.push_back(compareId);
6396 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6397 spvAtomicOperands.push_back(valueId);
6398 }
John Kessenich48d6e792017-10-06 21:21:48 -06006399
Jeff Bolz36831c92018-09-05 10:11:41 -05006400 if (opCode == spv::OpAtomicStore) {
6401 builder.createNoResultOp(opCode, spvAtomicOperands);
6402 return 0;
6403 } else {
6404 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6405
6406 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6407 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6408 if (op == glslang::EOpAtomicCounterDecrement)
6409 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6410
6411 return resultId;
6412 }
John Kessenich426394d2015-07-23 10:22:48 -06006413}
6414
John Kessenich91cef522016-05-05 16:45:40 -06006415// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006416spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006417{
John Kessenich66011cb2018-03-06 16:12:04 -07006418 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6419 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006420
Rex Xu51596642016-09-21 18:56:12 +08006421 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006422 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006423 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6424
chaocf200da82016-12-20 12:44:35 -08006425 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6426 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006427 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6428 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006429 } else if (op == glslang::EOpAnyInvocation ||
6430 op == glslang::EOpAllInvocations ||
6431 op == glslang::EOpAllInvocationsEqual) {
6432 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6433 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006434 } else {
6435 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006436 if (op == glslang::EOpMinInvocationsNonUniform ||
6437 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006438 op == glslang::EOpAddInvocationsNonUniform ||
6439 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6440 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6441 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6442 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6443 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6444 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006445 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006446
Rex Xu430ef402016-10-14 17:22:23 +08006447 switch (op) {
6448 case glslang::EOpMinInvocations:
6449 case glslang::EOpMaxInvocations:
6450 case glslang::EOpAddInvocations:
6451 case glslang::EOpMinInvocationsNonUniform:
6452 case glslang::EOpMaxInvocationsNonUniform:
6453 case glslang::EOpAddInvocationsNonUniform:
6454 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006455 break;
6456 case glslang::EOpMinInvocationsInclusiveScan:
6457 case glslang::EOpMaxInvocationsInclusiveScan:
6458 case glslang::EOpAddInvocationsInclusiveScan:
6459 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6460 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6461 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6462 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006463 break;
6464 case glslang::EOpMinInvocationsExclusiveScan:
6465 case glslang::EOpMaxInvocationsExclusiveScan:
6466 case glslang::EOpAddInvocationsExclusiveScan:
6467 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6468 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6469 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6470 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006471 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006472 default:
6473 break;
Rex Xu430ef402016-10-14 17:22:23 +08006474 }
John Kessenich149afc32018-08-14 13:31:43 -06006475 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6476 spvGroupOperands.push_back(scope);
6477 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006478 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006479 spvGroupOperands.push_back(groupOp);
6480 }
Rex Xu51596642016-09-21 18:56:12 +08006481 }
6482
John Kessenich149afc32018-08-14 13:31:43 -06006483 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6484 spv::IdImmediate op = { true, *opIt };
6485 spvGroupOperands.push_back(op);
6486 }
John Kessenich91cef522016-05-05 16:45:40 -06006487
6488 switch (op) {
6489 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006490 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006491 break;
John Kessenich91cef522016-05-05 16:45:40 -06006492 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006493 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006494 break;
John Kessenich91cef522016-05-05 16:45:40 -06006495 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006496 opCode = spv::OpSubgroupAllEqualKHR;
6497 break;
Rex Xu51596642016-09-21 18:56:12 +08006498 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006499 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006500 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006501 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006502 break;
6503 case glslang::EOpReadFirstInvocation:
6504 opCode = spv::OpSubgroupFirstInvocationKHR;
6505 break;
6506 case glslang::EOpBallot:
6507 {
6508 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6509 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6510 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6511 //
6512 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6513 //
6514 spv::Id uintType = builder.makeUintType(32);
6515 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6516 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6517
6518 std::vector<spv::Id> components;
6519 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6520 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6521
6522 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6523 return builder.createUnaryOp(spv::OpBitcast, typeId,
6524 builder.createCompositeConstruct(uvec2Type, components));
6525 }
6526
Rex Xu9d93a232016-05-05 12:30:44 +08006527 case glslang::EOpMinInvocations:
6528 case glslang::EOpMaxInvocations:
6529 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006530 case glslang::EOpMinInvocationsInclusiveScan:
6531 case glslang::EOpMaxInvocationsInclusiveScan:
6532 case glslang::EOpAddInvocationsInclusiveScan:
6533 case glslang::EOpMinInvocationsExclusiveScan:
6534 case glslang::EOpMaxInvocationsExclusiveScan:
6535 case glslang::EOpAddInvocationsExclusiveScan:
6536 if (op == glslang::EOpMinInvocations ||
6537 op == glslang::EOpMinInvocationsInclusiveScan ||
6538 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006539 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006540 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006541 else {
6542 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006543 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006544 else
Rex Xu51596642016-09-21 18:56:12 +08006545 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006546 }
Rex Xu430ef402016-10-14 17:22:23 +08006547 } else if (op == glslang::EOpMaxInvocations ||
6548 op == glslang::EOpMaxInvocationsInclusiveScan ||
6549 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006550 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006551 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006552 else {
6553 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006554 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006555 else
Rex Xu51596642016-09-21 18:56:12 +08006556 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006557 }
6558 } else {
6559 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006560 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006561 else
Rex Xu51596642016-09-21 18:56:12 +08006562 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006563 }
6564
Rex Xu2bbbe062016-08-23 15:41:05 +08006565 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006566 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006567
6568 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006569 case glslang::EOpMinInvocationsNonUniform:
6570 case glslang::EOpMaxInvocationsNonUniform:
6571 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006572 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6573 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6574 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6575 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6576 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6577 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6578 if (op == glslang::EOpMinInvocationsNonUniform ||
6579 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6580 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006581 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006582 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006583 else {
6584 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006585 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006586 else
Rex Xu51596642016-09-21 18:56:12 +08006587 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006588 }
6589 }
Rex Xu430ef402016-10-14 17:22:23 +08006590 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6591 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6592 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006593 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006594 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006595 else {
6596 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006597 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006598 else
Rex Xu51596642016-09-21 18:56:12 +08006599 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006600 }
6601 }
6602 else {
6603 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006604 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006605 else
Rex Xu51596642016-09-21 18:56:12 +08006606 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006607 }
6608
Rex Xu2bbbe062016-08-23 15:41:05 +08006609 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006610 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006611
6612 break;
John Kessenich91cef522016-05-05 16:45:40 -06006613 default:
6614 logger->missingFunctionality("invocation operation");
6615 return spv::NoResult;
6616 }
Rex Xu51596642016-09-21 18:56:12 +08006617
6618 assert(opCode != spv::OpNop);
6619 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006620}
6621
Rex Xu2bbbe062016-08-23 15:41:05 +08006622// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006623spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6624 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006625{
6626 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6627 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006628 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006629 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006630 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6631 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6632 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
6633
6634 // Handle group invocation operations scalar by scalar.
6635 // The result type is the same type as the original type.
6636 // The algorithm is to:
6637 // - break the vector into scalars
6638 // - apply the operation to each scalar
6639 // - make a vector out the scalar results
6640
6641 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006642 int numComponents = builder.getNumComponents(operands[0]);
6643 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006644 std::vector<spv::Id> results;
6645
6646 // do each scalar op
6647 for (int comp = 0; comp < numComponents; ++comp) {
6648 std::vector<unsigned int> indexes;
6649 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006650 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6651 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006652 if (op == spv::OpSubgroupReadInvocationKHR) {
6653 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006654 spv::IdImmediate operand = { true, operands[1] };
6655 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006656 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006657 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6658 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006659 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006660 spv::IdImmediate operand = { true, operands[1] };
6661 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006662 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006663 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6664 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006665 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006666 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006667 spvGroupOperands.push_back(scalar);
6668 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006669
Rex Xub7072052016-09-26 15:53:40 +08006670 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006671 }
6672
6673 // put the pieces together
6674 return builder.createCompositeConstruct(typeId, results);
6675}
Rex Xu2bbbe062016-08-23 15:41:05 +08006676
John Kessenich66011cb2018-03-06 16:12:04 -07006677// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006678spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6679 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006680{
6681 // Add the required capabilities.
6682 switch (op) {
6683 case glslang::EOpSubgroupElect:
6684 builder.addCapability(spv::CapabilityGroupNonUniform);
6685 break;
6686 case glslang::EOpSubgroupAll:
6687 case glslang::EOpSubgroupAny:
6688 case glslang::EOpSubgroupAllEqual:
6689 builder.addCapability(spv::CapabilityGroupNonUniform);
6690 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6691 break;
6692 case glslang::EOpSubgroupBroadcast:
6693 case glslang::EOpSubgroupBroadcastFirst:
6694 case glslang::EOpSubgroupBallot:
6695 case glslang::EOpSubgroupInverseBallot:
6696 case glslang::EOpSubgroupBallotBitExtract:
6697 case glslang::EOpSubgroupBallotBitCount:
6698 case glslang::EOpSubgroupBallotInclusiveBitCount:
6699 case glslang::EOpSubgroupBallotExclusiveBitCount:
6700 case glslang::EOpSubgroupBallotFindLSB:
6701 case glslang::EOpSubgroupBallotFindMSB:
6702 builder.addCapability(spv::CapabilityGroupNonUniform);
6703 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6704 break;
6705 case glslang::EOpSubgroupShuffle:
6706 case glslang::EOpSubgroupShuffleXor:
6707 builder.addCapability(spv::CapabilityGroupNonUniform);
6708 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6709 break;
6710 case glslang::EOpSubgroupShuffleUp:
6711 case glslang::EOpSubgroupShuffleDown:
6712 builder.addCapability(spv::CapabilityGroupNonUniform);
6713 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6714 break;
6715 case glslang::EOpSubgroupAdd:
6716 case glslang::EOpSubgroupMul:
6717 case glslang::EOpSubgroupMin:
6718 case glslang::EOpSubgroupMax:
6719 case glslang::EOpSubgroupAnd:
6720 case glslang::EOpSubgroupOr:
6721 case glslang::EOpSubgroupXor:
6722 case glslang::EOpSubgroupInclusiveAdd:
6723 case glslang::EOpSubgroupInclusiveMul:
6724 case glslang::EOpSubgroupInclusiveMin:
6725 case glslang::EOpSubgroupInclusiveMax:
6726 case glslang::EOpSubgroupInclusiveAnd:
6727 case glslang::EOpSubgroupInclusiveOr:
6728 case glslang::EOpSubgroupInclusiveXor:
6729 case glslang::EOpSubgroupExclusiveAdd:
6730 case glslang::EOpSubgroupExclusiveMul:
6731 case glslang::EOpSubgroupExclusiveMin:
6732 case glslang::EOpSubgroupExclusiveMax:
6733 case glslang::EOpSubgroupExclusiveAnd:
6734 case glslang::EOpSubgroupExclusiveOr:
6735 case glslang::EOpSubgroupExclusiveXor:
6736 builder.addCapability(spv::CapabilityGroupNonUniform);
6737 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6738 break;
6739 case glslang::EOpSubgroupClusteredAdd:
6740 case glslang::EOpSubgroupClusteredMul:
6741 case glslang::EOpSubgroupClusteredMin:
6742 case glslang::EOpSubgroupClusteredMax:
6743 case glslang::EOpSubgroupClusteredAnd:
6744 case glslang::EOpSubgroupClusteredOr:
6745 case glslang::EOpSubgroupClusteredXor:
6746 builder.addCapability(spv::CapabilityGroupNonUniform);
6747 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6748 break;
6749 case glslang::EOpSubgroupQuadBroadcast:
6750 case glslang::EOpSubgroupQuadSwapHorizontal:
6751 case glslang::EOpSubgroupQuadSwapVertical:
6752 case glslang::EOpSubgroupQuadSwapDiagonal:
6753 builder.addCapability(spv::CapabilityGroupNonUniform);
6754 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6755 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006756 case glslang::EOpSubgroupPartitionedAdd:
6757 case glslang::EOpSubgroupPartitionedMul:
6758 case glslang::EOpSubgroupPartitionedMin:
6759 case glslang::EOpSubgroupPartitionedMax:
6760 case glslang::EOpSubgroupPartitionedAnd:
6761 case glslang::EOpSubgroupPartitionedOr:
6762 case glslang::EOpSubgroupPartitionedXor:
6763 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6764 case glslang::EOpSubgroupPartitionedInclusiveMul:
6765 case glslang::EOpSubgroupPartitionedInclusiveMin:
6766 case glslang::EOpSubgroupPartitionedInclusiveMax:
6767 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6768 case glslang::EOpSubgroupPartitionedInclusiveOr:
6769 case glslang::EOpSubgroupPartitionedInclusiveXor:
6770 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6771 case glslang::EOpSubgroupPartitionedExclusiveMul:
6772 case glslang::EOpSubgroupPartitionedExclusiveMin:
6773 case glslang::EOpSubgroupPartitionedExclusiveMax:
6774 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6775 case glslang::EOpSubgroupPartitionedExclusiveOr:
6776 case glslang::EOpSubgroupPartitionedExclusiveXor:
6777 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6778 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6779 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006780 default: assert(0 && "Unhandled subgroup operation!");
6781 }
6782
6783 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6784 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6785 const bool isBool = typeProxy == glslang::EbtBool;
6786
6787 spv::Op opCode = spv::OpNop;
6788
6789 // Figure out which opcode to use.
6790 switch (op) {
6791 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6792 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6793 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6794 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6795 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6796 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6797 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6798 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6799 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6800 case glslang::EOpSubgroupBallotBitCount:
6801 case glslang::EOpSubgroupBallotInclusiveBitCount:
6802 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6803 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6804 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6805 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6806 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6807 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6808 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6809 case glslang::EOpSubgroupAdd:
6810 case glslang::EOpSubgroupInclusiveAdd:
6811 case glslang::EOpSubgroupExclusiveAdd:
6812 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006813 case glslang::EOpSubgroupPartitionedAdd:
6814 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6815 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07006816 if (isFloat) {
6817 opCode = spv::OpGroupNonUniformFAdd;
6818 } else {
6819 opCode = spv::OpGroupNonUniformIAdd;
6820 }
6821 break;
6822 case glslang::EOpSubgroupMul:
6823 case glslang::EOpSubgroupInclusiveMul:
6824 case glslang::EOpSubgroupExclusiveMul:
6825 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006826 case glslang::EOpSubgroupPartitionedMul:
6827 case glslang::EOpSubgroupPartitionedInclusiveMul:
6828 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07006829 if (isFloat) {
6830 opCode = spv::OpGroupNonUniformFMul;
6831 } else {
6832 opCode = spv::OpGroupNonUniformIMul;
6833 }
6834 break;
6835 case glslang::EOpSubgroupMin:
6836 case glslang::EOpSubgroupInclusiveMin:
6837 case glslang::EOpSubgroupExclusiveMin:
6838 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006839 case glslang::EOpSubgroupPartitionedMin:
6840 case glslang::EOpSubgroupPartitionedInclusiveMin:
6841 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07006842 if (isFloat) {
6843 opCode = spv::OpGroupNonUniformFMin;
6844 } else if (isUnsigned) {
6845 opCode = spv::OpGroupNonUniformUMin;
6846 } else {
6847 opCode = spv::OpGroupNonUniformSMin;
6848 }
6849 break;
6850 case glslang::EOpSubgroupMax:
6851 case glslang::EOpSubgroupInclusiveMax:
6852 case glslang::EOpSubgroupExclusiveMax:
6853 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006854 case glslang::EOpSubgroupPartitionedMax:
6855 case glslang::EOpSubgroupPartitionedInclusiveMax:
6856 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07006857 if (isFloat) {
6858 opCode = spv::OpGroupNonUniformFMax;
6859 } else if (isUnsigned) {
6860 opCode = spv::OpGroupNonUniformUMax;
6861 } else {
6862 opCode = spv::OpGroupNonUniformSMax;
6863 }
6864 break;
6865 case glslang::EOpSubgroupAnd:
6866 case glslang::EOpSubgroupInclusiveAnd:
6867 case glslang::EOpSubgroupExclusiveAnd:
6868 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006869 case glslang::EOpSubgroupPartitionedAnd:
6870 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6871 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07006872 if (isBool) {
6873 opCode = spv::OpGroupNonUniformLogicalAnd;
6874 } else {
6875 opCode = spv::OpGroupNonUniformBitwiseAnd;
6876 }
6877 break;
6878 case glslang::EOpSubgroupOr:
6879 case glslang::EOpSubgroupInclusiveOr:
6880 case glslang::EOpSubgroupExclusiveOr:
6881 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006882 case glslang::EOpSubgroupPartitionedOr:
6883 case glslang::EOpSubgroupPartitionedInclusiveOr:
6884 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07006885 if (isBool) {
6886 opCode = spv::OpGroupNonUniformLogicalOr;
6887 } else {
6888 opCode = spv::OpGroupNonUniformBitwiseOr;
6889 }
6890 break;
6891 case glslang::EOpSubgroupXor:
6892 case glslang::EOpSubgroupInclusiveXor:
6893 case glslang::EOpSubgroupExclusiveXor:
6894 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006895 case glslang::EOpSubgroupPartitionedXor:
6896 case glslang::EOpSubgroupPartitionedInclusiveXor:
6897 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07006898 if (isBool) {
6899 opCode = spv::OpGroupNonUniformLogicalXor;
6900 } else {
6901 opCode = spv::OpGroupNonUniformBitwiseXor;
6902 }
6903 break;
6904 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6905 case glslang::EOpSubgroupQuadSwapHorizontal:
6906 case glslang::EOpSubgroupQuadSwapVertical:
6907 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6908 default: assert(0 && "Unhandled subgroup operation!");
6909 }
6910
John Kessenich149afc32018-08-14 13:31:43 -06006911 // get the right Group Operation
6912 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006913 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006914 default:
6915 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006916 case glslang::EOpSubgroupBallotBitCount:
6917 case glslang::EOpSubgroupAdd:
6918 case glslang::EOpSubgroupMul:
6919 case glslang::EOpSubgroupMin:
6920 case glslang::EOpSubgroupMax:
6921 case glslang::EOpSubgroupAnd:
6922 case glslang::EOpSubgroupOr:
6923 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006924 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006925 break;
6926 case glslang::EOpSubgroupBallotInclusiveBitCount:
6927 case glslang::EOpSubgroupInclusiveAdd:
6928 case glslang::EOpSubgroupInclusiveMul:
6929 case glslang::EOpSubgroupInclusiveMin:
6930 case glslang::EOpSubgroupInclusiveMax:
6931 case glslang::EOpSubgroupInclusiveAnd:
6932 case glslang::EOpSubgroupInclusiveOr:
6933 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006934 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006935 break;
6936 case glslang::EOpSubgroupBallotExclusiveBitCount:
6937 case glslang::EOpSubgroupExclusiveAdd:
6938 case glslang::EOpSubgroupExclusiveMul:
6939 case glslang::EOpSubgroupExclusiveMin:
6940 case glslang::EOpSubgroupExclusiveMax:
6941 case glslang::EOpSubgroupExclusiveAnd:
6942 case glslang::EOpSubgroupExclusiveOr:
6943 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006944 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006945 break;
6946 case glslang::EOpSubgroupClusteredAdd:
6947 case glslang::EOpSubgroupClusteredMul:
6948 case glslang::EOpSubgroupClusteredMin:
6949 case glslang::EOpSubgroupClusteredMax:
6950 case glslang::EOpSubgroupClusteredAnd:
6951 case glslang::EOpSubgroupClusteredOr:
6952 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006953 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006954 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006955 case glslang::EOpSubgroupPartitionedAdd:
6956 case glslang::EOpSubgroupPartitionedMul:
6957 case glslang::EOpSubgroupPartitionedMin:
6958 case glslang::EOpSubgroupPartitionedMax:
6959 case glslang::EOpSubgroupPartitionedAnd:
6960 case glslang::EOpSubgroupPartitionedOr:
6961 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006962 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006963 break;
6964 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6965 case glslang::EOpSubgroupPartitionedInclusiveMul:
6966 case glslang::EOpSubgroupPartitionedInclusiveMin:
6967 case glslang::EOpSubgroupPartitionedInclusiveMax:
6968 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6969 case glslang::EOpSubgroupPartitionedInclusiveOr:
6970 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006971 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006972 break;
6973 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6974 case glslang::EOpSubgroupPartitionedExclusiveMul:
6975 case glslang::EOpSubgroupPartitionedExclusiveMin:
6976 case glslang::EOpSubgroupPartitionedExclusiveMax:
6977 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6978 case glslang::EOpSubgroupPartitionedExclusiveOr:
6979 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006980 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006981 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006982 }
6983
John Kessenich149afc32018-08-14 13:31:43 -06006984 // build the instruction
6985 std::vector<spv::IdImmediate> spvGroupOperands;
6986
6987 // Every operation begins with the Execution Scope operand.
6988 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6989 spvGroupOperands.push_back(executionScope);
6990
6991 // Next, for all operations that use a Group Operation, push that as an operand.
6992 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006993 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006994 spvGroupOperands.push_back(groupOperand);
6995 }
6996
John Kessenich66011cb2018-03-06 16:12:04 -07006997 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006998 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6999 spv::IdImmediate operand = { true, *opIt };
7000 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007001 }
7002
7003 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007004 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007005 switch (op) {
7006 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007007 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7008 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7009 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7010 }
7011 if (directionId != spv::NoResult) {
7012 spv::IdImmediate direction = { true, directionId };
7013 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007014 }
7015
7016 return builder.createOp(opCode, typeId, spvGroupOperands);
7017}
7018
John Kessenich5e4b1242015-08-06 22:53:06 -06007019spv::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 -06007020{
John Kessenich66011cb2018-03-06 16:12:04 -07007021 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7022 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007023
John Kessenich140f3df2015-06-26 16:58:36 -06007024 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007025 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007026 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007027 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007028 spv::Id typeId0 = 0;
7029 if (consumedOperands > 0)
7030 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007031 spv::Id typeId1 = 0;
7032 if (consumedOperands > 1)
7033 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007034 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007035
7036 switch (op) {
7037 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007038 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007039 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007040 else if (isUnsigned)
7041 libCall = spv::GLSLstd450UMin;
7042 else
7043 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007044 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007045 break;
7046 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007047 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007048 break;
7049 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007050 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007051 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007052 else if (isUnsigned)
7053 libCall = spv::GLSLstd450UMax;
7054 else
7055 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007056 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007057 break;
7058 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007059 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007060 break;
7061 case glslang::EOpDot:
7062 opCode = spv::OpDot;
7063 break;
7064 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007065 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007066 break;
7067
7068 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007069 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007070 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007071 else if (isUnsigned)
7072 libCall = spv::GLSLstd450UClamp;
7073 else
7074 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007075 builder.promoteScalar(precision, operands.front(), operands[1]);
7076 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007077 break;
7078 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007079 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7080 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007081 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007082 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007083 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007084 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007085 }
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::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007089 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007090 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007091 break;
7092 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007093 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007094 builder.promoteScalar(precision, operands[0], operands[2]);
7095 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007096 break;
7097
7098 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007099 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007100 break;
7101 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007102 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007103 break;
7104 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007105 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007106 break;
7107 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007108 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007109 break;
7110 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007111 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007112 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007113#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007114 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007115 if (typeProxy == glslang::EbtFloat16)
7116 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007117 libCall = spv::GLSLstd450InterpolateAtSample;
7118 break;
7119 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007120 if (typeProxy == glslang::EbtFloat16)
7121 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007122 libCall = spv::GLSLstd450InterpolateAtOffset;
7123 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007124 case glslang::EOpAddCarry:
7125 opCode = spv::OpIAddCarry;
7126 typeId = builder.makeStructResultType(typeId0, typeId0);
7127 consumedOperands = 2;
7128 break;
7129 case glslang::EOpSubBorrow:
7130 opCode = spv::OpISubBorrow;
7131 typeId = builder.makeStructResultType(typeId0, typeId0);
7132 consumedOperands = 2;
7133 break;
7134 case glslang::EOpUMulExtended:
7135 opCode = spv::OpUMulExtended;
7136 typeId = builder.makeStructResultType(typeId0, typeId0);
7137 consumedOperands = 2;
7138 break;
7139 case glslang::EOpIMulExtended:
7140 opCode = spv::OpSMulExtended;
7141 typeId = builder.makeStructResultType(typeId0, typeId0);
7142 consumedOperands = 2;
7143 break;
7144 case glslang::EOpBitfieldExtract:
7145 if (isUnsigned)
7146 opCode = spv::OpBitFieldUExtract;
7147 else
7148 opCode = spv::OpBitFieldSExtract;
7149 break;
7150 case glslang::EOpBitfieldInsert:
7151 opCode = spv::OpBitFieldInsert;
7152 break;
7153
7154 case glslang::EOpFma:
7155 libCall = spv::GLSLstd450Fma;
7156 break;
7157 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007158 {
7159 libCall = spv::GLSLstd450FrexpStruct;
7160 assert(builder.isPointerType(typeId1));
7161 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007162 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007163 if (width == 16)
7164 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7165 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007166 if (builder.getNumComponents(operands[0]) == 1)
7167 frexpIntType = builder.makeIntegerType(width, true);
7168 else
7169 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7170 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7171 consumedOperands = 1;
7172 }
John Kessenich55e7d112015-11-15 21:33:39 -07007173 break;
7174 case glslang::EOpLdexp:
7175 libCall = spv::GLSLstd450Ldexp;
7176 break;
7177
Rex Xu574ab042016-04-14 16:53:07 +08007178 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007179 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007180
John Kessenich66011cb2018-03-06 16:12:04 -07007181 case glslang::EOpSubgroupBroadcast:
7182 case glslang::EOpSubgroupBallotBitExtract:
7183 case glslang::EOpSubgroupShuffle:
7184 case glslang::EOpSubgroupShuffleXor:
7185 case glslang::EOpSubgroupShuffleUp:
7186 case glslang::EOpSubgroupShuffleDown:
7187 case glslang::EOpSubgroupClusteredAdd:
7188 case glslang::EOpSubgroupClusteredMul:
7189 case glslang::EOpSubgroupClusteredMin:
7190 case glslang::EOpSubgroupClusteredMax:
7191 case glslang::EOpSubgroupClusteredAnd:
7192 case glslang::EOpSubgroupClusteredOr:
7193 case glslang::EOpSubgroupClusteredXor:
7194 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007195 case glslang::EOpSubgroupPartitionedAdd:
7196 case glslang::EOpSubgroupPartitionedMul:
7197 case glslang::EOpSubgroupPartitionedMin:
7198 case glslang::EOpSubgroupPartitionedMax:
7199 case glslang::EOpSubgroupPartitionedAnd:
7200 case glslang::EOpSubgroupPartitionedOr:
7201 case glslang::EOpSubgroupPartitionedXor:
7202 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7203 case glslang::EOpSubgroupPartitionedInclusiveMul:
7204 case glslang::EOpSubgroupPartitionedInclusiveMin:
7205 case glslang::EOpSubgroupPartitionedInclusiveMax:
7206 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7207 case glslang::EOpSubgroupPartitionedInclusiveOr:
7208 case glslang::EOpSubgroupPartitionedInclusiveXor:
7209 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7210 case glslang::EOpSubgroupPartitionedExclusiveMul:
7211 case glslang::EOpSubgroupPartitionedExclusiveMin:
7212 case glslang::EOpSubgroupPartitionedExclusiveMax:
7213 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7214 case glslang::EOpSubgroupPartitionedExclusiveOr:
7215 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007216 return createSubgroupOperation(op, typeId, operands, typeProxy);
7217
Rex Xu9d93a232016-05-05 12:30:44 +08007218 case glslang::EOpSwizzleInvocations:
7219 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7220 libCall = spv::SwizzleInvocationsAMD;
7221 break;
7222 case glslang::EOpSwizzleInvocationsMasked:
7223 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7224 libCall = spv::SwizzleInvocationsMaskedAMD;
7225 break;
7226 case glslang::EOpWriteInvocation:
7227 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7228 libCall = spv::WriteInvocationAMD;
7229 break;
7230
7231 case glslang::EOpMin3:
7232 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7233 if (isFloat)
7234 libCall = spv::FMin3AMD;
7235 else {
7236 if (isUnsigned)
7237 libCall = spv::UMin3AMD;
7238 else
7239 libCall = spv::SMin3AMD;
7240 }
7241 break;
7242 case glslang::EOpMax3:
7243 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7244 if (isFloat)
7245 libCall = spv::FMax3AMD;
7246 else {
7247 if (isUnsigned)
7248 libCall = spv::UMax3AMD;
7249 else
7250 libCall = spv::SMax3AMD;
7251 }
7252 break;
7253 case glslang::EOpMid3:
7254 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7255 if (isFloat)
7256 libCall = spv::FMid3AMD;
7257 else {
7258 if (isUnsigned)
7259 libCall = spv::UMid3AMD;
7260 else
7261 libCall = spv::SMid3AMD;
7262 }
7263 break;
7264
7265 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007266 if (typeProxy == glslang::EbtFloat16)
7267 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007268 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7269 libCall = spv::InterpolateAtVertexAMD;
7270 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05007271 case glslang::EOpBarrier:
7272 {
7273 // This is for the extended controlBarrier function, with four operands.
7274 // The unextended barrier() goes through createNoArgOperation.
7275 assert(operands.size() == 4);
7276 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7277 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7278 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7279 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007280 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7281 spv::MemorySemanticsMakeVisibleKHRMask |
7282 spv::MemorySemanticsOutputMemoryKHRMask |
7283 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007284 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7285 }
7286 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7287 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7288 }
7289 return 0;
7290 }
7291 break;
7292 case glslang::EOpMemoryBarrier:
7293 {
7294 // This is for the extended memoryBarrier function, with three operands.
7295 // The unextended memoryBarrier() goes through createNoArgOperation.
7296 assert(operands.size() == 3);
7297 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7298 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7299 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007300 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7301 spv::MemorySemanticsMakeVisibleKHRMask |
7302 spv::MemorySemanticsOutputMemoryKHRMask |
7303 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007304 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7305 }
7306 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7307 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7308 }
7309 return 0;
7310 }
7311 break;
Chao Chen3c366992018-09-19 11:41:59 -07007312
Chao Chenb50c02e2018-09-19 11:42:24 -07007313 case glslang::EOpReportIntersectionNV:
7314 {
7315 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007316 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007317 }
7318 break;
7319 case glslang::EOpTraceNV:
7320 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007321 builder.createNoResultOp(spv::OpTraceNV, operands);
7322 return 0;
7323 }
7324 break;
7325 case glslang::EOpExecuteCallableNV:
7326 {
7327 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007328 return 0;
7329 }
7330 break;
Chao Chen3c366992018-09-19 11:41:59 -07007331 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7332 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7333 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007334 case glslang::EOpCooperativeMatrixMulAdd:
7335 opCode = spv::OpCooperativeMatrixMulAddNV;
7336 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007337#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007338 default:
7339 return 0;
7340 }
7341
7342 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007343 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007344 // Use an extended instruction from the standard library.
7345 // Construct the call arguments, without modifying the original operands vector.
7346 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7347 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007348 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007349 } else if (opCode == spv::OpDot && !isFloat) {
7350 // int dot(int, int)
7351 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7352 const int componentCount = builder.getNumComponents(operands[0]);
7353 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7354 builder.setPrecision(mulOp, precision);
7355 id = builder.createCompositeExtract(mulOp, typeId, 0);
7356 for (int i = 1; i < componentCount; ++i) {
7357 builder.setPrecision(id, precision);
7358 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7359 }
John Kessenich2359bd02015-12-06 19:29:11 -07007360 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007361 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007362 case 0:
7363 // should all be handled by visitAggregate and createNoArgOperation
7364 assert(0);
7365 return 0;
7366 case 1:
7367 // should all be handled by createUnaryOperation
7368 assert(0);
7369 return 0;
7370 case 2:
7371 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7372 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007373 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007374 // anything 3 or over doesn't have l-value operands, so all should be consumed
7375 assert(consumedOperands == operands.size());
7376 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007377 break;
7378 }
7379 }
7380
John Kessenich55e7d112015-11-15 21:33:39 -07007381 // Decode the return types that were structures
7382 switch (op) {
7383 case glslang::EOpAddCarry:
7384 case glslang::EOpSubBorrow:
7385 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7386 id = builder.createCompositeExtract(id, typeId0, 0);
7387 break;
7388 case glslang::EOpUMulExtended:
7389 case glslang::EOpIMulExtended:
7390 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7391 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7392 break;
7393 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007394 {
7395 assert(operands.size() == 2);
7396 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7397 // "exp" is floating-point type (from HLSL intrinsic)
7398 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7399 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7400 builder.createStore(member1, operands[1]);
7401 } else
7402 // "exp" is integer type (from GLSL built-in function)
7403 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7404 id = builder.createCompositeExtract(id, typeId0, 0);
7405 }
John Kessenich55e7d112015-11-15 21:33:39 -07007406 break;
7407 default:
7408 break;
7409 }
7410
John Kessenich32cfd492016-02-02 12:37:46 -07007411 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007412}
7413
Rex Xu9d93a232016-05-05 12:30:44 +08007414// Intrinsics with no arguments (or no return value, and no precision).
7415spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007416{
John Kessenich155d3512019-08-08 23:29:20 -06007417#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05007418 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7419 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007420
7421 switch (op) {
7422 case glslang::EOpEmitVertex:
7423 builder.createNoResultOp(spv::OpEmitVertex);
7424 return 0;
7425 case glslang::EOpEndPrimitive:
7426 builder.createNoResultOp(spv::OpEndPrimitive);
7427 return 0;
7428 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007429 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007430 if (glslangIntermediate->usingVulkanMemoryModel()) {
7431 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7432 spv::MemorySemanticsOutputMemoryKHRMask |
7433 spv::MemorySemanticsAcquireReleaseMask);
7434 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7435 } else {
7436 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7437 }
John Kessenich82979362017-12-11 04:02:24 -07007438 } else {
7439 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7440 spv::MemorySemanticsWorkgroupMemoryMask |
7441 spv::MemorySemanticsAcquireReleaseMask);
7442 }
John Kessenich140f3df2015-06-26 16:58:36 -06007443 return 0;
7444 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007445 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7446 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007447 return 0;
7448 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007449 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7450 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007451 return 0;
7452 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007453 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7454 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007455 return 0;
7456 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007457 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7458 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007459 return 0;
7460 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007461 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7462 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007463 return 0;
7464 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007465 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7466 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007467 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007468 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007469 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007470 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007471 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007472 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007473 case glslang::EOpDeviceMemoryBarrier:
7474 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7475 spv::MemorySemanticsImageMemoryMask |
7476 spv::MemorySemanticsAcquireReleaseMask);
7477 return 0;
7478 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7479 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7480 spv::MemorySemanticsImageMemoryMask |
7481 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007482 return 0;
7483 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007484 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7485 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007486 return 0;
7487 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007488 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7489 spv::MemorySemanticsWorkgroupMemoryMask |
7490 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007491 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007492 case glslang::EOpSubgroupBarrier:
7493 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7494 spv::MemorySemanticsAcquireReleaseMask);
7495 return spv::NoResult;
7496 case glslang::EOpSubgroupMemoryBarrier:
7497 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7498 spv::MemorySemanticsAcquireReleaseMask);
7499 return spv::NoResult;
7500 case glslang::EOpSubgroupMemoryBarrierBuffer:
7501 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7502 spv::MemorySemanticsAcquireReleaseMask);
7503 return spv::NoResult;
7504 case glslang::EOpSubgroupMemoryBarrierImage:
7505 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7506 spv::MemorySemanticsAcquireReleaseMask);
7507 return spv::NoResult;
7508 case glslang::EOpSubgroupMemoryBarrierShared:
7509 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7510 spv::MemorySemanticsAcquireReleaseMask);
7511 return spv::NoResult;
7512 case glslang::EOpSubgroupElect: {
7513 std::vector<spv::Id> operands;
7514 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7515 }
Rex Xu9d93a232016-05-05 12:30:44 +08007516 case glslang::EOpTime:
7517 {
7518 std::vector<spv::Id> args; // Dummy arguments
7519 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7520 return builder.setPrecision(id, precision);
7521 }
Chao Chenb50c02e2018-09-19 11:42:24 -07007522 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007523 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007524 return 0;
7525 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007526 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007527 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007528
7529 case glslang::EOpBeginInvocationInterlock:
7530 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7531 return 0;
7532 case glslang::EOpEndInvocationInterlock:
7533 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7534 return 0;
7535
Jeff Bolzba6170b2019-07-01 09:23:23 -05007536 case glslang::EOpIsHelperInvocation:
7537 {
7538 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08007539 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
7540 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
7541 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05007542 }
7543
amhagan91fb0092019-07-10 21:14:38 -04007544 case glslang::EOpReadClockSubgroupKHR: {
7545 std::vector<spv::Id> args;
7546 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
7547 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7548 builder.addCapability(spv::CapabilityShaderClockKHR);
7549 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7550 }
7551
7552 case glslang::EOpReadClockDeviceKHR: {
7553 std::vector<spv::Id> args;
7554 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
7555 builder.addExtension(spv::E_SPV_KHR_shader_clock);
7556 builder.addCapability(spv::CapabilityShaderClockKHR);
7557 return builder.createOp(spv::OpReadClockKHR, typeId, args);
7558 }
John Kessenich140f3df2015-06-26 16:58:36 -06007559 default:
John Kessenich155d3512019-08-08 23:29:20 -06007560 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007561 }
John Kessenich155d3512019-08-08 23:29:20 -06007562#endif
7563
7564 logger->missingFunctionality("unknown operation with no arguments");
7565
7566 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007567}
7568
7569spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7570{
John Kessenich2f273362015-07-18 22:34:27 -06007571 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007572 spv::Id id;
7573 if (symbolValues.end() != iter) {
7574 id = iter->second;
7575 return id;
7576 }
7577
7578 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06007579 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
7580 auto forcedType = getForcedType(builtIn, symbol->getType());
7581 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06007582 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06007583 if (forcedType.second != spv::NoType)
7584 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06007585
Rex Xuc884b4a2016-06-29 15:03:44 +08007586 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007587 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7588 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7589 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06007590#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007591 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7592#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007593 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007594 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007595 if (symbol->getQualifier().hasIndex())
7596 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7597 if (symbol->getQualifier().hasComponent())
7598 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007599 // atomic counters use this:
7600 if (symbol->getQualifier().hasOffset())
7601 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007602 }
7603
scygan2c864272016-05-18 18:09:17 +02007604 if (symbol->getQualifier().hasLocation())
7605 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007606 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007607 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007608 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007609 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007610 }
John Kessenich140f3df2015-06-26 16:58:36 -06007611 if (symbol->getQualifier().hasSet())
7612 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007613 else if (IsDescriptorResource(symbol->getType())) {
7614 // default to 0
7615 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7616 }
John Kessenich140f3df2015-06-26 16:58:36 -06007617 if (symbol->getQualifier().hasBinding())
7618 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007619 else if (IsDescriptorResource(symbol->getType())) {
7620 // default to 0
7621 builder.addDecoration(id, spv::DecorationBinding, 0);
7622 }
John Kessenich6c292d32016-02-15 20:58:50 -07007623 if (symbol->getQualifier().hasAttachment())
7624 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich7015bd62019-08-01 03:28:08 -06007625#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007626 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007627 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007628 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007629 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007630 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7631 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7632 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7633 }
7634 if (symbol->getQualifier().hasXfbOffset())
7635 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007636 }
John Kessenich7015bd62019-08-01 03:28:08 -06007637#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007638
Rex Xu1da878f2016-02-21 20:59:01 +08007639 if (symbol->getType().isImage()) {
7640 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007641 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007642 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007643 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007644 }
7645
John Kessenich9c14f772019-06-17 08:38:35 -06007646 // add built-in variable decoration
7647 if (builtIn != spv::BuiltInMax) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007648 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich9c14f772019-06-17 08:38:35 -06007649 }
John Kessenich140f3df2015-06-26 16:58:36 -06007650
John Kessenich5611c6d2018-04-05 11:25:02 -06007651 // nonuniform
7652 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7653
John Kessenicha28f7a72019-08-06 07:00:58 -06007654#ifndef GLSLANG_WEB
chaoc0ad6a4e2016-12-19 16:29:34 -08007655 if (builtIn == spv::BuiltInSampleMask) {
7656 spv::Decoration decoration;
7657 // GL_NV_sample_mask_override_coverage extension
7658 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007659 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007660 else
7661 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007662 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007663 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07007664 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08007665 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7666 }
7667 }
chaoc771d89f2017-01-13 01:10:53 -08007668 else if (builtIn == spv::BuiltInLayer) {
7669 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007670 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007671 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007672 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7673 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7674 }
John Kessenichb41bff62017-08-11 13:07:17 -06007675 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007676 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7677 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007678 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7679 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7680 }
7681 }
7682
chaoc6e5acae2016-12-20 13:28:52 -08007683 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007684 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007685 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007686 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7687 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007688 if (symbol->getQualifier().pervertexNV) {
7689 builder.addDecoration(id, spv::DecorationPerVertexNV);
7690 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7691 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7692 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007693#endif
7694
John Kessenich5d610ee2018-03-07 18:05:55 -07007695 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7696 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7697 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7698 symbol->getType().getQualifier().semanticName);
7699 }
7700
John Kessenich7015bd62019-08-01 03:28:08 -06007701 if (symbol->isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007702 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7703 }
7704
John Kessenich140f3df2015-06-26 16:58:36 -06007705 return id;
7706}
7707
John Kessenicha28f7a72019-08-06 07:00:58 -06007708#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07007709// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7710void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7711{
7712 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007713 if (qualifier.perPrimitiveNV) {
7714 // Need to add capability/extension for fragment shader.
7715 // Mesh shader already adds this by default.
7716 if (glslangIntermediate->getStage() == EShLangFragment) {
7717 builder.addCapability(spv::CapabilityMeshShadingNV);
7718 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7719 }
Chao Chen3c366992018-09-19 11:41:59 -07007720 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007721 }
Chao Chen3c366992018-09-19 11:41:59 -07007722 if (qualifier.perViewNV)
7723 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7724 if (qualifier.perTaskNV)
7725 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7726 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007727 if (qualifier.perPrimitiveNV) {
7728 // Need to add capability/extension for fragment shader.
7729 // Mesh shader already adds this by default.
7730 if (glslangIntermediate->getStage() == EShLangFragment) {
7731 builder.addCapability(spv::CapabilityMeshShadingNV);
7732 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7733 }
Chao Chen3c366992018-09-19 11:41:59 -07007734 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007735 }
Chao Chen3c366992018-09-19 11:41:59 -07007736 if (qualifier.perViewNV)
7737 builder.addDecoration(id, spv::DecorationPerViewNV);
7738 if (qualifier.perTaskNV)
7739 builder.addDecoration(id, spv::DecorationPerTaskNV);
7740 }
7741}
7742#endif
7743
John Kessenich55e7d112015-11-15 21:33:39 -07007744// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007745// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007746//
7747// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7748//
7749// Recursively walk the nodes. The nodes form a tree whose leaves are
7750// regular constants, which themselves are trees that createSpvConstant()
7751// recursively walks. So, this function walks the "top" of the tree:
7752// - emit specialization constant-building instructions for specConstant
7753// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007754spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007755{
John Kessenich7cc0e282016-03-20 00:46:02 -06007756 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007757
qining4f4bb812016-04-03 23:55:17 -04007758 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007759 if (! node.getQualifier().specConstant) {
7760 // hand off to the non-spec-constant path
7761 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7762 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007763 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007764 nextConst, false);
7765 }
7766
7767 // We now know we have a specialization constant to build
7768
John Kessenich155d3512019-08-08 23:29:20 -06007769#ifndef GLSLANG_WEB
John Kessenichd94c0032016-05-30 19:29:40 -06007770 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007771 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7772 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7773 std::vector<spv::Id> dimConstId;
7774 for (int dim = 0; dim < 3; ++dim) {
7775 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7776 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007777 if (specConst) {
7778 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7779 glslangIntermediate->getLocalSizeSpecId(dim));
7780 }
qining4f4bb812016-04-03 23:55:17 -04007781 }
7782 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7783 }
John Kessenich155d3512019-08-08 23:29:20 -06007784#endif
qining4f4bb812016-04-03 23:55:17 -04007785
7786 // An AST node labelled as specialization constant should be a symbol node.
7787 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7788 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007789 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007790 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007791 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7792 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7793 // will set the builder into spec constant op instruction generating mode.
7794 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007795 result = accessChainLoad(sub_tree->getType());
7796 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007797 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007798 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007799 } else {
7800 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007801 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007802 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007803 builder.addName(result, sn->getName().c_str());
7804 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007805 }
qining4f4bb812016-04-03 23:55:17 -04007806
7807 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7808 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007809 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007810 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007811}
7812
John Kessenich140f3df2015-06-26 16:58:36 -06007813// Use 'consts' as the flattened glslang source of scalar constants to recursively
7814// build the aggregate SPIR-V constant.
7815//
7816// If there are not enough elements present in 'consts', 0 will be substituted;
7817// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7818//
qining08408382016-03-21 09:51:37 -04007819spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007820{
7821 // vector of constants for SPIR-V
7822 std::vector<spv::Id> spvConsts;
7823
7824 // Type is used for struct and array constants
7825 spv::Id typeId = convertGlslangToSpvType(glslangType);
7826
7827 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007828 glslang::TType elementType(glslangType, 0);
7829 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007830 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007831 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007832 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007833 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007834 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007835 } else if (glslangType.isCoopMat()) {
7836 glslang::TType componentType(glslangType.getBasicType());
7837 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007838 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007839 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7840 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007841 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007842 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007843 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7844 bool zero = nextConst >= consts.size();
7845 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06007846 case glslang::EbtInt:
7847 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7848 break;
7849 case glslang::EbtUint:
7850 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7851 break;
7852 case glslang::EbtFloat:
7853 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7854 break;
7855 case glslang::EbtBool:
7856 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7857 break;
7858#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07007859 case glslang::EbtInt8:
7860 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7861 break;
7862 case glslang::EbtUint8:
7863 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7864 break;
7865 case glslang::EbtInt16:
7866 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7867 break;
7868 case glslang::EbtUint16:
7869 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7870 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007871 case glslang::EbtInt64:
7872 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7873 break;
7874 case glslang::EbtUint64:
7875 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7876 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007877 case glslang::EbtDouble:
7878 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7879 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007880 case glslang::EbtFloat16:
7881 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7882 break;
John Kessenich39697cd2019-08-08 10:35:51 -06007883#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007884 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007885 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007886 break;
7887 }
7888 ++nextConst;
7889 }
7890 } else {
7891 // we have a non-aggregate (scalar) constant
7892 bool zero = nextConst >= consts.size();
7893 spv::Id scalar = 0;
7894 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06007895 case glslang::EbtInt:
7896 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
7897 break;
7898 case glslang::EbtUint:
7899 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
7900 break;
7901 case glslang::EbtFloat:
7902 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7903 break;
7904 case glslang::EbtBool:
7905 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
7906 break;
7907#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07007908 case glslang::EbtInt8:
7909 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7910 break;
7911 case glslang::EbtUint8:
7912 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7913 break;
7914 case glslang::EbtInt16:
7915 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7916 break;
7917 case glslang::EbtUint16:
7918 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7919 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007920 case glslang::EbtInt64:
7921 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7922 break;
7923 case glslang::EbtUint64:
7924 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7925 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007926 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007927 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007928 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007929 case glslang::EbtFloat16:
7930 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7931 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06007932 case glslang::EbtReference:
7933 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7934 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
7935 break;
John Kessenich39697cd2019-08-08 10:35:51 -06007936#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007937 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007938 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007939 break;
7940 }
7941 ++nextConst;
7942 return scalar;
7943 }
7944
7945 return builder.makeCompositeConstant(typeId, spvConsts);
7946}
7947
John Kessenich7c1aa102015-10-15 13:29:11 -06007948// Return true if the node is a constant or symbol whose reading has no
7949// non-trivial observable cost or effect.
7950bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7951{
7952 // don't know what this is
7953 if (node == nullptr)
7954 return false;
7955
7956 // a constant is safe
7957 if (node->getAsConstantUnion() != nullptr)
7958 return true;
7959
7960 // not a symbol means non-trivial
7961 if (node->getAsSymbolNode() == nullptr)
7962 return false;
7963
7964 // a symbol, depends on what's being read
7965 switch (node->getType().getQualifier().storage) {
7966 case glslang::EvqTemporary:
7967 case glslang::EvqGlobal:
7968 case glslang::EvqIn:
7969 case glslang::EvqInOut:
7970 case glslang::EvqConst:
7971 case glslang::EvqConstReadOnly:
7972 case glslang::EvqUniform:
7973 return true;
7974 default:
7975 return false;
7976 }
qining25262b32016-05-06 17:25:16 -04007977}
John Kessenich7c1aa102015-10-15 13:29:11 -06007978
7979// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007980// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007981// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007982// Return true if trivial.
7983bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7984{
7985 if (node == nullptr)
7986 return false;
7987
John Kessenich84cc15f2017-05-24 16:44:47 -06007988 // count non scalars as trivial, as well as anything coming from HLSL
7989 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007990 return true;
7991
John Kessenich7c1aa102015-10-15 13:29:11 -06007992 // symbols and constants are trivial
7993 if (isTrivialLeaf(node))
7994 return true;
7995
7996 // otherwise, it needs to be a simple operation or one or two leaf nodes
7997
7998 // not a simple operation
7999 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8000 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8001 if (binaryNode == nullptr && unaryNode == nullptr)
8002 return false;
8003
8004 // not on leaf nodes
8005 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8006 return false;
8007
8008 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8009 return false;
8010 }
8011
8012 switch (node->getAsOperator()->getOp()) {
8013 case glslang::EOpLogicalNot:
8014 case glslang::EOpConvIntToBool:
8015 case glslang::EOpConvUintToBool:
8016 case glslang::EOpConvFloatToBool:
8017 case glslang::EOpConvDoubleToBool:
8018 case glslang::EOpEqual:
8019 case glslang::EOpNotEqual:
8020 case glslang::EOpLessThan:
8021 case glslang::EOpGreaterThan:
8022 case glslang::EOpLessThanEqual:
8023 case glslang::EOpGreaterThanEqual:
8024 case glslang::EOpIndexDirect:
8025 case glslang::EOpIndexDirectStruct:
8026 case glslang::EOpLogicalXor:
8027 case glslang::EOpAny:
8028 case glslang::EOpAll:
8029 return true;
8030 default:
8031 return false;
8032 }
8033}
8034
8035// Emit short-circuiting code, where 'right' is never evaluated unless
8036// the left side is true (for &&) or false (for ||).
8037spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
8038{
8039 spv::Id boolTypeId = builder.makeBoolType();
8040
8041 // emit left operand
8042 builder.clearAccessChain();
8043 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008044 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008045
8046 // Operands to accumulate OpPhi operands
8047 std::vector<spv::Id> phiOperands;
8048 // accumulate left operand's phi information
8049 phiOperands.push_back(leftId);
8050 phiOperands.push_back(builder.getBuildPoint()->getId());
8051
8052 // Make the two kinds of operation symmetric with a "!"
8053 // || => emit "if (! left) result = right"
8054 // && => emit "if ( left) result = right"
8055 //
8056 // TODO: this runtime "not" for || could be avoided by adding functionality
8057 // to 'builder' to have an "else" without an "then"
8058 if (op == glslang::EOpLogicalOr)
8059 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8060
8061 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008062 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008063
8064 // emit right operand as the "then" part of the "if"
8065 builder.clearAccessChain();
8066 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008067 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008068
8069 // accumulate left operand's phi information
8070 phiOperands.push_back(rightId);
8071 phiOperands.push_back(builder.getBuildPoint()->getId());
8072
8073 // finish the "if"
8074 ifBuilder.makeEndIf();
8075
8076 // phi together the two results
8077 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8078}
8079
John Kessenicha28f7a72019-08-06 07:00:58 -06008080#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008081// Return type Id of the imported set of extended instructions corresponds to the name.
8082// Import this set if it has not been imported yet.
8083spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8084{
8085 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8086 return extBuiltinMap[name];
8087 else {
Rex Xu51596642016-09-21 18:56:12 +08008088 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008089 spv::Id extBuiltins = builder.import(name);
8090 extBuiltinMap[name] = extBuiltins;
8091 return extBuiltins;
8092 }
8093}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008094#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008095
John Kessenich140f3df2015-06-26 16:58:36 -06008096}; // end anonymous namespace
8097
8098namespace glslang {
8099
John Kessenich68d78fd2015-07-12 19:28:10 -06008100void GetSpirvVersion(std::string& version)
8101{
John Kessenich9e55f632015-07-15 10:03:39 -06008102 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008103 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008104 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008105 version = buf;
8106}
8107
John Kessenicha372a3e2017-11-02 22:32:14 -06008108// For low-order part of the generator's magic number. Bump up
8109// when there is a change in the style (e.g., if SSA form changes,
8110// or a different instruction sequence to do something gets used).
8111int GetSpirvGeneratorVersion()
8112{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008113 // return 1; // start
8114 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008115 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008116 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008117 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008118 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8119 // versions 4 and 6 each generate OpArrayLength as it has long been done
8120 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06008121}
8122
John Kessenich140f3df2015-06-26 16:58:36 -06008123// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008124void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008125{
8126 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008127 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008128 if (out.fail())
8129 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008130 for (int i = 0; i < (int)spirv.size(); ++i) {
8131 unsigned int word = spirv[i];
8132 out.write((const char*)&word, 4);
8133 }
8134 out.close();
8135}
8136
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008137// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008138void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008139{
John Kessenich155d3512019-08-08 23:29:20 -06008140#ifndef GLSLANG_WEB
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008141 std::ofstream out;
8142 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008143 if (out.fail())
8144 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008145 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008146 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008147 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008148 if (varName != nullptr) {
8149 out << "\t #pragma once" << std::endl;
8150 out << "const uint32_t " << varName << "[] = {" << std::endl;
8151 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008152 const int WORDS_PER_LINE = 8;
8153 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8154 out << "\t";
8155 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8156 const unsigned int word = spirv[i + j];
8157 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8158 if (i + j + 1 < (int)spirv.size()) {
8159 out << ",";
8160 }
8161 }
8162 out << std::endl;
8163 }
Flavio15017db2017-02-15 14:29:33 -08008164 if (varName != nullptr) {
8165 out << "};";
8166 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008167 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008168#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008169}
8170
John Kessenich140f3df2015-06-26 16:58:36 -06008171//
8172// Set up the glslang traversal
8173//
John Kessenich4e11b612018-08-30 16:56:59 -06008174void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008175{
Lei Zhang17535f72016-05-04 15:55:59 -04008176 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008177 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008178}
8179
John Kessenich4e11b612018-08-30 16:56:59 -06008180void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008181 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008182{
John Kessenich140f3df2015-06-26 16:58:36 -06008183 TIntermNode* root = intermediate.getTreeRoot();
8184
8185 if (root == 0)
8186 return;
8187
John Kessenich4e11b612018-08-30 16:56:59 -06008188 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008189 if (options == nullptr)
8190 options = &defaultOptions;
8191
John Kessenich4e11b612018-08-30 16:56:59 -06008192 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008193
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008194 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008195 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008196 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008197 it.dumpSpv(spirv);
8198
GregFfb03a552018-03-29 11:49:14 -06008199#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008200 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8201 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008202 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8203 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008204 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008205 prelegalization = false;
8206 }
John Kessenich717c80a2018-08-23 15:17:10 -06008207
John Kessenich4e11b612018-08-30 16:56:59 -06008208 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008209 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008210
John Kessenich717c80a2018-08-23 15:17:10 -06008211 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008212 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008213
GregFcd1f1692017-09-21 18:40:22 -06008214#endif
8215
John Kessenich4e11b612018-08-30 16:56:59 -06008216 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008217}
8218
8219}; // end namespace glslang