blob: d39c260907d068ca6a097d4ade03e092250ee244 [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.
3// Copyright (C) 2015-2016 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 Xu9d93a232016-05-05 12:30:44 +080049#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080050 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080051#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080052#ifdef NV_EXTENSIONS
53 #include "GLSL.ext.NV.h"
54#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060055}
John Kessenich140f3df2015-06-26 16:58:36 -060056
GregFfb03a552018-03-29 11:49:14 -060057#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -060058 #include "spirv-tools/optimizer.hpp"
59 #include "message.h"
GregFcd1f1692017-09-21 18:40:22 -060060#endif
61
GregFfb03a552018-03-29 11:49:14 -060062#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -060063using namespace spvtools;
64#endif
65
John Kessenich140f3df2015-06-26 16:58:36 -060066// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020067#include "../glslang/MachineIndependent/localintermediate.h"
68#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060069#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050070#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060071
John Kessenich140f3df2015-06-26 16:58:36 -060072#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050073#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040074#include <list>
75#include <map>
76#include <stack>
77#include <string>
78#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060079
80namespace {
81
qining4c912612016-04-01 10:35:16 -040082namespace {
83class SpecConstantOpModeGuard {
84public:
85 SpecConstantOpModeGuard(spv::Builder* builder)
86 : builder_(builder) {
87 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040088 }
89 ~SpecConstantOpModeGuard() {
90 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
91 : builder_->setToNormalCodeGenMode();
92 }
qining40887662016-04-03 22:20:42 -040093 void turnOnSpecConstantOpMode() {
94 builder_->setToSpecConstCodeGenMode();
95 }
qining4c912612016-04-01 10:35:16 -040096
97private:
98 spv::Builder* builder_;
99 bool previous_flag_;
100};
John Kessenichead86222018-03-28 18:01:20 -0600101
102struct OpDecorations {
103 spv::Decoration precision;
104 spv::Decoration noContraction;
105};
106
107} // namespace
qining4c912612016-04-01 10:35:16 -0400108
John Kessenich140f3df2015-06-26 16:58:36 -0600109//
110// The main holder of information for translating glslang to SPIR-V.
111//
112// Derives from the AST walking base class.
113//
114class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
115public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700116 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
117 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700118 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600119
120 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
121 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
122 void visitConstantUnion(glslang::TIntermConstantUnion*);
123 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
124 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
125 void visitSymbol(glslang::TIntermSymbol* symbol);
126 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
127 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
128 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
129
John Kessenichfca82622016-11-26 13:23:20 -0700130 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700131 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600132
133protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700134 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
135 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
136
Rex Xu17ff3432016-10-14 17:41:45 +0800137 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800138 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100139 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700140 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700141 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
142 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenicha2858d92018-01-31 08:11:18 -0700143 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, unsigned int& dependencyLength) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600144 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich140f3df2015-06-26 16:58:36 -0600145 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
146 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600147 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
148 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
149 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600150 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kessenichead86222018-03-28 18:01:20 -0600151 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
152 bool lastBufferBlockMember);
John Kessenich0e737842017-03-24 18:38:16 -0600153 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600154 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
155 glslang::TLayoutPacking, const glslang::TQualifier&);
156 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
157 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700158 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700159 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800160 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600161 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700162 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700163 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
164 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700165 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
166 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100167 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600168
John Kessenich6fccb3c2016-09-19 16:01:41 -0600169 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd41993d2017-09-10 15:21:05 -0600170 bool writableParam(glslang::TStorageQualifier);
171 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600172 void makeFunctions(const glslang::TIntermSequence&);
173 void makeGlobalInitializers(const glslang::TIntermSequence&);
174 void visitFunctions(const glslang::TIntermSequence&);
175 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800176 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600177 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
178 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600179 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
180
John Kessenichead86222018-03-28 18:01:20 -0600181 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
182 glslang::TBasicType typeProxy, bool reduceComparison = true);
183 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
184 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
185 glslang::TBasicType typeProxy);
186 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
187 glslang::TBasicType typeProxy);
188 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
189 glslang::TBasicType typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -0700190 spv::Id createConversionOperation(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600191 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800192 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800193 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800194 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700195 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600196 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 +0800197 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600198 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
qining08408382016-03-21 09:51:37 -0400199 spv::Id createSpvConstant(const glslang::TIntermTyped&);
200 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600201 bool isTrivialLeaf(const glslang::TIntermTyped* node);
202 bool isTrivial(const glslang::TIntermTyped* node);
203 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500204#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800205 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500206#endif
John Kessenich66011cb2018-03-06 16:12:04 -0700207 void addPre13Extension(const char* ext)
208 {
209 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
210 builder.addExtension(ext);
211 }
John Kessenich140f3df2015-06-26 16:58:36 -0600212
John Kessenich121853f2017-05-31 17:11:16 -0600213 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600214 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600215 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700216 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600217 int sequenceDepth;
218
Lei Zhang17535f72016-05-04 15:55:59 -0400219 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400220
John Kessenich140f3df2015-06-26 16:58:36 -0600221 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
222 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700223 bool inEntryPoint;
224 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700225 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 -0700226 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600227 const glslang::TIntermediate* glslangIntermediate;
228 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800229 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600230
John Kessenich2f273362015-07-18 22:34:27 -0600231 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600232 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600233 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700234 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700235 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
236 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600237 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700238 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
John Kessenich140f3df2015-06-26 16:58:36 -0600239};
240
241//
242// Helper functions for translating glslang representations to SPIR-V enumerants.
243//
244
245// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700246spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600247{
John Kessenich66e2faf2016-03-12 18:34:36 -0700248 switch (source) {
249 case glslang::EShSourceGlsl:
250 switch (profile) {
251 case ENoProfile:
252 case ECoreProfile:
253 case ECompatibilityProfile:
254 return spv::SourceLanguageGLSL;
255 case EEsProfile:
256 return spv::SourceLanguageESSL;
257 default:
258 return spv::SourceLanguageUnknown;
259 }
260 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600261 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600262 default:
263 return spv::SourceLanguageUnknown;
264 }
265}
266
267// Translate glslang language (stage) to SPIR-V execution model.
268spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
269{
270 switch (stage) {
271 case EShLangVertex: return spv::ExecutionModelVertex;
272 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
273 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
274 case EShLangGeometry: return spv::ExecutionModelGeometry;
275 case EShLangFragment: return spv::ExecutionModelFragment;
276 case EShLangCompute: return spv::ExecutionModelGLCompute;
277 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700278 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600279 return spv::ExecutionModelFragment;
280 }
281}
282
John Kessenich140f3df2015-06-26 16:58:36 -0600283// Translate glslang sampler type to SPIR-V dimensionality.
284spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
285{
286 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700287 case glslang::Esd1D: return spv::Dim1D;
288 case glslang::Esd2D: return spv::Dim2D;
289 case glslang::Esd3D: return spv::Dim3D;
290 case glslang::EsdCube: return spv::DimCube;
291 case glslang::EsdRect: return spv::DimRect;
292 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700293 case glslang::EsdSubpass: return spv::DimSubpassData;
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::Dim2D;
297 }
298}
299
John Kessenichf6640762016-08-01 19:44:00 -0600300// Translate glslang precision to SPIR-V precision decorations.
301spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600302{
John Kessenichf6640762016-08-01 19:44:00 -0600303 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700304 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600305 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600306 default:
307 return spv::NoPrecision;
308 }
309}
310
John Kessenichf6640762016-08-01 19:44:00 -0600311// Translate glslang type to SPIR-V precision decorations.
312spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
313{
314 return TranslatePrecisionDecoration(type.getQualifier().precision);
315}
316
John Kessenich140f3df2015-06-26 16:58:36 -0600317// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600318spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600319{
320 if (type.getBasicType() == glslang::EbtBlock) {
321 switch (type.getQualifier().storage) {
322 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600323 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600324 case glslang::EvqVaryingIn: return spv::DecorationBlock;
325 case glslang::EvqVaryingOut: return spv::DecorationBlock;
326 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700327 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600328 break;
329 }
330 }
331
John Kessenich4016e382016-07-15 11:53:56 -0600332 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600333}
334
Rex Xu1da878f2016-02-21 20:59:01 +0800335// Translate glslang type to SPIR-V memory decorations.
336void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
337{
338 if (qualifier.coherent)
339 memory.push_back(spv::DecorationCoherent);
340 if (qualifier.volatil)
341 memory.push_back(spv::DecorationVolatile);
342 if (qualifier.restrict)
343 memory.push_back(spv::DecorationRestrict);
344 if (qualifier.readonly)
345 memory.push_back(spv::DecorationNonWritable);
346 if (qualifier.writeonly)
347 memory.push_back(spv::DecorationNonReadable);
348}
349
John Kessenich140f3df2015-06-26 16:58:36 -0600350// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700351spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600352{
353 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700354 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600355 case glslang::ElmRowMajor:
356 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700357 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600358 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700359 default:
360 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600361 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600362 }
363 } else {
364 switch (type.getBasicType()) {
365 default:
John Kessenich4016e382016-07-15 11:53:56 -0600366 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600367 break;
368 case glslang::EbtBlock:
369 switch (type.getQualifier().storage) {
370 case glslang::EvqUniform:
371 case glslang::EvqBuffer:
372 switch (type.getQualifier().layoutPacking) {
373 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600374 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
375 default:
John Kessenich4016e382016-07-15 11:53:56 -0600376 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600377 }
378 case glslang::EvqVaryingIn:
379 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700380 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600381 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600382 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700383 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600384 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600385 }
386 }
387 }
388}
389
390// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600391// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700392// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800393spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600394{
Rex Xubbceed72016-05-21 09:40:44 +0800395 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700396 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600397 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800398 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700399 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700400 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600401 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800402#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800403 else if (qualifier.explicitInterp) {
404 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800405 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800406 }
Rex Xu9d93a232016-05-05 12:30:44 +0800407#endif
Rex Xubbceed72016-05-21 09:40:44 +0800408 else
John Kessenich4016e382016-07-15 11:53:56 -0600409 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800410}
411
412// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600413// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800414// should be applied.
415spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
416{
417 if (qualifier.patch)
418 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700419 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600420 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700421 else if (qualifier.sample) {
422 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600423 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700424 } else
John Kessenich4016e382016-07-15 11:53:56 -0600425 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600426}
427
John Kessenich92187592016-02-01 13:45:25 -0700428// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700429spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600430{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700431 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600432 return spv::DecorationInvariant;
433 else
John Kessenich4016e382016-07-15 11:53:56 -0600434 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600435}
436
qining9220dbb2016-05-04 17:34:38 -0400437// If glslang type is noContraction, return SPIR-V NoContraction decoration.
438spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
439{
440 if (qualifier.noContraction)
441 return spv::DecorationNoContraction;
442 else
John Kessenich4016e382016-07-15 11:53:56 -0600443 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400444}
445
David Netoa901ffe2016-06-08 14:11:40 +0100446// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
447// associated capabilities when required. For some built-in variables, a capability
448// is generated only when using the variable in an executable instruction, but not when
449// just declaring a struct member variable with it. This is true for PointSize,
450// ClipDistance, and CullDistance.
451spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600452{
453 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700454 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600455 // Defer adding the capability until the built-in is actually used.
456 if (! memberDeclaration) {
457 switch (glslangIntermediate->getStage()) {
458 case EShLangGeometry:
459 builder.addCapability(spv::CapabilityGeometryPointSize);
460 break;
461 case EShLangTessControl:
462 case EShLangTessEvaluation:
463 builder.addCapability(spv::CapabilityTessellationPointSize);
464 break;
465 default:
466 break;
467 }
John Kessenich92187592016-02-01 13:45:25 -0700468 }
469 return spv::BuiltInPointSize;
470
John Kessenichebb50532016-05-16 19:22:05 -0600471 // These *Distance capabilities logically belong here, but if the member is declared and
472 // then never used, consumers of SPIR-V prefer the capability not be declared.
473 // They are now generated when used, rather than here when declared.
474 // Potentially, the specification should be more clear what the minimum
475 // use needed is to trigger the capability.
476 //
John Kessenich92187592016-02-01 13:45:25 -0700477 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100478 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800479 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700480 return spv::BuiltInClipDistance;
481
482 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100483 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800484 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700485 return spv::BuiltInCullDistance;
486
487 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600488 builder.addCapability(spv::CapabilityMultiViewport);
489 if (glslangIntermediate->getStage() == EShLangVertex ||
490 glslangIntermediate->getStage() == EShLangTessControl ||
491 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800492
John Kessenichba6a3c22017-09-13 13:22:50 -0600493 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
494 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800495 }
John Kessenich92187592016-02-01 13:45:25 -0700496 return spv::BuiltInViewportIndex;
497
John Kessenich5e801132016-02-15 11:09:46 -0700498 case glslang::EbvSampleId:
499 builder.addCapability(spv::CapabilitySampleRateShading);
500 return spv::BuiltInSampleId;
501
502 case glslang::EbvSamplePosition:
503 builder.addCapability(spv::CapabilitySampleRateShading);
504 return spv::BuiltInSamplePosition;
505
506 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700507 return spv::BuiltInSampleMask;
508
John Kessenich78a45572016-07-08 14:05:15 -0600509 case glslang::EbvLayer:
John Kessenichba6a3c22017-09-13 13:22:50 -0600510 builder.addCapability(spv::CapabilityGeometry);
511 if (glslangIntermediate->getStage() == EShLangVertex ||
512 glslangIntermediate->getStage() == EShLangTessControl ||
513 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800514
John Kessenichba6a3c22017-09-13 13:22:50 -0600515 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
516 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800517 }
John Kessenich78a45572016-07-08 14:05:15 -0600518 return spv::BuiltInLayer;
519
John Kessenich140f3df2015-06-26 16:58:36 -0600520 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600521 case glslang::EbvVertexId: return spv::BuiltInVertexId;
522 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700523 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
524 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800525
John Kessenichda581a22015-10-14 14:10:30 -0600526 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700527 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800528 builder.addCapability(spv::CapabilityDrawParameters);
529 return spv::BuiltInBaseVertex;
530
John Kessenichda581a22015-10-14 14:10:30 -0600531 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700532 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800533 builder.addCapability(spv::CapabilityDrawParameters);
534 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200535
John Kessenichda581a22015-10-14 14:10:30 -0600536 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700537 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800538 builder.addCapability(spv::CapabilityDrawParameters);
539 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200540
541 case glslang::EbvPrimitiveId:
542 if (glslangIntermediate->getStage() == EShLangFragment)
543 builder.addCapability(spv::CapabilityGeometry);
544 return spv::BuiltInPrimitiveId;
545
Rex Xu37cdcee2017-06-29 17:46:34 +0800546 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800547 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
548 builder.addCapability(spv::CapabilityStencilExportEXT);
549 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800550
John Kessenich140f3df2015-06-26 16:58:36 -0600551 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600552 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
553 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
554 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
555 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
556 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
557 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
558 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600559 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
560 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
561 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
562 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
563 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
564 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
565 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
566 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800567
Rex Xu574ab042016-04-14 16:53:07 +0800568 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800569 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800570 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
571 return spv::BuiltInSubgroupSize;
572
Rex Xu574ab042016-04-14 16:53:07 +0800573 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800574 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800575 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
576 return spv::BuiltInSubgroupLocalInvocationId;
577
Rex Xu574ab042016-04-14 16:53:07 +0800578 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800579 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
580 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
581 return spv::BuiltInSubgroupEqMaskKHR;
582
Rex Xu574ab042016-04-14 16:53:07 +0800583 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800584 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
585 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
586 return spv::BuiltInSubgroupGeMaskKHR;
587
Rex Xu574ab042016-04-14 16:53:07 +0800588 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800589 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
590 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
591 return spv::BuiltInSubgroupGtMaskKHR;
592
Rex Xu574ab042016-04-14 16:53:07 +0800593 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800594 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
595 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
596 return spv::BuiltInSubgroupLeMaskKHR;
597
Rex Xu574ab042016-04-14 16:53:07 +0800598 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800599 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
600 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
601 return spv::BuiltInSubgroupLtMaskKHR;
602
John Kessenich66011cb2018-03-06 16:12:04 -0700603 case glslang::EbvNumSubgroups:
604 builder.addCapability(spv::CapabilityGroupNonUniform);
605 return spv::BuiltInNumSubgroups;
606
607 case glslang::EbvSubgroupID:
608 builder.addCapability(spv::CapabilityGroupNonUniform);
609 return spv::BuiltInSubgroupId;
610
611 case glslang::EbvSubgroupSize2:
612 builder.addCapability(spv::CapabilityGroupNonUniform);
613 return spv::BuiltInSubgroupSize;
614
615 case glslang::EbvSubgroupInvocation2:
616 builder.addCapability(spv::CapabilityGroupNonUniform);
617 return spv::BuiltInSubgroupLocalInvocationId;
618
619 case glslang::EbvSubgroupEqMask2:
620 builder.addCapability(spv::CapabilityGroupNonUniform);
621 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
622 return spv::BuiltInSubgroupEqMask;
623
624 case glslang::EbvSubgroupGeMask2:
625 builder.addCapability(spv::CapabilityGroupNonUniform);
626 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
627 return spv::BuiltInSubgroupGeMask;
628
629 case glslang::EbvSubgroupGtMask2:
630 builder.addCapability(spv::CapabilityGroupNonUniform);
631 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
632 return spv::BuiltInSubgroupGtMask;
633
634 case glslang::EbvSubgroupLeMask2:
635 builder.addCapability(spv::CapabilityGroupNonUniform);
636 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
637 return spv::BuiltInSubgroupLeMask;
638
639 case glslang::EbvSubgroupLtMask2:
640 builder.addCapability(spv::CapabilityGroupNonUniform);
641 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
642 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800643#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800644 case glslang::EbvBaryCoordNoPersp:
645 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
646 return spv::BuiltInBaryCoordNoPerspAMD;
647
648 case glslang::EbvBaryCoordNoPerspCentroid:
649 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
650 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
651
652 case glslang::EbvBaryCoordNoPerspSample:
653 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
654 return spv::BuiltInBaryCoordNoPerspSampleAMD;
655
656 case glslang::EbvBaryCoordSmooth:
657 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
658 return spv::BuiltInBaryCoordSmoothAMD;
659
660 case glslang::EbvBaryCoordSmoothCentroid:
661 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
662 return spv::BuiltInBaryCoordSmoothCentroidAMD;
663
664 case glslang::EbvBaryCoordSmoothSample:
665 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
666 return spv::BuiltInBaryCoordSmoothSampleAMD;
667
668 case glslang::EbvBaryCoordPullModel:
669 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
670 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800671#endif
chaoc771d89f2017-01-13 01:10:53 -0800672
John Kessenich6c8aaac2017-02-27 01:20:51 -0700673 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700674 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700675 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700676 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700677
678 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700679 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700680 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700681 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700682
chaoc771d89f2017-01-13 01:10:53 -0800683#ifdef NV_EXTENSIONS
684 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800685 if (!memberDeclaration) {
686 builder.addExtension(spv::E_SPV_NV_viewport_array2);
687 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
688 }
chaoc771d89f2017-01-13 01:10:53 -0800689 return spv::BuiltInViewportMaskNV;
690 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800691 if (!memberDeclaration) {
692 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
693 builder.addCapability(spv::CapabilityShaderStereoViewNV);
694 }
chaoc771d89f2017-01-13 01:10:53 -0800695 return spv::BuiltInSecondaryPositionNV;
696 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800697 if (!memberDeclaration) {
698 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
699 builder.addCapability(spv::CapabilityShaderStereoViewNV);
700 }
chaoc771d89f2017-01-13 01:10:53 -0800701 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800702 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800703 if (!memberDeclaration) {
704 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
705 builder.addCapability(spv::CapabilityPerViewAttributesNV);
706 }
chaocdf3956c2017-02-14 14:52:34 -0800707 return spv::BuiltInPositionPerViewNV;
708 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800709 if (!memberDeclaration) {
710 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
711 builder.addCapability(spv::CapabilityPerViewAttributesNV);
712 }
chaocdf3956c2017-02-14 14:52:34 -0800713 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700714 case glslang::EbvFragFullyCoveredNV:
715 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
716 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
717 return spv::BuiltInFullyCoveredEXT;
chaoc771d89f2017-01-13 01:10:53 -0800718#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800719 default:
720 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600721 }
722}
723
Rex Xufc618912015-09-09 16:42:49 +0800724// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700725spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800726{
727 assert(type.getBasicType() == glslang::EbtSampler);
728
John Kessenich5d0fa972016-02-15 11:57:00 -0700729 // Check for capabilities
730 switch (type.getQualifier().layoutFormat) {
731 case glslang::ElfRg32f:
732 case glslang::ElfRg16f:
733 case glslang::ElfR11fG11fB10f:
734 case glslang::ElfR16f:
735 case glslang::ElfRgba16:
736 case glslang::ElfRgb10A2:
737 case glslang::ElfRg16:
738 case glslang::ElfRg8:
739 case glslang::ElfR16:
740 case glslang::ElfR8:
741 case glslang::ElfRgba16Snorm:
742 case glslang::ElfRg16Snorm:
743 case glslang::ElfRg8Snorm:
744 case glslang::ElfR16Snorm:
745 case glslang::ElfR8Snorm:
746
747 case glslang::ElfRg32i:
748 case glslang::ElfRg16i:
749 case glslang::ElfRg8i:
750 case glslang::ElfR16i:
751 case glslang::ElfR8i:
752
753 case glslang::ElfRgb10a2ui:
754 case glslang::ElfRg32ui:
755 case glslang::ElfRg16ui:
756 case glslang::ElfRg8ui:
757 case glslang::ElfR16ui:
758 case glslang::ElfR8ui:
759 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
760 break;
761
762 default:
763 break;
764 }
765
766 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800767 switch (type.getQualifier().layoutFormat) {
768 case glslang::ElfNone: return spv::ImageFormatUnknown;
769 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
770 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
771 case glslang::ElfR32f: return spv::ImageFormatR32f;
772 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
773 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
774 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
775 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
776 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
777 case glslang::ElfR16f: return spv::ImageFormatR16f;
778 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
779 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
780 case glslang::ElfRg16: return spv::ImageFormatRg16;
781 case glslang::ElfRg8: return spv::ImageFormatRg8;
782 case glslang::ElfR16: return spv::ImageFormatR16;
783 case glslang::ElfR8: return spv::ImageFormatR8;
784 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
785 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
786 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
787 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
788 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
789 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
790 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
791 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
792 case glslang::ElfR32i: return spv::ImageFormatR32i;
793 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
794 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
795 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
796 case glslang::ElfR16i: return spv::ImageFormatR16i;
797 case glslang::ElfR8i: return spv::ImageFormatR8i;
798 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
799 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
800 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
801 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
802 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
803 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
804 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
805 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
806 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
807 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600808 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800809 }
810}
811
John Kesseniche18fd202018-01-30 11:01:39 -0700812spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +0800813{
John Kesseniche18fd202018-01-30 11:01:39 -0700814 if (selectionNode.getFlatten())
815 return spv::SelectionControlFlattenMask;
816 if (selectionNode.getDontFlatten())
817 return spv::SelectionControlDontFlattenMask;
818 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +0800819}
820
John Kesseniche18fd202018-01-30 11:01:39 -0700821spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -0600822{
John Kesseniche18fd202018-01-30 11:01:39 -0700823 if (switchNode.getFlatten())
824 return spv::SelectionControlFlattenMask;
825 if (switchNode.getDontFlatten())
826 return spv::SelectionControlDontFlattenMask;
827 return spv::SelectionControlMaskNone;
828}
829
John Kessenicha2858d92018-01-31 08:11:18 -0700830// return a non-0 dependency if the dependency argument must be set
831spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
832 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -0700833{
834 spv::LoopControlMask control = spv::LoopControlMaskNone;
835
836 if (loopNode.getDontUnroll())
837 control = control | spv::LoopControlDontUnrollMask;
838 if (loopNode.getUnroll())
839 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -0700840 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -0700841 control = control | spv::LoopControlDependencyInfiniteMask;
842 else if (loopNode.getLoopDependency() > 0) {
843 control = control | spv::LoopControlDependencyLengthMask;
844 dependencyLength = loopNode.getLoopDependency();
845 }
John Kesseniche18fd202018-01-30 11:01:39 -0700846
847 return control;
steve-lunargf1709e72017-05-02 20:14:50 -0600848}
849
John Kessenicha5c5fb62017-05-05 05:09:58 -0600850// Translate glslang type to SPIR-V storage class.
851spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
852{
853 if (type.getQualifier().isPipeInput())
854 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600855 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -0600856 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600857
858 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
859 type.getQualifier().storage == glslang::EvqUniform) {
860 if (type.getBasicType() == glslang::EbtAtomicUint)
861 return spv::StorageClassAtomicCounter;
862 if (type.containsOpaque())
863 return spv::StorageClassUniformConstant;
864 }
865
866 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -0700867 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -0600868 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600869 }
870
871 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600872 if (type.getQualifier().layoutPushConstant)
873 return spv::StorageClassPushConstant;
874 if (type.getBasicType() == glslang::EbtBlock)
875 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600876 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600877 }
John Kessenichbed4e4f2017-09-08 02:38:07 -0600878
879 switch (type.getQualifier().storage) {
880 case glslang::EvqShared: return spv::StorageClassWorkgroup;
881 case glslang::EvqGlobal: return spv::StorageClassPrivate;
882 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
883 case glslang::EvqTemporary: return spv::StorageClassFunction;
884 default:
885 assert(0);
886 break;
887 }
888
889 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600890}
891
qining25262b32016-05-06 17:25:16 -0400892// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700893// descriptor set.
894bool IsDescriptorResource(const glslang::TType& type)
895{
John Kessenichf7497e22016-03-08 21:36:22 -0700896 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700897 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700898 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700899
900 // non block...
901 // basically samplerXXX/subpass/sampler/texture are all included
902 // if they are the global-scope-class, not the function parameter
903 // (or local, if they ever exist) class.
904 if (type.getBasicType() == glslang::EbtSampler)
905 return type.getQualifier().isUniformOrBuffer();
906
907 // None of the above.
908 return false;
909}
910
John Kesseniche0b6cad2015-12-24 10:30:13 -0700911void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
912{
913 if (child.layoutMatrix == glslang::ElmNone)
914 child.layoutMatrix = parent.layoutMatrix;
915
916 if (parent.invariant)
917 child.invariant = true;
918 if (parent.nopersp)
919 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800920#ifdef AMD_EXTENSIONS
921 if (parent.explicitInterp)
922 child.explicitInterp = true;
923#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700924 if (parent.flat)
925 child.flat = true;
926 if (parent.centroid)
927 child.centroid = true;
928 if (parent.patch)
929 child.patch = true;
930 if (parent.sample)
931 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800932 if (parent.coherent)
933 child.coherent = true;
934 if (parent.volatil)
935 child.volatil = true;
936 if (parent.restrict)
937 child.restrict = true;
938 if (parent.readonly)
939 child.readonly = true;
940 if (parent.writeonly)
941 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700942}
943
John Kessenichf2b7f332016-09-01 17:05:23 -0600944bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700945{
John Kessenich7b9fa252016-01-21 18:56:57 -0700946 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600947 // - struct members might inherit from a struct declaration
948 // (note that non-block structs don't explicitly inherit,
949 // only implicitly, meaning no decoration involved)
950 // - affect decorations on the struct members
951 // (note smooth does not, and expecting something like volatile
952 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700953 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600954 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700955}
956
John Kessenich140f3df2015-06-26 16:58:36 -0600957//
958// Implement the TGlslangToSpvTraverser class.
959//
960
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700961TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -0600962 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
963 : TIntermTraverser(true, false, true),
964 options(options),
965 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600966 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700967 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700968 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600969 glslangIntermediate(glslangIntermediate)
970{
971 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
972
973 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -0600974 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
975 glslangIntermediate->getVersion());
976
John Kessenich121853f2017-05-31 17:11:16 -0600977 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -0600978 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -0600979 builder.setSourceFile(glslangIntermediate->getSourceFile());
980
981 // Set the source shader's text. If for SPV version 1.0, include
982 // a preamble in comments stating the OpModuleProcessed instructions.
983 // Otherwise, emit those as actual instructions.
984 std::string text;
985 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
986 for (int p = 0; p < (int)processes.size(); ++p) {
987 if (glslangIntermediate->getSpv().spv < 0x00010100) {
988 text.append("// OpModuleProcessed ");
989 text.append(processes[p]);
990 text.append("\n");
991 } else
992 builder.addModuleProcessed(processes[p]);
993 }
994 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
995 text.append("#line 1\n");
996 text.append(glslangIntermediate->getSourceText());
997 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -0600998 }
John Kessenich140f3df2015-06-26 16:58:36 -0600999 stdBuiltins = builder.import("GLSL.std.450");
1000 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -06001001 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1002 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001003
1004 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001005 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1006 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001007 builder.addSourceExtension(it->c_str());
1008
1009 // Add the top-level modes for this shader.
1010
John Kessenich92187592016-02-01 13:45:25 -07001011 if (glslangIntermediate->getXfbMode()) {
1012 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001013 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001014 }
John Kessenich140f3df2015-06-26 16:58:36 -06001015
1016 unsigned int mode;
1017 switch (glslangIntermediate->getStage()) {
1018 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001019 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001020 break;
1021
steve-lunarge7412492017-03-23 11:56:07 -06001022 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001023 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001024 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001025
steve-lunarge7412492017-03-23 11:56:07 -06001026 glslang::TLayoutGeometry primitive;
1027
1028 if (glslangIntermediate->getStage() == EShLangTessControl) {
1029 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1030 primitive = glslangIntermediate->getOutputPrimitive();
1031 } else {
1032 primitive = glslangIntermediate->getInputPrimitive();
1033 }
1034
1035 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001036 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1037 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1038 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001039 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001040 }
John Kessenich4016e382016-07-15 11:53:56 -06001041 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001042 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1043
John Kesseniche6903322015-10-13 16:29:02 -06001044 switch (glslangIntermediate->getVertexSpacing()) {
1045 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1046 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1047 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001048 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001049 }
John Kessenich4016e382016-07-15 11:53:56 -06001050 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001051 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1052
1053 switch (glslangIntermediate->getVertexOrder()) {
1054 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1055 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001056 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001057 }
John Kessenich4016e382016-07-15 11:53:56 -06001058 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001059 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1060
1061 if (glslangIntermediate->getPointMode())
1062 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001063 break;
1064
1065 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001066 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001067 switch (glslangIntermediate->getInputPrimitive()) {
1068 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1069 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1070 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001071 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001072 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001073 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001074 }
John Kessenich4016e382016-07-15 11:53:56 -06001075 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001076 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001077
John Kessenich140f3df2015-06-26 16:58:36 -06001078 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1079
1080 switch (glslangIntermediate->getOutputPrimitive()) {
1081 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1082 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1083 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001084 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001085 }
John Kessenich4016e382016-07-15 11:53:56 -06001086 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001087 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1088 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1089 break;
1090
1091 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001092 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001093 if (glslangIntermediate->getPixelCenterInteger())
1094 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001095
John Kessenich140f3df2015-06-26 16:58:36 -06001096 if (glslangIntermediate->getOriginUpperLeft())
1097 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001098 else
1099 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001100
1101 if (glslangIntermediate->getEarlyFragmentTests())
1102 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1103
chaocc1204522017-06-30 17:14:30 -07001104 if (glslangIntermediate->getPostDepthCoverage()) {
1105 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1106 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1107 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1108 }
1109
John Kesseniche6903322015-10-13 16:29:02 -06001110 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001111 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1112 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001113 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001114 }
John Kessenich4016e382016-07-15 11:53:56 -06001115 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001116 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1117
1118 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1119 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001120 break;
1121
1122 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001123 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001124 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1125 glslangIntermediate->getLocalSize(1),
1126 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001127 break;
1128
1129 default:
1130 break;
1131 }
John Kessenich140f3df2015-06-26 16:58:36 -06001132}
1133
John Kessenichfca82622016-11-26 13:23:20 -07001134// Finish creating SPV, after the traversal is complete.
1135void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001136{
John Kessenich517fe7a2016-11-26 13:31:47 -07001137 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001138 builder.setBuildPoint(shaderEntry->getLastBlock());
1139 builder.leaveFunction();
1140 }
1141
John Kessenich7ba63412015-12-20 17:37:07 -07001142 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001143 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1144 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001145
qiningda397332016-03-09 19:54:03 -05001146 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001147}
1148
John Kessenichfca82622016-11-26 13:23:20 -07001149// Write the SPV into 'out'.
1150void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001151{
John Kessenichfca82622016-11-26 13:23:20 -07001152 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001153}
1154
1155//
1156// Implement the traversal functions.
1157//
1158// Return true from interior nodes to have the external traversal
1159// continue on to children. Return false if children were
1160// already processed.
1161//
1162
1163//
qining25262b32016-05-06 17:25:16 -04001164// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001165// - uniform/input reads
1166// - output writes
1167// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1168// - something simple that degenerates into the last bullet
1169//
1170void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1171{
qining75d1d802016-04-06 14:42:01 -04001172 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1173 if (symbol->getType().getQualifier().isSpecConstant())
1174 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1175
John Kessenich140f3df2015-06-26 16:58:36 -06001176 // getSymbolId() will set up all the IO decorations on the first call.
1177 // Formal function parameters were mapped during makeFunctions().
1178 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001179
1180 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1181 if (builder.isPointer(id)) {
1182 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001183 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1184 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1185 iOSet.insert(id);
1186 }
John Kessenich7ba63412015-12-20 17:37:07 -07001187 }
1188
1189 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001190 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001191 // Prepare to generate code for the access
1192
1193 // L-value chains will be computed left to right. We're on the symbol now,
1194 // which is the left-most part of the access chain, so now is "clear" time,
1195 // followed by setting the base.
1196 builder.clearAccessChain();
1197
1198 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001199 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001200 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001201 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001202 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001203 // These are also pure R-values.
1204 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001205 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001206 builder.setAccessChainRValue(id);
1207 else
1208 builder.setAccessChainLValue(id);
1209 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001210
1211 // Process linkage-only nodes for any special additional interface work.
1212 if (linkageOnly) {
1213 if (glslangIntermediate->getHlslFunctionality1()) {
1214 // Map implicit counter buffers to their originating buffers, which should have been
1215 // seen by now, given earlier pruning of unused counters, and preservation of order
1216 // of declaration.
1217 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1218 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1219 // Save possible originating buffers for counter buffers, keyed by
1220 // making the potential counter-buffer name.
1221 std::string keyName = symbol->getName().c_str();
1222 keyName = glslangIntermediate->addCounterBufferName(keyName);
1223 counterOriginator[keyName] = symbol;
1224 } else {
1225 // Handle a counter buffer, by finding the saved originating buffer.
1226 std::string keyName = symbol->getName().c_str();
1227 auto it = counterOriginator.find(keyName);
1228 if (it != counterOriginator.end()) {
1229 id = getSymbolId(it->second);
1230 if (id != spv::NoResult) {
1231 spv::Id counterId = getSymbolId(symbol);
1232 if (counterId != spv::NoResult)
1233 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
1234 }
1235 }
1236 }
1237 }
1238 }
1239 }
John Kessenich140f3df2015-06-26 16:58:36 -06001240}
1241
1242bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1243{
John Kesseniche485c7a2017-05-31 18:50:53 -06001244 builder.setLine(node->getLoc().line);
1245
qining40887662016-04-03 22:20:42 -04001246 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1247 if (node->getType().getQualifier().isSpecConstant())
1248 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1249
John Kessenich140f3df2015-06-26 16:58:36 -06001250 // First, handle special cases
1251 switch (node->getOp()) {
1252 case glslang::EOpAssign:
1253 case glslang::EOpAddAssign:
1254 case glslang::EOpSubAssign:
1255 case glslang::EOpMulAssign:
1256 case glslang::EOpVectorTimesMatrixAssign:
1257 case glslang::EOpVectorTimesScalarAssign:
1258 case glslang::EOpMatrixTimesScalarAssign:
1259 case glslang::EOpMatrixTimesMatrixAssign:
1260 case glslang::EOpDivAssign:
1261 case glslang::EOpModAssign:
1262 case glslang::EOpAndAssign:
1263 case glslang::EOpInclusiveOrAssign:
1264 case glslang::EOpExclusiveOrAssign:
1265 case glslang::EOpLeftShiftAssign:
1266 case glslang::EOpRightShiftAssign:
1267 // A bin-op assign "a += b" means the same thing as "a = a + b"
1268 // where a is evaluated before b. For a simple assignment, GLSL
1269 // says to evaluate the left before the right. So, always, left
1270 // node then right node.
1271 {
1272 // get the left l-value, save it away
1273 builder.clearAccessChain();
1274 node->getLeft()->traverse(this);
1275 spv::Builder::AccessChain lValue = builder.getAccessChain();
1276
1277 // evaluate the right
1278 builder.clearAccessChain();
1279 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001280 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001281
1282 if (node->getOp() != glslang::EOpAssign) {
1283 // the left is also an r-value
1284 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001285 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001286
1287 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001288 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
1289 TranslateNoContractionDecoration(node->getType().getQualifier()) };
1290 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001291 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1292 node->getType().getBasicType());
1293
1294 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001295 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001296 }
1297
1298 // store the result
1299 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001300 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001301
1302 // assignments are expressions having an rValue after they are evaluated...
1303 builder.clearAccessChain();
1304 builder.setAccessChainRValue(rValue);
1305 }
1306 return false;
1307 case glslang::EOpIndexDirect:
1308 case glslang::EOpIndexDirectStruct:
1309 {
1310 // Get the left part of the access chain.
1311 node->getLeft()->traverse(this);
1312
1313 // Add the next element in the chain
1314
David Netoa901ffe2016-06-08 14:11:40 +01001315 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001316 if (! node->getLeft()->getType().isArray() &&
1317 node->getLeft()->getType().isVector() &&
1318 node->getOp() == glslang::EOpIndexDirect) {
1319 // This is essentially a hard-coded vector swizzle of size 1,
1320 // so short circuit the access-chain stuff with a swizzle.
1321 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001322 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001323 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001324 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001325 int spvIndex = glslangIndex;
1326 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1327 node->getOp() == glslang::EOpIndexDirectStruct)
1328 {
1329 // This may be, e.g., an anonymous block-member selection, which generally need
1330 // index remapping due to hidden members in anonymous blocks.
1331 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1332 assert(remapper.size() > 0);
1333 spvIndex = remapper[glslangIndex];
1334 }
John Kessenichebb50532016-05-16 19:22:05 -06001335
David Netoa901ffe2016-06-08 14:11:40 +01001336 // normal case for indexing array or structure or block
1337 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1338
1339 // Add capabilities here for accessing PointSize and clip/cull distance.
1340 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001341 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001342 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001343 }
1344 }
1345 return false;
1346 case glslang::EOpIndexIndirect:
1347 {
1348 // Structure or array or vector indirection.
1349 // Will use native SPIR-V access-chain for struct and array indirection;
1350 // matrices are arrays of vectors, so will also work for a matrix.
1351 // Will use the access chain's 'component' for variable index into a vector.
1352
1353 // This adapter is building access chains left to right.
1354 // Set up the access chain to the left.
1355 node->getLeft()->traverse(this);
1356
1357 // save it so that computing the right side doesn't trash it
1358 spv::Builder::AccessChain partial = builder.getAccessChain();
1359
1360 // compute the next index in the chain
1361 builder.clearAccessChain();
1362 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001363 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001364
1365 // restore the saved access chain
1366 builder.setAccessChain(partial);
1367
1368 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001369 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001370 else
John Kessenichfa668da2015-09-13 14:46:30 -06001371 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001372 }
1373 return false;
1374 case glslang::EOpVectorSwizzle:
1375 {
1376 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001377 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001378 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001379 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001380 }
1381 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001382 case glslang::EOpMatrixSwizzle:
1383 logger->missingFunctionality("matrix swizzle");
1384 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001385 case glslang::EOpLogicalOr:
1386 case glslang::EOpLogicalAnd:
1387 {
1388
1389 // These may require short circuiting, but can sometimes be done as straight
1390 // binary operations. The right operand must be short circuited if it has
1391 // side effects, and should probably be if it is complex.
1392 if (isTrivial(node->getRight()->getAsTyped()))
1393 break; // handle below as a normal binary operation
1394 // otherwise, we need to do dynamic short circuiting on the right operand
1395 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1396 builder.clearAccessChain();
1397 builder.setAccessChainRValue(result);
1398 }
1399 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001400 default:
1401 break;
1402 }
1403
1404 // Assume generic binary op...
1405
John Kessenich32cfd492016-02-02 12:37:46 -07001406 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001407 builder.clearAccessChain();
1408 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001409 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001410
John Kessenich32cfd492016-02-02 12:37:46 -07001411 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001412 builder.clearAccessChain();
1413 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001414 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001415
John Kessenich32cfd492016-02-02 12:37:46 -07001416 // get result
John Kessenichead86222018-03-28 18:01:20 -06001417 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
1418 TranslateNoContractionDecoration(node->getType().getQualifier()) };
1419 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001420 convertGlslangToSpvType(node->getType()), left, right,
1421 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001422
John Kessenich50e57562015-12-21 21:21:11 -07001423 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001424 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001425 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001426 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001427 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001428 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001429 return false;
1430 }
John Kessenich140f3df2015-06-26 16:58:36 -06001431}
1432
1433bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1434{
John Kesseniche485c7a2017-05-31 18:50:53 -06001435 builder.setLine(node->getLoc().line);
1436
qining40887662016-04-03 22:20:42 -04001437 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1438 if (node->getType().getQualifier().isSpecConstant())
1439 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1440
John Kessenichfc51d282015-08-19 13:34:18 -06001441 spv::Id result = spv::NoResult;
1442
1443 // try texturing first
1444 result = createImageTextureFunctionCall(node);
1445 if (result != spv::NoResult) {
1446 builder.clearAccessChain();
1447 builder.setAccessChainRValue(result);
1448
1449 return false; // done with this node
1450 }
1451
1452 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001453
1454 if (node->getOp() == glslang::EOpArrayLength) {
1455 // Quite special; won't want to evaluate the operand.
1456
1457 // Normal .length() would have been constant folded by the front-end.
1458 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001459 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001460
John Kessenichc9a80832015-09-12 12:17:44 -06001461 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1462 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001463 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1464 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001465
1466 builder.clearAccessChain();
1467 builder.setAccessChainRValue(length);
1468
1469 return false;
1470 }
1471
John Kessenichfc51d282015-08-19 13:34:18 -06001472 // Start by evaluating the operand
1473
John Kessenich8c8505c2016-07-26 12:50:38 -06001474 // Does it need a swizzle inversion? If so, evaluation is inverted;
1475 // operate first on the swizzle base, then apply the swizzle.
1476 spv::Id invertedType = spv::NoType;
1477 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1478 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1479 invertedType = getInvertedSwizzleType(*node->getOperand());
1480
John Kessenich140f3df2015-06-26 16:58:36 -06001481 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001482 if (invertedType != spv::NoType)
1483 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1484 else
1485 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001486
Rex Xufc618912015-09-09 16:42:49 +08001487 spv::Id operand = spv::NoResult;
1488
1489 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1490 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001491 node->getOp() == glslang::EOpAtomicCounter ||
1492 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001493 operand = builder.accessChainGetLValue(); // Special case l-value operands
1494 else
John Kessenich32cfd492016-02-02 12:37:46 -07001495 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001496
John Kessenichead86222018-03-28 18:01:20 -06001497 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
1498 TranslateNoContractionDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001499
1500 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001501 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001502 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001503
1504 // if not, then possibly an operation
1505 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001506 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001507
1508 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001509 if (invertedType)
John Kessenichead86222018-03-28 18:01:20 -06001510 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich8c8505c2016-07-26 12:50:38 -06001511
John Kessenich140f3df2015-06-26 16:58:36 -06001512 builder.clearAccessChain();
1513 builder.setAccessChainRValue(result);
1514
1515 return false; // done with this node
1516 }
1517
1518 // it must be a special case, check...
1519 switch (node->getOp()) {
1520 case glslang::EOpPostIncrement:
1521 case glslang::EOpPostDecrement:
1522 case glslang::EOpPreIncrement:
1523 case glslang::EOpPreDecrement:
1524 {
1525 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001526 spv::Id one = 0;
1527 if (node->getBasicType() == glslang::EbtFloat)
1528 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001529 else if (node->getBasicType() == glslang::EbtDouble)
1530 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001531 else if (node->getBasicType() == glslang::EbtFloat16)
1532 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001533 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1534 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001535 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1536 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001537 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1538 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001539 else
1540 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001541 glslang::TOperator op;
1542 if (node->getOp() == glslang::EOpPreIncrement ||
1543 node->getOp() == glslang::EOpPostIncrement)
1544 op = glslang::EOpAdd;
1545 else
1546 op = glslang::EOpSub;
1547
John Kessenichead86222018-03-28 18:01:20 -06001548 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001549 convertGlslangToSpvType(node->getType()), operand, one,
1550 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001551 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001552
1553 // The result of operation is always stored, but conditionally the
1554 // consumed result. The consumed result is always an r-value.
1555 builder.accessChainStore(result);
1556 builder.clearAccessChain();
1557 if (node->getOp() == glslang::EOpPreIncrement ||
1558 node->getOp() == glslang::EOpPreDecrement)
1559 builder.setAccessChainRValue(result);
1560 else
1561 builder.setAccessChainRValue(operand);
1562 }
1563
1564 return false;
1565
1566 case glslang::EOpEmitStreamVertex:
1567 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1568 return false;
1569 case glslang::EOpEndStreamPrimitive:
1570 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1571 return false;
1572
1573 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001574 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001575 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001576 }
John Kessenich140f3df2015-06-26 16:58:36 -06001577}
1578
1579bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1580{
qining27e04a02016-04-14 16:40:20 -04001581 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1582 if (node->getType().getQualifier().isSpecConstant())
1583 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1584
John Kessenichfc51d282015-08-19 13:34:18 -06001585 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001586 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1587 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001588
1589 // try texturing
1590 result = createImageTextureFunctionCall(node);
1591 if (result != spv::NoResult) {
1592 builder.clearAccessChain();
1593 builder.setAccessChainRValue(result);
1594
1595 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001596#ifdef AMD_EXTENSIONS
1597 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1598#else
John Kessenich56bab042015-09-16 10:54:31 -06001599 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001600#endif
Rex Xufc618912015-09-09 16:42:49 +08001601 // "imageStore" is a special case, which has no result
1602 return false;
1603 }
John Kessenichfc51d282015-08-19 13:34:18 -06001604
John Kessenich140f3df2015-06-26 16:58:36 -06001605 glslang::TOperator binOp = glslang::EOpNull;
1606 bool reduceComparison = true;
1607 bool isMatrix = false;
1608 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001609 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001610
1611 assert(node->getOp());
1612
John Kessenichf6640762016-08-01 19:44:00 -06001613 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001614
1615 switch (node->getOp()) {
1616 case glslang::EOpSequence:
1617 {
1618 if (preVisit)
1619 ++sequenceDepth;
1620 else
1621 --sequenceDepth;
1622
1623 if (sequenceDepth == 1) {
1624 // If this is the parent node of all the functions, we want to see them
1625 // early, so all call points have actual SPIR-V functions to reference.
1626 // In all cases, still let the traverser visit the children for us.
1627 makeFunctions(node->getAsAggregate()->getSequence());
1628
John Kessenich6fccb3c2016-09-19 16:01:41 -06001629 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001630 // anything else gets there, so visit out of order, doing them all now.
1631 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1632
John Kessenich6a60c2f2016-12-08 21:01:59 -07001633 // 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 -06001634 // so do them manually.
1635 visitFunctions(node->getAsAggregate()->getSequence());
1636
1637 return false;
1638 }
1639
1640 return true;
1641 }
1642 case glslang::EOpLinkerObjects:
1643 {
1644 if (visit == glslang::EvPreVisit)
1645 linkageOnly = true;
1646 else
1647 linkageOnly = false;
1648
1649 return true;
1650 }
1651 case glslang::EOpComma:
1652 {
1653 // processing from left to right naturally leaves the right-most
1654 // lying around in the access chain
1655 glslang::TIntermSequence& glslangOperands = node->getSequence();
1656 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1657 glslangOperands[i]->traverse(this);
1658
1659 return false;
1660 }
1661 case glslang::EOpFunction:
1662 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001663 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001664 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001665 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001666 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001667 } else {
1668 handleFunctionEntry(node);
1669 }
1670 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001671 if (inEntryPoint)
1672 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001673 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001674 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001675 }
1676
1677 return true;
1678 case glslang::EOpParameters:
1679 // Parameters will have been consumed by EOpFunction processing, but not
1680 // the body, so we still visited the function node's children, making this
1681 // child redundant.
1682 return false;
1683 case glslang::EOpFunctionCall:
1684 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001685 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001686 if (node->isUserDefined())
1687 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001688 // 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 -07001689 if (result) {
1690 builder.clearAccessChain();
1691 builder.setAccessChainRValue(result);
1692 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001693 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001694
1695 return false;
1696 }
1697 case glslang::EOpConstructMat2x2:
1698 case glslang::EOpConstructMat2x3:
1699 case glslang::EOpConstructMat2x4:
1700 case glslang::EOpConstructMat3x2:
1701 case glslang::EOpConstructMat3x3:
1702 case glslang::EOpConstructMat3x4:
1703 case glslang::EOpConstructMat4x2:
1704 case glslang::EOpConstructMat4x3:
1705 case glslang::EOpConstructMat4x4:
1706 case glslang::EOpConstructDMat2x2:
1707 case glslang::EOpConstructDMat2x3:
1708 case glslang::EOpConstructDMat2x4:
1709 case glslang::EOpConstructDMat3x2:
1710 case glslang::EOpConstructDMat3x3:
1711 case glslang::EOpConstructDMat3x4:
1712 case glslang::EOpConstructDMat4x2:
1713 case glslang::EOpConstructDMat4x3:
1714 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001715 case glslang::EOpConstructIMat2x2:
1716 case glslang::EOpConstructIMat2x3:
1717 case glslang::EOpConstructIMat2x4:
1718 case glslang::EOpConstructIMat3x2:
1719 case glslang::EOpConstructIMat3x3:
1720 case glslang::EOpConstructIMat3x4:
1721 case glslang::EOpConstructIMat4x2:
1722 case glslang::EOpConstructIMat4x3:
1723 case glslang::EOpConstructIMat4x4:
1724 case glslang::EOpConstructUMat2x2:
1725 case glslang::EOpConstructUMat2x3:
1726 case glslang::EOpConstructUMat2x4:
1727 case glslang::EOpConstructUMat3x2:
1728 case glslang::EOpConstructUMat3x3:
1729 case glslang::EOpConstructUMat3x4:
1730 case glslang::EOpConstructUMat4x2:
1731 case glslang::EOpConstructUMat4x3:
1732 case glslang::EOpConstructUMat4x4:
1733 case glslang::EOpConstructBMat2x2:
1734 case glslang::EOpConstructBMat2x3:
1735 case glslang::EOpConstructBMat2x4:
1736 case glslang::EOpConstructBMat3x2:
1737 case glslang::EOpConstructBMat3x3:
1738 case glslang::EOpConstructBMat3x4:
1739 case glslang::EOpConstructBMat4x2:
1740 case glslang::EOpConstructBMat4x3:
1741 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001742 case glslang::EOpConstructF16Mat2x2:
1743 case glslang::EOpConstructF16Mat2x3:
1744 case glslang::EOpConstructF16Mat2x4:
1745 case glslang::EOpConstructF16Mat3x2:
1746 case glslang::EOpConstructF16Mat3x3:
1747 case glslang::EOpConstructF16Mat3x4:
1748 case glslang::EOpConstructF16Mat4x2:
1749 case glslang::EOpConstructF16Mat4x3:
1750 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06001751 isMatrix = true;
1752 // fall through
1753 case glslang::EOpConstructFloat:
1754 case glslang::EOpConstructVec2:
1755 case glslang::EOpConstructVec3:
1756 case glslang::EOpConstructVec4:
1757 case glslang::EOpConstructDouble:
1758 case glslang::EOpConstructDVec2:
1759 case glslang::EOpConstructDVec3:
1760 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001761 case glslang::EOpConstructFloat16:
1762 case glslang::EOpConstructF16Vec2:
1763 case glslang::EOpConstructF16Vec3:
1764 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001765 case glslang::EOpConstructBool:
1766 case glslang::EOpConstructBVec2:
1767 case glslang::EOpConstructBVec3:
1768 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07001769 case glslang::EOpConstructInt8:
1770 case glslang::EOpConstructI8Vec2:
1771 case glslang::EOpConstructI8Vec3:
1772 case glslang::EOpConstructI8Vec4:
1773 case glslang::EOpConstructUint8:
1774 case glslang::EOpConstructU8Vec2:
1775 case glslang::EOpConstructU8Vec3:
1776 case glslang::EOpConstructU8Vec4:
1777 case glslang::EOpConstructInt16:
1778 case glslang::EOpConstructI16Vec2:
1779 case glslang::EOpConstructI16Vec3:
1780 case glslang::EOpConstructI16Vec4:
1781 case glslang::EOpConstructUint16:
1782 case glslang::EOpConstructU16Vec2:
1783 case glslang::EOpConstructU16Vec3:
1784 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001785 case glslang::EOpConstructInt:
1786 case glslang::EOpConstructIVec2:
1787 case glslang::EOpConstructIVec3:
1788 case glslang::EOpConstructIVec4:
1789 case glslang::EOpConstructUint:
1790 case glslang::EOpConstructUVec2:
1791 case glslang::EOpConstructUVec3:
1792 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001793 case glslang::EOpConstructInt64:
1794 case glslang::EOpConstructI64Vec2:
1795 case glslang::EOpConstructI64Vec3:
1796 case glslang::EOpConstructI64Vec4:
1797 case glslang::EOpConstructUint64:
1798 case glslang::EOpConstructU64Vec2:
1799 case glslang::EOpConstructU64Vec3:
1800 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001801 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001802 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001803 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001804 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001805 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001806 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001807 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001808 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001809 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001810 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001811 std::vector<spv::Id> constituents;
1812 for (int c = 0; c < (int)arguments.size(); ++c)
1813 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001814 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001815 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001816 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001817 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001818 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001819
1820 builder.clearAccessChain();
1821 builder.setAccessChainRValue(constructed);
1822
1823 return false;
1824 }
1825
1826 // These six are component-wise compares with component-wise results.
1827 // Forward on to createBinaryOperation(), requesting a vector result.
1828 case glslang::EOpLessThan:
1829 case glslang::EOpGreaterThan:
1830 case glslang::EOpLessThanEqual:
1831 case glslang::EOpGreaterThanEqual:
1832 case glslang::EOpVectorEqual:
1833 case glslang::EOpVectorNotEqual:
1834 {
1835 // Map the operation to a binary
1836 binOp = node->getOp();
1837 reduceComparison = false;
1838 switch (node->getOp()) {
1839 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1840 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1841 default: binOp = node->getOp(); break;
1842 }
1843
1844 break;
1845 }
1846 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001847 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001848 binOp = glslang::EOpMul;
1849 break;
1850 case glslang::EOpOuterProduct:
1851 // two vectors multiplied to make a matrix
1852 binOp = glslang::EOpOuterProduct;
1853 break;
1854 case glslang::EOpDot:
1855 {
qining25262b32016-05-06 17:25:16 -04001856 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001857 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001858 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001859 binOp = glslang::EOpMul;
1860 break;
1861 }
1862 case glslang::EOpMod:
1863 // when an aggregate, this is the floating-point mod built-in function,
1864 // which can be emitted by the one in createBinaryOperation()
1865 binOp = glslang::EOpMod;
1866 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001867 case glslang::EOpEmitVertex:
1868 case glslang::EOpEndPrimitive:
1869 case glslang::EOpBarrier:
1870 case glslang::EOpMemoryBarrier:
1871 case glslang::EOpMemoryBarrierAtomicCounter:
1872 case glslang::EOpMemoryBarrierBuffer:
1873 case glslang::EOpMemoryBarrierImage:
1874 case glslang::EOpMemoryBarrierShared:
1875 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07001876 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001877 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07001878 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001879 case glslang::EOpWorkgroupMemoryBarrier:
1880 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07001881 case glslang::EOpSubgroupBarrier:
1882 case glslang::EOpSubgroupMemoryBarrier:
1883 case glslang::EOpSubgroupMemoryBarrierBuffer:
1884 case glslang::EOpSubgroupMemoryBarrierImage:
1885 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06001886 noReturnValue = true;
1887 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1888 break;
1889
John Kessenich426394d2015-07-23 10:22:48 -06001890 case glslang::EOpAtomicAdd:
1891 case glslang::EOpAtomicMin:
1892 case glslang::EOpAtomicMax:
1893 case glslang::EOpAtomicAnd:
1894 case glslang::EOpAtomicOr:
1895 case glslang::EOpAtomicXor:
1896 case glslang::EOpAtomicExchange:
1897 case glslang::EOpAtomicCompSwap:
1898 atomic = true;
1899 break;
1900
John Kessenich0d0c6d32017-07-23 16:08:26 -06001901 case glslang::EOpAtomicCounterAdd:
1902 case glslang::EOpAtomicCounterSubtract:
1903 case glslang::EOpAtomicCounterMin:
1904 case glslang::EOpAtomicCounterMax:
1905 case glslang::EOpAtomicCounterAnd:
1906 case glslang::EOpAtomicCounterOr:
1907 case glslang::EOpAtomicCounterXor:
1908 case glslang::EOpAtomicCounterExchange:
1909 case glslang::EOpAtomicCounterCompSwap:
1910 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1911 builder.addCapability(spv::CapabilityAtomicStorageOps);
1912 atomic = true;
1913 break;
1914
John Kessenich140f3df2015-06-26 16:58:36 -06001915 default:
1916 break;
1917 }
1918
1919 //
1920 // See if it maps to a regular operation.
1921 //
John Kessenich140f3df2015-06-26 16:58:36 -06001922 if (binOp != glslang::EOpNull) {
1923 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1924 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1925 assert(left && right);
1926
1927 builder.clearAccessChain();
1928 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001929 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001930
1931 builder.clearAccessChain();
1932 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001933 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001934
John Kesseniche485c7a2017-05-31 18:50:53 -06001935 builder.setLine(node->getLoc().line);
John Kessenichead86222018-03-28 18:01:20 -06001936 OpDecorations decorations = { precision,
1937 TranslateNoContractionDecoration(node->getType().getQualifier()) };
1938 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06001939 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001940 left->getType().getBasicType(), reduceComparison);
1941
1942 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001943 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001944 builder.clearAccessChain();
1945 builder.setAccessChainRValue(result);
1946
1947 return false;
1948 }
1949
John Kessenich426394d2015-07-23 10:22:48 -06001950 //
1951 // Create the list of operands.
1952 //
John Kessenich140f3df2015-06-26 16:58:36 -06001953 glslang::TIntermSequence& glslangOperands = node->getSequence();
1954 std::vector<spv::Id> operands;
1955 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001956 // special case l-value operands; there are just a few
1957 bool lvalue = false;
1958 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001959 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001960 case glslang::EOpModf:
1961 if (arg == 1)
1962 lvalue = true;
1963 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001964 case glslang::EOpInterpolateAtSample:
1965 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001966#ifdef AMD_EXTENSIONS
1967 case glslang::EOpInterpolateAtVertex:
1968#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001969 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001970 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001971
1972 // Does it need a swizzle inversion? If so, evaluation is inverted;
1973 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001974 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001975 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1976 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1977 }
Rex Xu7a26c172015-12-08 17:12:09 +08001978 break;
Rex Xud4782c12015-09-06 16:30:11 +08001979 case glslang::EOpAtomicAdd:
1980 case glslang::EOpAtomicMin:
1981 case glslang::EOpAtomicMax:
1982 case glslang::EOpAtomicAnd:
1983 case glslang::EOpAtomicOr:
1984 case glslang::EOpAtomicXor:
1985 case glslang::EOpAtomicExchange:
1986 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06001987 case glslang::EOpAtomicCounterAdd:
1988 case glslang::EOpAtomicCounterSubtract:
1989 case glslang::EOpAtomicCounterMin:
1990 case glslang::EOpAtomicCounterMax:
1991 case glslang::EOpAtomicCounterAnd:
1992 case glslang::EOpAtomicCounterOr:
1993 case glslang::EOpAtomicCounterXor:
1994 case glslang::EOpAtomicCounterExchange:
1995 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08001996 if (arg == 0)
1997 lvalue = true;
1998 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001999 case glslang::EOpAddCarry:
2000 case glslang::EOpSubBorrow:
2001 if (arg == 2)
2002 lvalue = true;
2003 break;
2004 case glslang::EOpUMulExtended:
2005 case glslang::EOpIMulExtended:
2006 if (arg >= 2)
2007 lvalue = true;
2008 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002009 default:
2010 break;
2011 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002012 builder.clearAccessChain();
2013 if (invertedType != spv::NoType && arg == 0)
2014 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2015 else
2016 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002017 if (lvalue)
2018 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002019 else {
2020 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07002021 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002022 }
John Kessenich140f3df2015-06-26 16:58:36 -06002023 }
John Kessenich426394d2015-07-23 10:22:48 -06002024
John Kesseniche485c7a2017-05-31 18:50:53 -06002025 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06002026 if (atomic) {
2027 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002028 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002029 } else {
2030 // Pass through to generic operations.
2031 switch (glslangOperands.size()) {
2032 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002033 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002034 break;
2035 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002036 {
2037 OpDecorations decorations = { precision,
2038 TranslateNoContractionDecoration(node->getType().getQualifier()) };
2039 result = createUnaryOperation(
2040 node->getOp(), decorations,
2041 resultType(), operands.front(),
2042 glslangOperands[0]->getAsTyped()->getBasicType());
2043 }
John Kessenich426394d2015-07-23 10:22:48 -06002044 break;
2045 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002046 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002047 break;
2048 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002049 if (invertedType)
2050 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002051 }
2052
2053 if (noReturnValue)
2054 return false;
2055
2056 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002057 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002058 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002059 } else {
2060 builder.clearAccessChain();
2061 builder.setAccessChainRValue(result);
2062 return false;
2063 }
2064}
2065
John Kessenich433e9ff2017-01-26 20:31:11 -07002066// This path handles both if-then-else and ?:
2067// The if-then-else has a node type of void, while
2068// ?: has either a void or a non-void node type
2069//
2070// Leaving the result, when not void:
2071// GLSL only has r-values as the result of a :?, but
2072// if we have an l-value, that can be more efficient if it will
2073// become the base of a complex r-value expression, because the
2074// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002075bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2076{
John Kessenich4bee5312018-02-20 21:29:05 -07002077 // See if it simple and safe, or required, to execute both sides.
2078 // Crucially, side effects must be either semantically required or avoided,
2079 // and there are performance trade-offs.
2080 // Return true if required or a good idea (and safe) to execute both sides,
2081 // false otherwise.
2082 const auto bothSidesPolicy = [&]() -> bool {
2083 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002084 if (node->getTrueBlock() == nullptr ||
2085 node->getFalseBlock() == nullptr)
2086 return false;
2087
John Kessenich4bee5312018-02-20 21:29:05 -07002088 // required? (unless we write additional code to look for side effects
2089 // and make performance trade-offs if none are present)
2090 if (!node->getShortCircuit())
2091 return true;
2092
2093 // if not required to execute both, decide based on performance/practicality...
2094
2095 // see if OpSelect can handle it
2096 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2097 node->getBasicType() == glslang::EbtVoid)
2098 return false;
2099
John Kessenich433e9ff2017-01-26 20:31:11 -07002100 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2101 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2102
2103 // return true if a single operand to ? : is okay for OpSelect
2104 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002105 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002106 };
2107
2108 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2109 operandOkay(node->getFalseBlock()->getAsTyped());
2110 };
2111
John Kessenich4bee5312018-02-20 21:29:05 -07002112 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2113 // emit the condition before doing anything with selection
2114 node->getCondition()->traverse(this);
2115 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2116
2117 // Find a way of executing both sides and selecting the right result.
2118 const auto executeBothSides = [&]() -> void {
2119 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002120 node->getTrueBlock()->traverse(this);
2121 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2122 node->getFalseBlock()->traverse(this);
2123 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2124
John Kesseniche485c7a2017-05-31 18:50:53 -06002125 builder.setLine(node->getLoc().line);
2126
John Kessenich4bee5312018-02-20 21:29:05 -07002127 // done if void
2128 if (node->getBasicType() == glslang::EbtVoid)
2129 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002130
John Kessenich4bee5312018-02-20 21:29:05 -07002131 // emit code to select between trueValue and falseValue
2132
2133 // see if OpSelect can handle it
2134 if (node->getType().isScalar() || node->getType().isVector()) {
2135 // Emit OpSelect for this selection.
2136
2137 // smear condition to vector, if necessary (AST is always scalar)
2138 if (builder.isVector(trueValue))
2139 condition = builder.smearScalar(spv::NoPrecision, condition,
2140 builder.makeVectorType(builder.makeBoolType(),
2141 builder.getNumComponents(trueValue)));
2142
2143 // OpSelect
2144 result = builder.createTriOp(spv::OpSelect,
2145 convertGlslangToSpvType(node->getType()), condition,
2146 trueValue, falseValue);
2147
2148 builder.clearAccessChain();
2149 builder.setAccessChainRValue(result);
2150 } else {
2151 // We need control flow to select the result.
2152 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2153 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2154
2155 // Selection control:
2156 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2157
2158 // make an "if" based on the value created by the condition
2159 spv::Builder::If ifBuilder(condition, control, builder);
2160
2161 // emit the "then" statement
2162 builder.createStore(trueValue, result);
2163 ifBuilder.makeBeginElse();
2164 // emit the "else" statement
2165 builder.createStore(falseValue, result);
2166
2167 // finish off the control flow
2168 ifBuilder.makeEndIf();
2169
2170 builder.clearAccessChain();
2171 builder.setAccessChainLValue(result);
2172 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002173 };
2174
John Kessenich4bee5312018-02-20 21:29:05 -07002175 // Execute the one side needed, as per the condition
2176 const auto executeOneSide = [&]() {
2177 // Always emit control flow.
2178 if (node->getBasicType() != glslang::EbtVoid)
2179 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002180
John Kessenich4bee5312018-02-20 21:29:05 -07002181 // Selection control:
2182 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2183
2184 // make an "if" based on the value created by the condition
2185 spv::Builder::If ifBuilder(condition, control, builder);
2186
2187 // emit the "then" statement
2188 if (node->getTrueBlock() != nullptr) {
2189 node->getTrueBlock()->traverse(this);
2190 if (result != spv::NoResult)
2191 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2192 }
2193
2194 if (node->getFalseBlock() != nullptr) {
2195 ifBuilder.makeBeginElse();
2196 // emit the "else" statement
2197 node->getFalseBlock()->traverse(this);
2198 if (result != spv::NoResult)
2199 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2200 }
2201
2202 // finish off the control flow
2203 ifBuilder.makeEndIf();
2204
2205 if (result != spv::NoResult) {
2206 builder.clearAccessChain();
2207 builder.setAccessChainLValue(result);
2208 }
2209 };
2210
2211 // Try for OpSelect (or a requirement to execute both sides)
2212 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002213 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2214 if (node->getType().getQualifier().isSpecConstant())
2215 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002216 executeBothSides();
2217 } else
2218 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002219
2220 return false;
2221}
2222
2223bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2224{
2225 // emit and get the condition before doing anything with switch
2226 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002227 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002228
Rex Xu57e65922017-07-04 23:23:40 +08002229 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002230 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002231
John Kessenich140f3df2015-06-26 16:58:36 -06002232 // browse the children to sort out code segments
2233 int defaultSegment = -1;
2234 std::vector<TIntermNode*> codeSegments;
2235 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2236 std::vector<int> caseValues;
2237 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2238 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2239 TIntermNode* child = *c;
2240 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002241 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002242 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002243 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002244 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2245 } else
2246 codeSegments.push_back(child);
2247 }
2248
qining25262b32016-05-06 17:25:16 -04002249 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002250 // statements between the last case and the end of the switch statement
2251 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2252 (int)codeSegments.size() == defaultSegment)
2253 codeSegments.push_back(nullptr);
2254
2255 // make the switch statement
2256 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002257 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002258
2259 // emit all the code in the segments
2260 breakForLoop.push(false);
2261 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2262 builder.nextSwitchSegment(segmentBlocks, s);
2263 if (codeSegments[s])
2264 codeSegments[s]->traverse(this);
2265 else
2266 builder.addSwitchBreak();
2267 }
2268 breakForLoop.pop();
2269
2270 builder.endSwitch(segmentBlocks);
2271
2272 return false;
2273}
2274
2275void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2276{
2277 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002278 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002279
2280 builder.clearAccessChain();
2281 builder.setAccessChainRValue(constant);
2282}
2283
2284bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2285{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002286 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002287 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002288
2289 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002290 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2291 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002292
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002293 // Spec requires back edges to target header blocks, and every header block
2294 // must dominate its merge block. Make a header block first to ensure these
2295 // conditions are met. By definition, it will contain OpLoopMerge, followed
2296 // by a block-ending branch. But we don't want to put any other body/test
2297 // instructions in it, since the body/test may have arbitrary instructions,
2298 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002299 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002300 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002301 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002302 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002303 spv::Block& test = builder.makeNewBlock();
2304 builder.createBranch(&test);
2305
2306 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002307 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002308 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002309 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2310
2311 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002312 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002313 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002314 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002315 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002316 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002317
2318 builder.setBuildPoint(&blocks.continue_target);
2319 if (node->getTerminal())
2320 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002321 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002322 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002323 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002324 builder.createBranch(&blocks.body);
2325
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002326 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002327 builder.setBuildPoint(&blocks.body);
2328 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002329 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002330 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002331 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002332
2333 builder.setBuildPoint(&blocks.continue_target);
2334 if (node->getTerminal())
2335 node->getTerminal()->traverse(this);
2336 if (node->getTest()) {
2337 node->getTest()->traverse(this);
2338 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002339 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002340 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002341 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002342 // TODO: unless there was a break/return/discard instruction
2343 // somewhere in the body, this is an infinite loop, so we should
2344 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002345 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002346 }
John Kessenich140f3df2015-06-26 16:58:36 -06002347 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002348 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002349 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002350 return false;
2351}
2352
2353bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2354{
2355 if (node->getExpression())
2356 node->getExpression()->traverse(this);
2357
John Kesseniche485c7a2017-05-31 18:50:53 -06002358 builder.setLine(node->getLoc().line);
2359
John Kessenich140f3df2015-06-26 16:58:36 -06002360 switch (node->getFlowOp()) {
2361 case glslang::EOpKill:
2362 builder.makeDiscard();
2363 break;
2364 case glslang::EOpBreak:
2365 if (breakForLoop.top())
2366 builder.createLoopExit();
2367 else
2368 builder.addSwitchBreak();
2369 break;
2370 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002371 builder.createLoopContinue();
2372 break;
2373 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002374 if (node->getExpression()) {
2375 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2376 spv::Id returnId = accessChainLoad(glslangReturnType);
2377 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2378 builder.clearAccessChain();
2379 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2380 builder.setAccessChainLValue(copyId);
2381 multiTypeStore(glslangReturnType, returnId);
2382 returnId = builder.createLoad(copyId);
2383 }
2384 builder.makeReturn(false, returnId);
2385 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002386 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002387
2388 builder.clearAccessChain();
2389 break;
2390
2391 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002392 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002393 break;
2394 }
2395
2396 return false;
2397}
2398
2399spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2400{
qining25262b32016-05-06 17:25:16 -04002401 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002402 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002403 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002404 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002405 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002406 }
2407
2408 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002409 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002410 spv::Id spvType = convertGlslangToSpvType(node->getType());
2411
Rex Xucabbb782017-03-24 13:41:14 +08002412 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2413 node->getType().containsBasicType(glslang::EbtInt16) ||
2414 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002415 if (contains16BitType) {
2416 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
John Kessenich66011cb2018-03-06 16:12:04 -07002417 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002418 builder.addCapability(spv::CapabilityStorageInputOutput16);
2419 } else if (storageClass == spv::StorageClassPushConstant) {
John Kessenich66011cb2018-03-06 16:12:04 -07002420 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002421 builder.addCapability(spv::CapabilityStoragePushConstant16);
2422 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich66011cb2018-03-06 16:12:04 -07002423 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002424 builder.addCapability(spv::CapabilityStorageUniform16);
2425 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2426 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2427 }
2428 }
Rex Xuf89ad982017-04-07 23:22:33 +08002429
John Kessenich140f3df2015-06-26 16:58:36 -06002430 const char* name = node->getName().c_str();
2431 if (glslang::IsAnonymous(name))
2432 name = "";
2433
2434 return builder.createVariable(storageClass, spvType, name);
2435}
2436
2437// Return type Id of the sampled type.
2438spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2439{
2440 switch (sampler.type) {
2441 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08002442#ifdef AMD_EXTENSIONS
2443 case glslang::EbtFloat16:
2444 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
2445 builder.addCapability(spv::CapabilityFloat16ImageAMD);
2446 return builder.makeFloatType(16);
2447#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002448 case glslang::EbtInt: return builder.makeIntType(32);
2449 case glslang::EbtUint: return builder.makeUintType(32);
2450 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002451 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002452 return builder.makeFloatType(32);
2453 }
2454}
2455
John Kessenich8c8505c2016-07-26 12:50:38 -06002456// If node is a swizzle operation, return the type that should be used if
2457// the swizzle base is first consumed by another operation, before the swizzle
2458// is applied.
2459spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2460{
John Kessenichecba76f2017-01-06 00:34:48 -07002461 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002462 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2463 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2464 else
2465 return spv::NoType;
2466}
2467
2468// When inverting a swizzle with a parent op, this function
2469// will apply the swizzle operation to a completed parent operation.
2470spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2471{
2472 std::vector<unsigned> swizzle;
2473 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2474 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2475}
2476
John Kessenich8c8505c2016-07-26 12:50:38 -06002477// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2478void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2479{
2480 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2481 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2482 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2483}
2484
John Kessenich3ac051e2015-12-20 11:29:16 -07002485// Convert from a glslang type to an SPV type, by calling into a
2486// recursive version of this function. This establishes the inherited
2487// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002488spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2489{
John Kessenichead86222018-03-28 18:01:20 -06002490 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false);
John Kessenich31ed4832015-09-09 17:51:38 -06002491}
2492
2493// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002494// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002495// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06002496spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
2497 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier, bool lastBufferBlockMember)
John Kessenich31ed4832015-09-09 17:51:38 -06002498{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002499 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002500
2501 switch (type.getBasicType()) {
2502 case glslang::EbtVoid:
2503 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002504 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002505 break;
2506 case glslang::EbtFloat:
2507 spvType = builder.makeFloatType(32);
2508 break;
2509 case glslang::EbtDouble:
2510 spvType = builder.makeFloatType(64);
2511 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002512 case glslang::EbtFloat16:
John Kessenich66011cb2018-03-06 16:12:04 -07002513 builder.addCapability(spv::CapabilityFloat16);
2514#if AMD_EXTENSIONS
2515 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2516 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
2517#endif
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002518 spvType = builder.makeFloatType(16);
2519 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002520 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002521 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2522 // a 32-bit int where non-0 means true.
2523 if (explicitLayout != glslang::ElpNone)
2524 spvType = builder.makeUintType(32);
2525 else
2526 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002527 break;
John Kessenich66011cb2018-03-06 16:12:04 -07002528 case glslang::EbtInt8:
2529 builder.addCapability(spv::CapabilityInt8);
2530 spvType = builder.makeIntType(8);
2531 break;
2532 case glslang::EbtUint8:
2533 builder.addCapability(spv::CapabilityInt8);
2534 spvType = builder.makeUintType(8);
2535 break;
2536 case glslang::EbtInt16:
2537 builder.addCapability(spv::CapabilityInt16);
2538#ifdef AMD_EXTENSIONS
2539 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2540 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2541#endif
2542 spvType = builder.makeIntType(16);
2543 break;
2544 case glslang::EbtUint16:
2545 builder.addCapability(spv::CapabilityInt16);
2546#ifdef AMD_EXTENSIONS
2547 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2548 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2549#endif
2550 spvType = builder.makeUintType(16);
2551 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002552 case glslang::EbtInt:
2553 spvType = builder.makeIntType(32);
2554 break;
2555 case glslang::EbtUint:
2556 spvType = builder.makeUintType(32);
2557 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002558 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002559 spvType = builder.makeIntType(64);
2560 break;
2561 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002562 spvType = builder.makeUintType(64);
2563 break;
John Kessenich426394d2015-07-23 10:22:48 -06002564 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002565 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002566 spvType = builder.makeUintType(32);
2567 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002568 case glslang::EbtSampler:
2569 {
2570 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002571 if (sampler.sampler) {
2572 // pure sampler
2573 spvType = builder.makeSamplerType();
2574 } else {
2575 // an image is present, make its type
2576 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2577 sampler.image ? 2 : 1, TranslateImageFormat(type));
2578 if (sampler.combined) {
2579 // already has both image and sampler, make the combined type
2580 spvType = builder.makeSampledImageType(spvType);
2581 }
John Kessenich55e7d112015-11-15 21:33:39 -07002582 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002583 }
John Kessenich140f3df2015-06-26 16:58:36 -06002584 break;
2585 case glslang::EbtStruct:
2586 case glslang::EbtBlock:
2587 {
2588 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002589 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002590
2591 // Try to share structs for different layouts, but not yet for other
2592 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002593 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002594 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002595 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002596 break;
2597
2598 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002599 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002600 memberRemapper[glslangMembers].resize(glslangMembers->size());
2601 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002602 }
2603 break;
2604 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002605 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002606 break;
2607 }
2608
2609 if (type.isMatrix())
2610 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2611 else {
2612 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2613 if (type.getVectorSize() > 1)
2614 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2615 }
2616
2617 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002618 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2619
John Kessenichc9a80832015-09-12 12:17:44 -06002620 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002621 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002622 // We need to decorate array strides for types needing explicit layout, except blocks.
2623 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002624 // Use a dummy glslang type for querying internal strides of
2625 // arrays of arrays, but using just a one-dimensional array.
2626 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06002627 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
2628 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07002629
2630 // Will compute the higher-order strides here, rather than making a whole
2631 // pile of types and doing repetitive recursion on their contents.
2632 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2633 }
John Kessenichf8842e52016-01-04 19:22:56 -07002634
2635 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002636 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002637 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002638 if (stride > 0)
2639 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002640 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002641 }
2642 } else {
2643 // single-dimensional array, and don't yet have stride
2644
John Kessenichf8842e52016-01-04 19:22:56 -07002645 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002646 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2647 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002648 }
John Kessenich31ed4832015-09-09 17:51:38 -06002649
John Kessenichead86222018-03-28 18:01:20 -06002650 // Do the outer dimension, which might not be known for a runtime-sized array.
2651 // (Unsized arrays that survive through linking will be runtime-sized arrays)
2652 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07002653 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichead86222018-03-28 18:01:20 -06002654 else
2655 spvType = builder.makeRuntimeArray(spvType);
John Kessenichc9e0a422015-12-29 21:27:24 -07002656 if (stride > 0)
2657 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002658 }
2659
2660 return spvType;
2661}
2662
John Kessenich0e737842017-03-24 18:38:16 -06002663// TODO: this functionality should exist at a higher level, in creating the AST
2664//
2665// Identify interface members that don't have their required extension turned on.
2666//
2667bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2668{
2669 auto& extensions = glslangIntermediate->getRequestedExtensions();
2670
Rex Xubcf291a2017-03-29 23:01:36 +08002671 if (member.getFieldName() == "gl_ViewportMask" &&
2672 extensions.find("GL_NV_viewport_array2") == extensions.end())
2673 return true;
2674 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2675 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2676 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002677 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2678 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2679 return true;
2680 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2681 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2682 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002683 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2684 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2685 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002686
2687 return false;
2688};
2689
John Kessenich6090df02016-06-30 21:18:02 -06002690// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2691// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2692// Mutually recursive with convertGlslangToSpvType().
2693spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2694 const glslang::TTypeList* glslangMembers,
2695 glslang::TLayoutPacking explicitLayout,
2696 const glslang::TQualifier& qualifier)
2697{
2698 // Create a vector of struct types for SPIR-V to consume
2699 std::vector<spv::Id> spvMembers;
2700 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
John Kessenich6090df02016-06-30 21:18:02 -06002701 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2702 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2703 if (glslangMember.hiddenMember()) {
2704 ++memberDelta;
2705 if (type.getBasicType() == glslang::EbtBlock)
2706 memberRemapper[glslangMembers][i] = -1;
2707 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002708 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002709 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002710 if (filterMember(glslangMember))
2711 continue;
2712 }
John Kessenich6090df02016-06-30 21:18:02 -06002713 // modify just this child's view of the qualifier
2714 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2715 InheritQualifiers(memberQualifier, qualifier);
2716
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002717 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002718 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002719 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002720
2721 // recurse
John Kessenichead86222018-03-28 18:01:20 -06002722 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
2723 i == (int)glslangMembers->size() - 1;
2724 spvMembers.push_back(
2725 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember));
John Kessenich6090df02016-06-30 21:18:02 -06002726 }
2727 }
2728
2729 // Make the SPIR-V type
2730 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002731 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002732 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2733
2734 // Decorate it
2735 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2736
2737 return spvType;
2738}
2739
2740void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2741 const glslang::TTypeList* glslangMembers,
2742 glslang::TLayoutPacking explicitLayout,
2743 const glslang::TQualifier& qualifier,
2744 spv::Id spvType)
2745{
2746 // Name and decorate the non-hidden members
2747 int offset = -1;
2748 int locationOffset = 0; // for use within the members of this struct
2749 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2750 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2751 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002752 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002753 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002754 if (filterMember(glslangMember))
2755 continue;
2756 }
John Kessenich6090df02016-06-30 21:18:02 -06002757
2758 // modify just this child's view of the qualifier
2759 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2760 InheritQualifiers(memberQualifier, qualifier);
2761
2762 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07002763 if (member < 0)
2764 continue;
2765
2766 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2767 builder.addMemberDecoration(spvType, member,
2768 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2769 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2770 // Add interpolation and auxiliary storage decorations only to
2771 // top-level members of Input and Output storage classes
2772 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2773 type.getQualifier().storage == glslang::EvqVaryingOut) {
2774 if (type.getBasicType() == glslang::EbtBlock ||
2775 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
2776 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2777 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002778 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002779 }
2780 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002781
John Kessenich5d610ee2018-03-07 18:05:55 -07002782 if (type.getBasicType() == glslang::EbtBlock &&
2783 qualifier.storage == glslang::EvqBuffer) {
2784 // Add memory decorations only to top-level members of shader storage block
2785 std::vector<spv::Decoration> memory;
2786 TranslateMemoryDecoration(memberQualifier, memory);
2787 for (unsigned int i = 0; i < memory.size(); ++i)
2788 builder.addMemberDecoration(spvType, member, memory[i]);
2789 }
John Kessenich6090df02016-06-30 21:18:02 -06002790
John Kessenich5d610ee2018-03-07 18:05:55 -07002791 // Location assignment was already completed correctly by the front end,
2792 // just track whether a member needs to be decorated.
2793 // Ignore member locations if the container is an array, as that's
2794 // ill-specified and decisions have been made to not allow this.
2795 if (! type.isArray() && memberQualifier.hasLocation())
2796 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002797
John Kessenich5d610ee2018-03-07 18:05:55 -07002798 if (qualifier.hasLocation()) // track for upcoming inheritance
2799 locationOffset += glslangIntermediate->computeTypeLocationSize(
2800 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06002801
John Kessenich5d610ee2018-03-07 18:05:55 -07002802 // component, XFB, others
2803 if (glslangMember.getQualifier().hasComponent())
2804 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
2805 glslangMember.getQualifier().layoutComponent);
2806 if (glslangMember.getQualifier().hasXfbOffset())
2807 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
2808 glslangMember.getQualifier().layoutXfbOffset);
2809 else if (explicitLayout != glslang::ElpNone) {
2810 // figure out what to do with offset, which is accumulating
2811 int nextOffset;
2812 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2813 if (offset >= 0)
2814 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2815 offset = nextOffset;
2816 }
John Kessenich6090df02016-06-30 21:18:02 -06002817
John Kessenich5d610ee2018-03-07 18:05:55 -07002818 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2819 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
2820 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06002821
John Kessenich5d610ee2018-03-07 18:05:55 -07002822 // built-in variable decorations
2823 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
2824 if (builtIn != spv::BuiltInMax)
2825 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002826
John Kessenichead86222018-03-28 18:01:20 -06002827 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
2828 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
2829 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
2830 memberQualifier.semanticName);
2831 }
2832
chaoc771d89f2017-01-13 01:10:53 -08002833#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07002834 if (builtIn == spv::BuiltInLayer) {
2835 // SPV_NV_viewport_array2 extension
2836 if (glslangMember.getQualifier().layoutViewportRelative){
2837 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2838 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2839 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08002840 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002841 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2842 builder.addMemberDecoration(spvType, member,
2843 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
2844 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2845 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2846 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08002847 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002848 }
2849 if (glslangMember.getQualifier().layoutPassthrough) {
2850 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2851 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2852 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2853 }
chaoc771d89f2017-01-13 01:10:53 -08002854#endif
John Kessenich6090df02016-06-30 21:18:02 -06002855 }
2856
2857 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07002858 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2859 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002860 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2861 builder.addCapability(spv::CapabilityGeometryStreams);
2862 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2863 }
John Kessenich6090df02016-06-30 21:18:02 -06002864}
2865
John Kessenich6c292d32016-02-15 20:58:50 -07002866// Turn the expression forming the array size into an id.
2867// This is not quite trivial, because of specialization constants.
2868// Sometimes, a raw constant is turned into an Id, and sometimes
2869// a specialization constant expression is.
2870spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2871{
2872 // First, see if this is sized with a node, meaning a specialization constant:
2873 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2874 if (specNode != nullptr) {
2875 builder.clearAccessChain();
2876 specNode->traverse(this);
2877 return accessChainLoad(specNode->getAsTyped()->getType());
2878 }
qining25262b32016-05-06 17:25:16 -04002879
John Kessenich6c292d32016-02-15 20:58:50 -07002880 // Otherwise, need a compile-time (front end) size, get it:
2881 int size = arraySizes.getDimSize(dim);
2882 assert(size > 0);
2883 return builder.makeUintConstant(size);
2884}
2885
John Kessenich103bef92016-02-08 21:38:15 -07002886// Wrap the builder's accessChainLoad to:
2887// - localize handling of RelaxedPrecision
2888// - use the SPIR-V inferred type instead of another conversion of the glslang type
2889// (avoids unnecessary work and possible type punning for structures)
2890// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002891spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2892{
John Kessenich103bef92016-02-08 21:38:15 -07002893 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2894 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2895
2896 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002897 if (type.getBasicType() == glslang::EbtBool) {
2898 if (builder.isScalarType(nominalTypeId)) {
2899 // Conversion for bool
2900 spv::Id boolType = builder.makeBoolType();
2901 if (nominalTypeId != boolType)
2902 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2903 } else if (builder.isVectorType(nominalTypeId)) {
2904 // Conversion for bvec
2905 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2906 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2907 if (nominalTypeId != bvecType)
2908 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2909 }
2910 }
John Kessenich103bef92016-02-08 21:38:15 -07002911
2912 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002913}
2914
Rex Xu27253232016-02-23 17:51:09 +08002915// Wrap the builder's accessChainStore to:
2916// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002917//
2918// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002919void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2920{
2921 // Need to convert to abstract types when necessary
2922 if (type.getBasicType() == glslang::EbtBool) {
2923 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2924
2925 if (builder.isScalarType(nominalTypeId)) {
2926 // Conversion for bool
2927 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002928 if (nominalTypeId != boolType) {
2929 // keep these outside arguments, for determinant order-of-evaluation
2930 spv::Id one = builder.makeUintConstant(1);
2931 spv::Id zero = builder.makeUintConstant(0);
2932 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2933 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002934 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002935 } else if (builder.isVectorType(nominalTypeId)) {
2936 // Conversion for bvec
2937 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2938 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002939 if (nominalTypeId != bvecType) {
2940 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002941 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2942 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2943 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002944 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002945 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2946 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002947 }
2948 }
2949
2950 builder.accessChainStore(rvalue);
2951}
2952
John Kessenich4bf71552016-09-02 11:20:21 -06002953// For storing when types match at the glslang level, but not might match at the
2954// SPIR-V level.
2955//
2956// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002957// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002958// as in a member-decorated way.
2959//
2960// NOTE: This function can handle any store request; if it's not special it
2961// simplifies to a simple OpStore.
2962//
2963// Implicitly uses the existing builder.accessChain as the storage target.
2964void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2965{
John Kessenichb3e24e42016-09-11 12:33:43 -06002966 // we only do the complex path here if it's an aggregate
2967 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002968 accessChainStore(type, rValue);
2969 return;
2970 }
2971
John Kessenichb3e24e42016-09-11 12:33:43 -06002972 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002973 spv::Id rType = builder.getTypeId(rValue);
2974 spv::Id lValue = builder.accessChainGetLValue();
2975 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2976 if (lType == rType) {
2977 accessChainStore(type, rValue);
2978 return;
2979 }
2980
John Kessenichb3e24e42016-09-11 12:33:43 -06002981 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002982 // where the two types were the same type in GLSL. This requires member
2983 // by member copy, recursively.
2984
John Kessenichb3e24e42016-09-11 12:33:43 -06002985 // If an array, copy element by element.
2986 if (type.isArray()) {
2987 glslang::TType glslangElementType(type, 0);
2988 spv::Id elementRType = builder.getContainedTypeId(rType);
2989 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2990 // get the source member
2991 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002992
John Kessenichb3e24e42016-09-11 12:33:43 -06002993 // set up the target storage
2994 builder.clearAccessChain();
2995 builder.setAccessChainLValue(lValue);
2996 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002997
John Kessenichb3e24e42016-09-11 12:33:43 -06002998 // store the member
2999 multiTypeStore(glslangElementType, elementRValue);
3000 }
3001 } else {
3002 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003003
John Kessenichb3e24e42016-09-11 12:33:43 -06003004 // loop over structure members
3005 const glslang::TTypeList& members = *type.getStruct();
3006 for (int m = 0; m < (int)members.size(); ++m) {
3007 const glslang::TType& glslangMemberType = *members[m].type;
3008
3009 // get the source member
3010 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3011 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3012
3013 // set up the target storage
3014 builder.clearAccessChain();
3015 builder.setAccessChainLValue(lValue);
3016 builder.accessChainPush(builder.makeIntConstant(m));
3017
3018 // store the member
3019 multiTypeStore(glslangMemberType, memberRValue);
3020 }
John Kessenich4bf71552016-09-02 11:20:21 -06003021 }
3022}
3023
John Kessenichf85e8062015-12-19 13:57:10 -07003024// Decide whether or not this type should be
3025// decorated with offsets and strides, and if so
3026// whether std140 or std430 rules should be applied.
3027glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003028{
John Kessenichf85e8062015-12-19 13:57:10 -07003029 // has to be a block
3030 if (type.getBasicType() != glslang::EbtBlock)
3031 return glslang::ElpNone;
3032
3033 // has to be a uniform or buffer block
3034 if (type.getQualifier().storage != glslang::EvqUniform &&
3035 type.getQualifier().storage != glslang::EvqBuffer)
3036 return glslang::ElpNone;
3037
3038 // return the layout to use
3039 switch (type.getQualifier().layoutPacking) {
3040 case glslang::ElpStd140:
3041 case glslang::ElpStd430:
3042 return type.getQualifier().layoutPacking;
3043 default:
3044 return glslang::ElpNone;
3045 }
John Kessenich31ed4832015-09-09 17:51:38 -06003046}
3047
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003048// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003049int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003050{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003051 int size;
John Kessenich49987892015-12-29 17:11:44 -07003052 int stride;
3053 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003054
3055 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003056}
3057
John Kessenich49987892015-12-29 17:11:44 -07003058// 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 -07003059// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003060int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003061{
John Kessenich49987892015-12-29 17:11:44 -07003062 glslang::TType elementType;
3063 elementType.shallowCopy(matrixType);
3064 elementType.clearArraySizes();
3065
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003066 int size;
John Kessenich49987892015-12-29 17:11:44 -07003067 int stride;
3068 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
3069
3070 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003071}
3072
John Kessenich5e4b1242015-08-06 22:53:06 -06003073// Given a member type of a struct, realign the current offset for it, and compute
3074// the next (not yet aligned) offset for the next member, which will get aligned
3075// on the next call.
3076// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3077// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3078// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003079void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003080 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003081{
3082 // this will get a positive value when deemed necessary
3083 nextOffset = -1;
3084
John Kessenich5e4b1242015-08-06 22:53:06 -06003085 // override anything in currentOffset with user-set offset
3086 if (memberType.getQualifier().hasOffset())
3087 currentOffset = memberType.getQualifier().layoutOffset;
3088
3089 // It could be that current linker usage in glslang updated all the layoutOffset,
3090 // in which case the following code does not matter. But, that's not quite right
3091 // once cross-compilation unit GLSL validation is done, as the original user
3092 // settings are needed in layoutOffset, and then the following will come into play.
3093
John Kessenichf85e8062015-12-19 13:57:10 -07003094 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003095 if (! memberType.getQualifier().hasOffset())
3096 currentOffset = -1;
3097
3098 return;
3099 }
3100
John Kessenichf85e8062015-12-19 13:57:10 -07003101 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003102 if (currentOffset < 0)
3103 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003104
John Kessenich5e4b1242015-08-06 22:53:06 -06003105 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3106 // but possibly not yet correctly aligned.
3107
3108 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003109 int dummyStride;
3110 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003111
3112 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003113 // TODO: make this consistent in early phases of code:
3114 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3115 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3116 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06003117 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003118 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003119 int dummySize;
3120 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3121 if (componentAlignment <= 4)
3122 memberAlignment = componentAlignment;
3123 }
3124
3125 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003126 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003127
3128 // Bump up to vec4 if there is a bad straddle
3129 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
3130 glslang::RoundToPow2(currentOffset, 16);
3131
John Kessenich5e4b1242015-08-06 22:53:06 -06003132 nextOffset = currentOffset + memberSize;
3133}
3134
David Netoa901ffe2016-06-08 14:11:40 +01003135void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003136{
David Netoa901ffe2016-06-08 14:11:40 +01003137 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3138 switch (glslangBuiltIn)
3139 {
3140 case glslang::EbvClipDistance:
3141 case glslang::EbvCullDistance:
3142 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003143#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003144 case glslang::EbvViewportMaskNV:
3145 case glslang::EbvSecondaryPositionNV:
3146 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003147 case glslang::EbvPositionPerViewNV:
3148 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08003149#endif
David Netoa901ffe2016-06-08 14:11:40 +01003150 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3151 // Alternately, we could just call this for any glslang built-in, since the
3152 // capability already guards against duplicates.
3153 TranslateBuiltInDecoration(glslangBuiltIn, false);
3154 break;
3155 default:
3156 // Capabilities were already generated when the struct was declared.
3157 break;
3158 }
John Kessenichebb50532016-05-16 19:22:05 -06003159}
3160
John Kessenich6fccb3c2016-09-19 16:01:41 -06003161bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003162{
John Kessenicheee9d532016-09-19 18:09:30 -06003163 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003164}
3165
John Kessenichd41993d2017-09-10 15:21:05 -06003166// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003167// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3168// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd41993d2017-09-10 15:21:05 -06003169bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier)
3170{
John Kessenich6a14f782017-12-04 02:48:10 -07003171 assert(qualifier == glslang::EvqIn ||
3172 qualifier == glslang::EvqOut ||
3173 qualifier == glslang::EvqInOut ||
3174 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003175 return qualifier != glslang::EvqConstReadOnly;
3176}
3177
3178// Is parameter pass-by-original?
3179bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3180 bool implicitThisParam)
3181{
3182 if (implicitThisParam) // implicit this
3183 return true;
3184 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003185 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003186 return paramType.containsOpaque() || // sampler, etc.
3187 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3188}
3189
John Kessenich140f3df2015-06-26 16:58:36 -06003190// Make all the functions, skeletally, without actually visiting their bodies.
3191void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3192{
John Kessenichfad62972017-07-18 02:35:46 -06003193 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
3194 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3195 if (paramPrecision != spv::NoPrecision)
3196 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06003197 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06003198 };
3199
John Kessenich140f3df2015-06-26 16:58:36 -06003200 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3201 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003202 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003203 continue;
3204
3205 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003206 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003207 //
qining25262b32016-05-06 17:25:16 -04003208 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003209 // function. What it is an address of varies:
3210 //
John Kessenich4bf71552016-09-02 11:20:21 -06003211 // - "in" parameters not marked as "const" can be written to without modifying the calling
3212 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003213 //
3214 // - "const in" parameters can just be the r-value, as no writes need occur.
3215 //
John Kessenich4bf71552016-09-02 11:20:21 -06003216 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3217 // 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 -06003218
3219 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003220 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003221 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3222
John Kessenichfad62972017-07-18 02:35:46 -06003223 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3224 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003225
John Kessenichfad62972017-07-18 02:35:46 -06003226 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003227 for (int p = 0; p < (int)parameters.size(); ++p) {
3228 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3229 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003230 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003231 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003232 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003233 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3234 else
John Kessenich4bf71552016-09-02 11:20:21 -06003235 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003236 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003237 paramTypes.push_back(typeId);
3238 }
3239
3240 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003241 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3242 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003243 glslFunction->getName().c_str(), paramTypes,
3244 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003245 if (implicitThis)
3246 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003247
3248 // Track function to emit/call later
3249 functionMap[glslFunction->getName().c_str()] = function;
3250
3251 // Set the parameter id's
3252 for (int p = 0; p < (int)parameters.size(); ++p) {
3253 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3254 // give a name too
3255 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3256 }
3257 }
3258}
3259
3260// Process all the initializers, while skipping the functions and link objects
3261void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3262{
3263 builder.setBuildPoint(shaderEntry->getLastBlock());
3264 for (int i = 0; i < (int)initializers.size(); ++i) {
3265 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3266 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3267
3268 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003269 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003270 initializer->traverse(this);
3271 }
3272 }
3273}
3274
3275// Process all the functions, while skipping initializers.
3276void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3277{
3278 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3279 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003280 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003281 node->traverse(this);
3282 }
3283}
3284
3285void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3286{
qining25262b32016-05-06 17:25:16 -04003287 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003288 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003289 currentFunction = functionMap[node->getName().c_str()];
3290 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003291 builder.setBuildPoint(functionBlock);
3292}
3293
Rex Xu04db3f52015-09-16 11:44:02 +08003294void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003295{
Rex Xufc618912015-09-09 16:42:49 +08003296 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003297
3298 glslang::TSampler sampler = {};
3299 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003300#ifdef AMD_EXTENSIONS
3301 bool f16ShadowCompare = false;
3302#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003303 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003304 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3305 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003306#ifdef AMD_EXTENSIONS
3307 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3308#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003309 }
3310
John Kessenich140f3df2015-06-26 16:58:36 -06003311 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3312 builder.clearAccessChain();
3313 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003314
3315 // Special case l-value operands
3316 bool lvalue = false;
3317 switch (node.getOp()) {
3318 case glslang::EOpImageAtomicAdd:
3319 case glslang::EOpImageAtomicMin:
3320 case glslang::EOpImageAtomicMax:
3321 case glslang::EOpImageAtomicAnd:
3322 case glslang::EOpImageAtomicOr:
3323 case glslang::EOpImageAtomicXor:
3324 case glslang::EOpImageAtomicExchange:
3325 case glslang::EOpImageAtomicCompSwap:
3326 if (i == 0)
3327 lvalue = true;
3328 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003329 case glslang::EOpSparseImageLoad:
3330 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3331 lvalue = true;
3332 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003333#ifdef AMD_EXTENSIONS
3334 case glslang::EOpSparseTexture:
3335 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3336 lvalue = true;
3337 break;
3338 case glslang::EOpSparseTextureClamp:
3339 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3340 lvalue = true;
3341 break;
3342 case glslang::EOpSparseTextureLod:
3343 case glslang::EOpSparseTextureOffset:
3344 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
3345 lvalue = true;
3346 break;
3347#else
Rex Xu48edadf2015-12-31 16:11:41 +08003348 case glslang::EOpSparseTexture:
3349 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3350 lvalue = true;
3351 break;
3352 case glslang::EOpSparseTextureClamp:
3353 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3354 lvalue = true;
3355 break;
3356 case glslang::EOpSparseTextureLod:
3357 case glslang::EOpSparseTextureOffset:
3358 if (i == 3)
3359 lvalue = true;
3360 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003361#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003362 case glslang::EOpSparseTextureFetch:
3363 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3364 lvalue = true;
3365 break;
3366 case glslang::EOpSparseTextureFetchOffset:
3367 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3368 lvalue = true;
3369 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003370#ifdef AMD_EXTENSIONS
3371 case glslang::EOpSparseTextureLodOffset:
3372 case glslang::EOpSparseTextureGrad:
3373 case glslang::EOpSparseTextureOffsetClamp:
3374 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
3375 lvalue = true;
3376 break;
3377 case glslang::EOpSparseTextureGradOffset:
3378 case glslang::EOpSparseTextureGradClamp:
3379 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
3380 lvalue = true;
3381 break;
3382 case glslang::EOpSparseTextureGradOffsetClamp:
3383 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
3384 lvalue = true;
3385 break;
3386#else
Rex Xu48edadf2015-12-31 16:11:41 +08003387 case glslang::EOpSparseTextureLodOffset:
3388 case glslang::EOpSparseTextureGrad:
3389 case glslang::EOpSparseTextureOffsetClamp:
3390 if (i == 4)
3391 lvalue = true;
3392 break;
3393 case glslang::EOpSparseTextureGradOffset:
3394 case glslang::EOpSparseTextureGradClamp:
3395 if (i == 5)
3396 lvalue = true;
3397 break;
3398 case glslang::EOpSparseTextureGradOffsetClamp:
3399 if (i == 6)
3400 lvalue = true;
3401 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003402#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08003403 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003404 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3405 lvalue = true;
3406 break;
3407 case glslang::EOpSparseTextureGatherOffset:
3408 case glslang::EOpSparseTextureGatherOffsets:
3409 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3410 lvalue = true;
3411 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003412#ifdef AMD_EXTENSIONS
3413 case glslang::EOpSparseTextureGatherLod:
3414 if (i == 3)
3415 lvalue = true;
3416 break;
3417 case glslang::EOpSparseTextureGatherLodOffset:
3418 case glslang::EOpSparseTextureGatherLodOffsets:
3419 if (i == 4)
3420 lvalue = true;
3421 break;
Rex Xu129799a2017-07-05 17:23:28 +08003422 case glslang::EOpSparseImageLoadLod:
3423 if (i == 3)
3424 lvalue = true;
3425 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003426#endif
Rex Xufc618912015-09-09 16:42:49 +08003427 default:
3428 break;
3429 }
3430
Rex Xu6b86d492015-09-16 17:48:22 +08003431 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003432 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003433 else
John Kessenich32cfd492016-02-02 12:37:46 -07003434 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003435 }
3436}
3437
John Kessenichfc51d282015-08-19 13:34:18 -06003438void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003439{
John Kessenichfc51d282015-08-19 13:34:18 -06003440 builder.clearAccessChain();
3441 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003442 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003443}
John Kessenich140f3df2015-06-26 16:58:36 -06003444
John Kessenichfc51d282015-08-19 13:34:18 -06003445spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3446{
John Kesseniche485c7a2017-05-31 18:50:53 -06003447 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003448 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003449
3450 builder.setLine(node->getLoc().line);
3451
John Kessenichfc51d282015-08-19 13:34:18 -06003452 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003453 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3454 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08003455#ifdef AMD_EXTENSIONS
3456 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
3457 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
3458 : false;
3459#endif
3460
John Kessenichfc51d282015-08-19 13:34:18 -06003461 std::vector<spv::Id> arguments;
3462 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003463 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003464 else
3465 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003466 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003467
3468 spv::Builder::TextureParameters params = { };
3469 params.sampler = arguments[0];
3470
Rex Xu04db3f52015-09-16 11:44:02 +08003471 glslang::TCrackedTextureOp cracked;
3472 node->crackTexture(sampler, cracked);
3473
amhagan05506bb2017-06-13 16:53:02 -04003474 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003475
John Kessenichfc51d282015-08-19 13:34:18 -06003476 // Check for queries
3477 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003478 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3479 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003480 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003481
John Kessenichfc51d282015-08-19 13:34:18 -06003482 switch (node->getOp()) {
3483 case glslang::EOpImageQuerySize:
3484 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003485 if (arguments.size() > 1) {
3486 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003487 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003488 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003489 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003490 case glslang::EOpImageQuerySamples:
3491 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003492 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003493 case glslang::EOpTextureQueryLod:
3494 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003495 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003496 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003497 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003498 case glslang::EOpSparseTexelsResident:
3499 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003500 default:
3501 assert(0);
3502 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003503 }
John Kessenich140f3df2015-06-26 16:58:36 -06003504 }
3505
LoopDawg4425f242018-02-18 11:40:01 -07003506 int components = node->getType().getVectorSize();
3507
3508 if (node->getOp() == glslang::EOpTextureFetch) {
3509 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3510 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3511 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3512 // here around e.g. which ones return scalars or other types.
3513 components = 4;
3514 }
3515
3516 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3517
3518 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3519
Rex Xufc618912015-09-09 16:42:49 +08003520 // Check for image functions other than queries
3521 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003522 std::vector<spv::Id> operands;
3523 auto opIt = arguments.begin();
3524 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003525
3526 // Handle subpass operations
3527 // TODO: GLSL should change to have the "MS" only on the type rather than the
3528 // built-in function.
3529 if (cracked.subpass) {
3530 // add on the (0,0) coordinate
3531 spv::Id zero = builder.makeIntConstant(0);
3532 std::vector<spv::Id> comps;
3533 comps.push_back(zero);
3534 comps.push_back(zero);
3535 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3536 if (sampler.ms) {
3537 operands.push_back(spv::ImageOperandsSampleMask);
3538 operands.push_back(*(opIt++));
3539 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003540 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3541 builder.setPrecision(result, precision);
3542 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003543 }
3544
John Kessenich56bab042015-09-16 10:54:31 -06003545 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003546#ifdef AMD_EXTENSIONS
3547 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3548#else
John Kessenich56bab042015-09-16 10:54:31 -06003549 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003550#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003551 if (sampler.ms) {
3552 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003553 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003554#ifdef AMD_EXTENSIONS
3555 } else if (cracked.lod) {
3556 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3557 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3558
3559 operands.push_back(spv::ImageOperandsLodMask);
3560 operands.push_back(*opIt);
3561#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003562 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003563 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3564 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003565
LoopDawg4425f242018-02-18 11:40:01 -07003566 std::vector<spv::Id> result = { builder.createOp(spv::OpImageRead, resultType(), operands) };
3567 builder.setPrecision(result[0], precision);
3568
3569 // If needed, add a conversion constructor to the proper size.
3570 if (components != node->getType().getVectorSize())
3571 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3572
3573 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08003574#ifdef AMD_EXTENSIONS
3575 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3576#else
John Kessenich56bab042015-09-16 10:54:31 -06003577 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003578#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003579 if (sampler.ms) {
3580 operands.push_back(*(opIt + 1));
3581 operands.push_back(spv::ImageOperandsSampleMask);
3582 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003583#ifdef AMD_EXTENSIONS
3584 } else if (cracked.lod) {
3585 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3586 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3587
3588 operands.push_back(*(opIt + 1));
3589 operands.push_back(spv::ImageOperandsLodMask);
3590 operands.push_back(*opIt);
3591#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003592 } else
3593 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003594 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003595 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3596 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003597 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003598#ifdef AMD_EXTENSIONS
3599 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3600#else
Rex Xu5eafa472016-02-19 22:24:03 +08003601 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003602#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003603 builder.addCapability(spv::CapabilitySparseResidency);
3604 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3605 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3606
3607 if (sampler.ms) {
3608 operands.push_back(spv::ImageOperandsSampleMask);
3609 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003610#ifdef AMD_EXTENSIONS
3611 } else if (cracked.lod) {
3612 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3613 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3614
3615 operands.push_back(spv::ImageOperandsLodMask);
3616 operands.push_back(*opIt++);
3617#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003618 }
3619
3620 // Create the return type that was a special structure
3621 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003622 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003623 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3624 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3625
3626 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3627
3628 // Decode the return type
3629 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3630 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003631 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003632 // Process image atomic operations
3633
3634 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3635 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003636 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003637
John Kessenich8c8505c2016-07-26 12:50:38 -06003638 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003639 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003640
3641 std::vector<spv::Id> operands;
3642 operands.push_back(pointer);
3643 for (; opIt != arguments.end(); ++opIt)
3644 operands.push_back(*opIt);
3645
John Kessenich8c8505c2016-07-26 12:50:38 -06003646 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003647 }
3648 }
3649
amhagan05506bb2017-06-13 16:53:02 -04003650#ifdef AMD_EXTENSIONS
3651 // Check for fragment mask functions other than queries
3652 if (cracked.fragMask) {
3653 assert(sampler.ms);
3654
3655 auto opIt = arguments.begin();
3656 std::vector<spv::Id> operands;
3657
3658 // Extract the image if necessary
3659 if (builder.isSampledImage(params.sampler))
3660 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3661
3662 operands.push_back(params.sampler);
3663 ++opIt;
3664
3665 if (sampler.isSubpass()) {
3666 // add on the (0,0) coordinate
3667 spv::Id zero = builder.makeIntConstant(0);
3668 std::vector<spv::Id> comps;
3669 comps.push_back(zero);
3670 comps.push_back(zero);
3671 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3672 }
3673
3674 for (; opIt != arguments.end(); ++opIt)
3675 operands.push_back(*opIt);
3676
3677 spv::Op fragMaskOp = spv::OpNop;
3678 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3679 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3680 else if (node->getOp() == glslang::EOpFragmentFetch)
3681 fragMaskOp = spv::OpFragmentFetchAMD;
3682
3683 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3684 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3685 return builder.createOp(fragMaskOp, resultType(), operands);
3686 }
3687#endif
3688
Rex Xufc618912015-09-09 16:42:49 +08003689 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003690 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003691 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3692
John Kessenichfc51d282015-08-19 13:34:18 -06003693 // check for bias argument
3694 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003695#ifdef AMD_EXTENSIONS
3696 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3697#else
Rex Xu71519fe2015-11-11 15:35:47 +08003698 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003699#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003700 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003701#ifdef AMD_EXTENSIONS
3702 if (cracked.gather)
3703 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08003704
3705 if (f16ShadowCompare)
3706 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003707#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003708 if (cracked.offset)
3709 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003710#ifdef AMD_EXTENSIONS
3711 else if (cracked.offsets)
3712 ++nonBiasArgCount;
3713#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003714 if (cracked.grad)
3715 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003716 if (cracked.lodClamp)
3717 ++nonBiasArgCount;
3718 if (sparse)
3719 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003720
3721 if ((int)arguments.size() > nonBiasArgCount)
3722 bias = true;
3723 }
3724
John Kessenicha5c33d62016-06-02 23:45:21 -06003725 // See if the sampler param should really be just the SPV image part
3726 if (cracked.fetch) {
3727 // a fetch needs to have the image extracted first
3728 if (builder.isSampledImage(params.sampler))
3729 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3730 }
3731
Rex Xu225e0fc2016-11-17 17:47:59 +08003732#ifdef AMD_EXTENSIONS
3733 if (cracked.gather) {
3734 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3735 if (bias || cracked.lod ||
3736 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3737 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003738 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003739 }
3740 }
3741#endif
3742
John Kessenichfc51d282015-08-19 13:34:18 -06003743 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003744
John Kessenichfc51d282015-08-19 13:34:18 -06003745 params.coords = arguments[1];
3746 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003747 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003748
3749 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08003750#ifdef AMD_EXTENSIONS
3751 if (cubeCompare || f16ShadowCompare) {
3752#else
Rex Xu48edadf2015-12-31 16:11:41 +08003753 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08003754#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003755 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003756 ++extraArgs;
3757 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003758 params.Dref = arguments[2];
3759 ++extraArgs;
3760 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003761 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003762 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003763 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003764 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003765 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003766 dRefComp = builder.getNumComponents(params.coords) - 1;
3767 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003768 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3769 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003770
3771 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003772 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003773 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003774 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003775 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3776 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3777 noImplicitLod = true;
3778 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003779
3780 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003781 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003782 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003783 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003784 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003785
3786 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003787 if (cracked.grad) {
3788 params.gradX = arguments[2 + extraArgs];
3789 params.gradY = arguments[3 + extraArgs];
3790 extraArgs += 2;
3791 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003792
3793 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003794 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003795 params.offset = arguments[2 + extraArgs];
3796 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003797 } else if (cracked.offsets) {
3798 params.offsets = arguments[2 + extraArgs];
3799 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003800 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003801
3802 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003803 if (cracked.lodClamp) {
3804 params.lodClamp = arguments[2 + extraArgs];
3805 ++extraArgs;
3806 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003807
3808 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003809 if (sparse) {
3810 params.texelOut = arguments[2 + extraArgs];
3811 ++extraArgs;
3812 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003813
John Kessenich76d4dfc2016-06-16 12:43:23 -06003814 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003815 if (cracked.gather && ! sampler.shadow) {
3816 // default component is 0, if missing, otherwise an argument
3817 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003818 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003819 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003820 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003821 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003822 }
3823
3824 // bias
3825 if (bias) {
3826 params.bias = arguments[2 + extraArgs];
3827 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003828 }
John Kessenichfc51d282015-08-19 13:34:18 -06003829
John Kessenich65336482016-06-16 14:06:26 -06003830 // projective component (might not to move)
3831 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3832 // are divided by the last component of P."
3833 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3834 // unused components will appear after all used components."
3835 if (cracked.proj) {
3836 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3837 int projTargetComp;
3838 switch (sampler.dim) {
3839 case glslang::Esd1D: projTargetComp = 1; break;
3840 case glslang::Esd2D: projTargetComp = 2; break;
3841 case glslang::EsdRect: projTargetComp = 2; break;
3842 default: projTargetComp = projSourceComp; break;
3843 }
3844 // copy the projective coordinate if we have to
3845 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003846 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003847 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3848 projSourceComp);
3849 params.coords = builder.createCompositeInsert(projComp, params.coords,
3850 builder.getTypeId(params.coords), projTargetComp);
3851 }
3852 }
3853
LoopDawg4425f242018-02-18 11:40:01 -07003854 std::vector<spv::Id> result = {
3855 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
3856 };
3857
3858 if (components != node->getType().getVectorSize())
3859 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3860
3861 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06003862}
3863
3864spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3865{
3866 // Grab the function's pointer from the previously created function
3867 spv::Function* function = functionMap[node->getName().c_str()];
3868 if (! function)
3869 return 0;
3870
3871 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3872 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3873
3874 // See comments in makeFunctions() for details about the semantics for parameter passing.
3875 //
3876 // These imply we need a four step process:
3877 // 1. Evaluate the arguments
3878 // 2. Allocate and make copies of in, out, and inout arguments
3879 // 3. Make the call
3880 // 4. Copy back the results
3881
3882 // 1. Evaluate the arguments
3883 std::vector<spv::Builder::AccessChain> lValues;
3884 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003885 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003886 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003887 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003888 // build l-value
3889 builder.clearAccessChain();
3890 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003891 argTypes.push_back(&paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003892 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenich6a14f782017-12-04 02:48:10 -07003893 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0) ||
3894 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003895 // save l-value
3896 lValues.push_back(builder.getAccessChain());
3897 } else {
3898 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003899 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003900 }
3901 }
3902
3903 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3904 // copy the original into that space.
3905 //
3906 // Also, build up the list of actual arguments to pass in for the call
3907 int lValueCount = 0;
3908 int rValueCount = 0;
3909 std::vector<spv::Id> spvArgs;
3910 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003911 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003912 spv::Id arg;
John Kessenichd41993d2017-09-10 15:21:05 -06003913 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003914 builder.setAccessChain(lValues[lValueCount]);
3915 arg = builder.accessChainGetLValue();
3916 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06003917 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003918 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003919 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3920 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3921 // need to copy the input into output space
3922 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003923 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003924 builder.clearAccessChain();
3925 builder.setAccessChainLValue(arg);
3926 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003927 }
3928 ++lValueCount;
3929 } else {
3930 arg = rValues[rValueCount];
3931 ++rValueCount;
3932 }
3933 spvArgs.push_back(arg);
3934 }
3935
3936 // 3. Make the call.
3937 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003938 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003939
3940 // 4. Copy back out an "out" arguments.
3941 lValueCount = 0;
3942 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003943 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenichd41993d2017-09-10 15:21:05 -06003944 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0))
3945 ++lValueCount;
3946 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003947 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3948 spv::Id copy = builder.createLoad(spvArgs[a]);
3949 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003950 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003951 }
3952 ++lValueCount;
3953 }
3954 }
3955
3956 return result;
3957}
3958
3959// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06003960spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06003961 spv::Id typeId, spv::Id left, spv::Id right,
3962 glslang::TBasicType typeProxy, bool reduceComparison)
3963{
John Kessenich66011cb2018-03-06 16:12:04 -07003964 bool isUnsigned = isTypeUnsignedInt(typeProxy);
3965 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08003966 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003967
3968 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003969 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003970 bool comparison = false;
3971
3972 switch (op) {
3973 case glslang::EOpAdd:
3974 case glslang::EOpAddAssign:
3975 if (isFloat)
3976 binOp = spv::OpFAdd;
3977 else
3978 binOp = spv::OpIAdd;
3979 break;
3980 case glslang::EOpSub:
3981 case glslang::EOpSubAssign:
3982 if (isFloat)
3983 binOp = spv::OpFSub;
3984 else
3985 binOp = spv::OpISub;
3986 break;
3987 case glslang::EOpMul:
3988 case glslang::EOpMulAssign:
3989 if (isFloat)
3990 binOp = spv::OpFMul;
3991 else
3992 binOp = spv::OpIMul;
3993 break;
3994 case glslang::EOpVectorTimesScalar:
3995 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003996 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003997 if (builder.isVector(right))
3998 std::swap(left, right);
3999 assert(builder.isScalar(right));
4000 needMatchingVectors = false;
4001 binOp = spv::OpVectorTimesScalar;
4002 } else
4003 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004004 break;
4005 case glslang::EOpVectorTimesMatrix:
4006 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004007 binOp = spv::OpVectorTimesMatrix;
4008 break;
4009 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004010 binOp = spv::OpMatrixTimesVector;
4011 break;
4012 case glslang::EOpMatrixTimesScalar:
4013 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004014 binOp = spv::OpMatrixTimesScalar;
4015 break;
4016 case glslang::EOpMatrixTimesMatrix:
4017 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004018 binOp = spv::OpMatrixTimesMatrix;
4019 break;
4020 case glslang::EOpOuterProduct:
4021 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004022 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004023 break;
4024
4025 case glslang::EOpDiv:
4026 case glslang::EOpDivAssign:
4027 if (isFloat)
4028 binOp = spv::OpFDiv;
4029 else if (isUnsigned)
4030 binOp = spv::OpUDiv;
4031 else
4032 binOp = spv::OpSDiv;
4033 break;
4034 case glslang::EOpMod:
4035 case glslang::EOpModAssign:
4036 if (isFloat)
4037 binOp = spv::OpFMod;
4038 else if (isUnsigned)
4039 binOp = spv::OpUMod;
4040 else
4041 binOp = spv::OpSMod;
4042 break;
4043 case glslang::EOpRightShift:
4044 case glslang::EOpRightShiftAssign:
4045 if (isUnsigned)
4046 binOp = spv::OpShiftRightLogical;
4047 else
4048 binOp = spv::OpShiftRightArithmetic;
4049 break;
4050 case glslang::EOpLeftShift:
4051 case glslang::EOpLeftShiftAssign:
4052 binOp = spv::OpShiftLeftLogical;
4053 break;
4054 case glslang::EOpAnd:
4055 case glslang::EOpAndAssign:
4056 binOp = spv::OpBitwiseAnd;
4057 break;
4058 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004059 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004060 binOp = spv::OpLogicalAnd;
4061 break;
4062 case glslang::EOpInclusiveOr:
4063 case glslang::EOpInclusiveOrAssign:
4064 binOp = spv::OpBitwiseOr;
4065 break;
4066 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004067 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004068 binOp = spv::OpLogicalOr;
4069 break;
4070 case glslang::EOpExclusiveOr:
4071 case glslang::EOpExclusiveOrAssign:
4072 binOp = spv::OpBitwiseXor;
4073 break;
4074 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004075 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004076 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004077 break;
4078
4079 case glslang::EOpLessThan:
4080 case glslang::EOpGreaterThan:
4081 case glslang::EOpLessThanEqual:
4082 case glslang::EOpGreaterThanEqual:
4083 case glslang::EOpEqual:
4084 case glslang::EOpNotEqual:
4085 case glslang::EOpVectorEqual:
4086 case glslang::EOpVectorNotEqual:
4087 comparison = true;
4088 break;
4089 default:
4090 break;
4091 }
4092
John Kessenich7c1aa102015-10-15 13:29:11 -06004093 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004094 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004095 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07004096 if (builder.isMatrix(left) || builder.isMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004097 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004098
4099 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004100 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004101 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004102
qining25262b32016-05-06 17:25:16 -04004103 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004104 builder.addDecoration(result, decorations.noContraction);
4105 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004106 }
4107
4108 if (! comparison)
4109 return 0;
4110
John Kessenich7c1aa102015-10-15 13:29:11 -06004111 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004112
John Kessenich4583b612016-08-07 19:14:22 -06004113 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004114 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4115 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
4116 return result;
4117 }
John Kessenich140f3df2015-06-26 16:58:36 -06004118
4119 switch (op) {
4120 case glslang::EOpLessThan:
4121 if (isFloat)
4122 binOp = spv::OpFOrdLessThan;
4123 else if (isUnsigned)
4124 binOp = spv::OpULessThan;
4125 else
4126 binOp = spv::OpSLessThan;
4127 break;
4128 case glslang::EOpGreaterThan:
4129 if (isFloat)
4130 binOp = spv::OpFOrdGreaterThan;
4131 else if (isUnsigned)
4132 binOp = spv::OpUGreaterThan;
4133 else
4134 binOp = spv::OpSGreaterThan;
4135 break;
4136 case glslang::EOpLessThanEqual:
4137 if (isFloat)
4138 binOp = spv::OpFOrdLessThanEqual;
4139 else if (isUnsigned)
4140 binOp = spv::OpULessThanEqual;
4141 else
4142 binOp = spv::OpSLessThanEqual;
4143 break;
4144 case glslang::EOpGreaterThanEqual:
4145 if (isFloat)
4146 binOp = spv::OpFOrdGreaterThanEqual;
4147 else if (isUnsigned)
4148 binOp = spv::OpUGreaterThanEqual;
4149 else
4150 binOp = spv::OpSGreaterThanEqual;
4151 break;
4152 case glslang::EOpEqual:
4153 case glslang::EOpVectorEqual:
4154 if (isFloat)
4155 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004156 else if (isBool)
4157 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004158 else
4159 binOp = spv::OpIEqual;
4160 break;
4161 case glslang::EOpNotEqual:
4162 case glslang::EOpVectorNotEqual:
4163 if (isFloat)
4164 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004165 else if (isBool)
4166 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004167 else
4168 binOp = spv::OpINotEqual;
4169 break;
4170 default:
4171 break;
4172 }
4173
qining25262b32016-05-06 17:25:16 -04004174 if (binOp != spv::OpNop) {
4175 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004176 builder.addDecoration(result, decorations.noContraction);
4177 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004178 }
John Kessenich140f3df2015-06-26 16:58:36 -06004179
4180 return 0;
4181}
4182
John Kessenich04bb8a02015-12-12 12:28:14 -07004183//
4184// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
4185// These can be any of:
4186//
4187// matrix * scalar
4188// scalar * matrix
4189// matrix * matrix linear algebraic
4190// matrix * vector
4191// vector * matrix
4192// matrix * matrix componentwise
4193// matrix op matrix op in {+, -, /}
4194// matrix op scalar op in {+, -, /}
4195// scalar op matrix op in {+, -, /}
4196//
John Kessenichead86222018-03-28 18:01:20 -06004197spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4198 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07004199{
4200 bool firstClass = true;
4201
4202 // First, handle first-class matrix operations (* and matrix/scalar)
4203 switch (op) {
4204 case spv::OpFDiv:
4205 if (builder.isMatrix(left) && builder.isScalar(right)) {
4206 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01004207 spv::Id resultType = builder.getTypeId(right);
4208 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07004209 op = spv::OpMatrixTimesScalar;
4210 } else
4211 firstClass = false;
4212 break;
4213 case spv::OpMatrixTimesScalar:
4214 if (builder.isMatrix(right))
4215 std::swap(left, right);
4216 assert(builder.isScalar(right));
4217 break;
4218 case spv::OpVectorTimesMatrix:
4219 assert(builder.isVector(left));
4220 assert(builder.isMatrix(right));
4221 break;
4222 case spv::OpMatrixTimesVector:
4223 assert(builder.isMatrix(left));
4224 assert(builder.isVector(right));
4225 break;
4226 case spv::OpMatrixTimesMatrix:
4227 assert(builder.isMatrix(left));
4228 assert(builder.isMatrix(right));
4229 break;
4230 default:
4231 firstClass = false;
4232 break;
4233 }
4234
qining25262b32016-05-06 17:25:16 -04004235 if (firstClass) {
4236 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004237 builder.addDecoration(result, decorations.noContraction);
4238 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004239 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004240
LoopDawg592860c2016-06-09 08:57:35 -06004241 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004242 // The result type of all of them is the same type as the (a) matrix operand.
4243 // The algorithm is to:
4244 // - break the matrix(es) into vectors
4245 // - smear any scalar to a vector
4246 // - do vector operations
4247 // - make a matrix out the vector results
4248 switch (op) {
4249 case spv::OpFAdd:
4250 case spv::OpFSub:
4251 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004252 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004253 case spv::OpFMul:
4254 {
4255 // one time set up...
4256 bool leftMat = builder.isMatrix(left);
4257 bool rightMat = builder.isMatrix(right);
4258 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4259 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4260 spv::Id scalarType = builder.getScalarTypeId(typeId);
4261 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4262 std::vector<spv::Id> results;
4263 spv::Id smearVec = spv::NoResult;
4264 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06004265 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004266 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06004267 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004268
4269 // do each vector op
4270 for (unsigned int c = 0; c < numCols; ++c) {
4271 std::vector<unsigned int> indexes;
4272 indexes.push_back(c);
4273 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4274 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004275 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06004276 builder.addDecoration(result, decorations.noContraction);
4277 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004278 }
4279
4280 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004281 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
4282 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07004283 }
4284 default:
4285 assert(0);
4286 return spv::NoResult;
4287 }
4288}
4289
John Kessenichead86222018-03-28 18:01:20 -06004290spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
4291 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004292{
4293 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004294 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004295 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07004296 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4297 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004298
4299 switch (op) {
4300 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004301 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004302 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004303 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06004304 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004305 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004306 unaryOp = spv::OpSNegate;
4307 break;
4308
4309 case glslang::EOpLogicalNot:
4310 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004311 unaryOp = spv::OpLogicalNot;
4312 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004313 case glslang::EOpBitwiseNot:
4314 unaryOp = spv::OpNot;
4315 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004316
John Kessenich140f3df2015-06-26 16:58:36 -06004317 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004318 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004319 break;
4320 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004321 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004322 break;
4323 case glslang::EOpTranspose:
4324 unaryOp = spv::OpTranspose;
4325 break;
4326
4327 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004328 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004329 break;
4330 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004331 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004332 break;
4333 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004334 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004335 break;
4336 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004337 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004338 break;
4339 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004340 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004341 break;
4342 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004343 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004344 break;
4345 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004346 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004347 break;
4348 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004349 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004350 break;
4351
4352 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004353 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004354 break;
4355 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004356 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004357 break;
4358 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004359 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004360 break;
4361 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004362 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004363 break;
4364 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004365 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004366 break;
4367 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004368 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004369 break;
4370
4371 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004372 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004373 break;
4374 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004375 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004376 break;
4377
4378 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004379 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004380 break;
4381 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004382 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004383 break;
4384 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004385 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004386 break;
4387 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004388 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004389 break;
4390 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004391 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004392 break;
4393 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004394 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004395 break;
4396
4397 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004398 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004399 break;
4400 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004401 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004402 break;
4403 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004404 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004405 break;
4406 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004407 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004408 break;
4409 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004410 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004411 break;
4412 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004413 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004414 break;
4415
4416 case glslang::EOpIsNan:
4417 unaryOp = spv::OpIsNan;
4418 break;
4419 case glslang::EOpIsInf:
4420 unaryOp = spv::OpIsInf;
4421 break;
LoopDawg592860c2016-06-09 08:57:35 -06004422 case glslang::EOpIsFinite:
4423 unaryOp = spv::OpIsFinite;
4424 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004425
Rex Xucbc426e2015-12-15 16:03:10 +08004426 case glslang::EOpFloatBitsToInt:
4427 case glslang::EOpFloatBitsToUint:
4428 case glslang::EOpIntBitsToFloat:
4429 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004430 case glslang::EOpDoubleBitsToInt64:
4431 case glslang::EOpDoubleBitsToUint64:
4432 case glslang::EOpInt64BitsToDouble:
4433 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004434 case glslang::EOpFloat16BitsToInt16:
4435 case glslang::EOpFloat16BitsToUint16:
4436 case glslang::EOpInt16BitsToFloat16:
4437 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08004438 unaryOp = spv::OpBitcast;
4439 break;
4440
John Kessenich140f3df2015-06-26 16:58:36 -06004441 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004442 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004443 break;
4444 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004445 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004446 break;
4447 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004448 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004449 break;
4450 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004451 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004452 break;
4453 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004454 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004455 break;
4456 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004457 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004458 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004459 case glslang::EOpPackSnorm4x8:
4460 libCall = spv::GLSLstd450PackSnorm4x8;
4461 break;
4462 case glslang::EOpUnpackSnorm4x8:
4463 libCall = spv::GLSLstd450UnpackSnorm4x8;
4464 break;
4465 case glslang::EOpPackUnorm4x8:
4466 libCall = spv::GLSLstd450PackUnorm4x8;
4467 break;
4468 case glslang::EOpUnpackUnorm4x8:
4469 libCall = spv::GLSLstd450UnpackUnorm4x8;
4470 break;
4471 case glslang::EOpPackDouble2x32:
4472 libCall = spv::GLSLstd450PackDouble2x32;
4473 break;
4474 case glslang::EOpUnpackDouble2x32:
4475 libCall = spv::GLSLstd450UnpackDouble2x32;
4476 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004477
Rex Xu8ff43de2016-04-22 16:51:45 +08004478 case glslang::EOpPackInt2x32:
4479 case glslang::EOpUnpackInt2x32:
4480 case glslang::EOpPackUint2x32:
4481 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07004482 case glslang::EOpPack16:
4483 case glslang::EOpPack32:
4484 case glslang::EOpPack64:
4485 case glslang::EOpUnpack32:
4486 case glslang::EOpUnpack16:
4487 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08004488 case glslang::EOpPackInt2x16:
4489 case glslang::EOpUnpackInt2x16:
4490 case glslang::EOpPackUint2x16:
4491 case glslang::EOpUnpackUint2x16:
4492 case glslang::EOpPackInt4x16:
4493 case glslang::EOpUnpackInt4x16:
4494 case glslang::EOpPackUint4x16:
4495 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004496 case glslang::EOpPackFloat2x16:
4497 case glslang::EOpUnpackFloat2x16:
4498 unaryOp = spv::OpBitcast;
4499 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004500
John Kessenich140f3df2015-06-26 16:58:36 -06004501 case glslang::EOpDPdx:
4502 unaryOp = spv::OpDPdx;
4503 break;
4504 case glslang::EOpDPdy:
4505 unaryOp = spv::OpDPdy;
4506 break;
4507 case glslang::EOpFwidth:
4508 unaryOp = spv::OpFwidth;
4509 break;
4510 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004511 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004512 unaryOp = spv::OpDPdxFine;
4513 break;
4514 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004515 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004516 unaryOp = spv::OpDPdyFine;
4517 break;
4518 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004519 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004520 unaryOp = spv::OpFwidthFine;
4521 break;
4522 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004523 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004524 unaryOp = spv::OpDPdxCoarse;
4525 break;
4526 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004527 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004528 unaryOp = spv::OpDPdyCoarse;
4529 break;
4530 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004531 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004532 unaryOp = spv::OpFwidthCoarse;
4533 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004534 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004535 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004536 libCall = spv::GLSLstd450InterpolateAtCentroid;
4537 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004538 case glslang::EOpAny:
4539 unaryOp = spv::OpAny;
4540 break;
4541 case glslang::EOpAll:
4542 unaryOp = spv::OpAll;
4543 break;
4544
4545 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004546 if (isFloat)
4547 libCall = spv::GLSLstd450FAbs;
4548 else
4549 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004550 break;
4551 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004552 if (isFloat)
4553 libCall = spv::GLSLstd450FSign;
4554 else
4555 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004556 break;
4557
John Kessenichfc51d282015-08-19 13:34:18 -06004558 case glslang::EOpAtomicCounterIncrement:
4559 case glslang::EOpAtomicCounterDecrement:
4560 case glslang::EOpAtomicCounter:
4561 {
4562 // Handle all of the atomics in one place, in createAtomicOperation()
4563 std::vector<spv::Id> operands;
4564 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06004565 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004566 }
4567
John Kessenichfc51d282015-08-19 13:34:18 -06004568 case glslang::EOpBitFieldReverse:
4569 unaryOp = spv::OpBitReverse;
4570 break;
4571 case glslang::EOpBitCount:
4572 unaryOp = spv::OpBitCount;
4573 break;
4574 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004575 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004576 break;
4577 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004578 if (isUnsigned)
4579 libCall = spv::GLSLstd450FindUMsb;
4580 else
4581 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004582 break;
4583
Rex Xu574ab042016-04-14 16:53:07 +08004584 case glslang::EOpBallot:
4585 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004586 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004587 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004588 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004589#ifdef AMD_EXTENSIONS
4590 case glslang::EOpMinInvocations:
4591 case glslang::EOpMaxInvocations:
4592 case glslang::EOpAddInvocations:
4593 case glslang::EOpMinInvocationsNonUniform:
4594 case glslang::EOpMaxInvocationsNonUniform:
4595 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004596 case glslang::EOpMinInvocationsInclusiveScan:
4597 case glslang::EOpMaxInvocationsInclusiveScan:
4598 case glslang::EOpAddInvocationsInclusiveScan:
4599 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4600 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4601 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4602 case glslang::EOpMinInvocationsExclusiveScan:
4603 case glslang::EOpMaxInvocationsExclusiveScan:
4604 case glslang::EOpAddInvocationsExclusiveScan:
4605 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4606 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4607 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004608#endif
Rex Xu51596642016-09-21 18:56:12 +08004609 {
4610 std::vector<spv::Id> operands;
4611 operands.push_back(operand);
4612 return createInvocationsOperation(op, typeId, operands, typeProxy);
4613 }
John Kessenich66011cb2018-03-06 16:12:04 -07004614 case glslang::EOpSubgroupAll:
4615 case glslang::EOpSubgroupAny:
4616 case glslang::EOpSubgroupAllEqual:
4617 case glslang::EOpSubgroupBroadcastFirst:
4618 case glslang::EOpSubgroupBallot:
4619 case glslang::EOpSubgroupInverseBallot:
4620 case glslang::EOpSubgroupBallotBitCount:
4621 case glslang::EOpSubgroupBallotInclusiveBitCount:
4622 case glslang::EOpSubgroupBallotExclusiveBitCount:
4623 case glslang::EOpSubgroupBallotFindLSB:
4624 case glslang::EOpSubgroupBallotFindMSB:
4625 case glslang::EOpSubgroupAdd:
4626 case glslang::EOpSubgroupMul:
4627 case glslang::EOpSubgroupMin:
4628 case glslang::EOpSubgroupMax:
4629 case glslang::EOpSubgroupAnd:
4630 case glslang::EOpSubgroupOr:
4631 case glslang::EOpSubgroupXor:
4632 case glslang::EOpSubgroupInclusiveAdd:
4633 case glslang::EOpSubgroupInclusiveMul:
4634 case glslang::EOpSubgroupInclusiveMin:
4635 case glslang::EOpSubgroupInclusiveMax:
4636 case glslang::EOpSubgroupInclusiveAnd:
4637 case glslang::EOpSubgroupInclusiveOr:
4638 case glslang::EOpSubgroupInclusiveXor:
4639 case glslang::EOpSubgroupExclusiveAdd:
4640 case glslang::EOpSubgroupExclusiveMul:
4641 case glslang::EOpSubgroupExclusiveMin:
4642 case glslang::EOpSubgroupExclusiveMax:
4643 case glslang::EOpSubgroupExclusiveAnd:
4644 case glslang::EOpSubgroupExclusiveOr:
4645 case glslang::EOpSubgroupExclusiveXor:
4646 case glslang::EOpSubgroupQuadSwapHorizontal:
4647 case glslang::EOpSubgroupQuadSwapVertical:
4648 case glslang::EOpSubgroupQuadSwapDiagonal: {
4649 std::vector<spv::Id> operands;
4650 operands.push_back(operand);
4651 return createSubgroupOperation(op, typeId, operands, typeProxy);
4652 }
Rex Xu9d93a232016-05-05 12:30:44 +08004653#ifdef AMD_EXTENSIONS
4654 case glslang::EOpMbcnt:
4655 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4656 libCall = spv::MbcntAMD;
4657 break;
4658
4659 case glslang::EOpCubeFaceIndex:
4660 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4661 libCall = spv::CubeFaceIndexAMD;
4662 break;
4663
4664 case glslang::EOpCubeFaceCoord:
4665 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4666 libCall = spv::CubeFaceCoordAMD;
4667 break;
4668#endif
Rex Xu338b1852016-05-05 20:38:33 +08004669
John Kessenich140f3df2015-06-26 16:58:36 -06004670 default:
4671 return 0;
4672 }
4673
4674 spv::Id id;
4675 if (libCall >= 0) {
4676 std::vector<spv::Id> args;
4677 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004678 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004679 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004680 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004681 }
John Kessenich140f3df2015-06-26 16:58:36 -06004682
John Kessenichead86222018-03-28 18:01:20 -06004683 builder.addDecoration(id, decorations.noContraction);
4684 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004685}
4686
John Kessenich7a53f762016-01-20 11:19:27 -07004687// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06004688spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4689 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07004690{
4691 // Handle unary operations vector by vector.
4692 // The result type is the same type as the original type.
4693 // The algorithm is to:
4694 // - break the matrix into vectors
4695 // - apply the operation to each vector
4696 // - make a matrix out the vector results
4697
4698 // get the types sorted out
4699 int numCols = builder.getNumColumns(operand);
4700 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004701 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4702 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004703 std::vector<spv::Id> results;
4704
4705 // do each vector op
4706 for (int c = 0; c < numCols; ++c) {
4707 std::vector<unsigned int> indexes;
4708 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004709 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4710 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06004711 builder.addDecoration(destVec, decorations.noContraction);
4712 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004713 }
4714
4715 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004716 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
4717 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07004718}
4719
John Kessenich66011cb2018-03-06 16:12:04 -07004720spv::Id TGlslangToSpvTraverser::createConversionOperation(glslang::TOperator op, spv::Id operand, int vectorSize)
4721{
4722 spv::Op convOp = spv::OpNop;
4723 spv::Id type = 0;
4724
4725 spv::Id result = 0;
4726
4727 switch(op) {
4728 case glslang::EOpConvInt8ToUint16:
4729 convOp = spv::OpSConvert;
4730 type = builder.makeIntType(16);
4731 break;
4732 case glslang::EOpConvInt8ToUint:
4733 convOp = spv::OpSConvert;
4734 type = builder.makeIntType(32);
4735 break;
4736 case glslang::EOpConvInt8ToUint64:
4737 convOp = spv::OpSConvert;
4738 type = builder.makeIntType(64);
4739 break;
4740 case glslang::EOpConvInt16ToUint8:
4741 convOp = spv::OpSConvert;
4742 type = builder.makeIntType(8);
4743 break;
4744 case glslang::EOpConvInt16ToUint:
4745 convOp = spv::OpSConvert;
4746 type = builder.makeIntType(32);
4747 break;
4748 case glslang::EOpConvInt16ToUint64:
4749 convOp = spv::OpSConvert;
4750 type = builder.makeIntType(64);
4751 break;
4752 case glslang::EOpConvIntToUint8:
4753 convOp = spv::OpSConvert;
4754 type = builder.makeIntType(8);
4755 break;
4756 case glslang::EOpConvIntToUint16:
4757 convOp = spv::OpSConvert;
4758 type = builder.makeIntType(16);
4759 break;
4760 case glslang::EOpConvIntToUint64:
4761 convOp = spv::OpSConvert;
4762 type = builder.makeIntType(64);
4763 break;
4764 case glslang::EOpConvInt64ToUint8:
4765 convOp = spv::OpSConvert;
4766 type = builder.makeIntType(8);
4767 break;
4768 case glslang::EOpConvInt64ToUint16:
4769 convOp = spv::OpSConvert;
4770 type = builder.makeIntType(16);
4771 break;
4772 case glslang::EOpConvInt64ToUint:
4773 convOp = spv::OpSConvert;
4774 type = builder.makeIntType(32);
4775 break;
4776 case glslang::EOpConvUint8ToInt16:
4777 convOp = spv::OpUConvert;
4778 type = builder.makeIntType(16);
4779 break;
4780 case glslang::EOpConvUint8ToInt:
4781 convOp = spv::OpUConvert;
4782 type = builder.makeIntType(32);
4783 break;
4784 case glslang::EOpConvUint8ToInt64:
4785 convOp = spv::OpUConvert;
4786 type = builder.makeIntType(64);
4787 break;
4788 case glslang::EOpConvUint16ToInt8:
4789 convOp = spv::OpUConvert;
4790 type = builder.makeIntType(8);
4791 break;
4792 case glslang::EOpConvUint16ToInt:
4793 convOp = spv::OpUConvert;
4794 type = builder.makeIntType(32);
4795 break;
4796 case glslang::EOpConvUint16ToInt64:
4797 convOp = spv::OpUConvert;
4798 type = builder.makeIntType(64);
4799 break;
4800 case glslang::EOpConvUintToInt8:
4801 convOp = spv::OpUConvert;
4802 type = builder.makeIntType(8);
4803 break;
4804 case glslang::EOpConvUintToInt16:
4805 convOp = spv::OpUConvert;
4806 type = builder.makeIntType(16);
4807 break;
4808 case glslang::EOpConvUintToInt64:
4809 convOp = spv::OpUConvert;
4810 type = builder.makeIntType(64);
4811 break;
4812 case glslang::EOpConvUint64ToInt8:
4813 convOp = spv::OpUConvert;
4814 type = builder.makeIntType(8);
4815 break;
4816 case glslang::EOpConvUint64ToInt16:
4817 convOp = spv::OpUConvert;
4818 type = builder.makeIntType(16);
4819 break;
4820 case glslang::EOpConvUint64ToInt:
4821 convOp = spv::OpUConvert;
4822 type = builder.makeIntType(32);
4823 break;
4824
4825 default:
4826 assert(false && "Default missing");
4827 break;
4828 }
4829
4830 if (vectorSize > 0)
4831 type = builder.makeVectorType(type, vectorSize);
4832
4833 result = builder.createUnaryOp(convOp, type, operand);
4834 return result;
4835}
4836
John Kessenichead86222018-03-28 18:01:20 -06004837spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
4838 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004839{
4840 spv::Op convOp = spv::OpNop;
4841 spv::Id zero = 0;
4842 spv::Id one = 0;
4843
4844 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4845
4846 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07004847 case glslang::EOpConvInt8ToBool:
4848 case glslang::EOpConvUint8ToBool:
4849 zero = builder.makeUint8Constant(0);
4850 zero = makeSmearedConstant(zero, vectorSize);
4851 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08004852 case glslang::EOpConvInt16ToBool:
4853 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07004854 zero = builder.makeUint16Constant(0);
4855 zero = makeSmearedConstant(zero, vectorSize);
4856 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4857 case glslang::EOpConvIntToBool:
4858 case glslang::EOpConvUintToBool:
4859 zero = builder.makeUintConstant(0);
4860 zero = makeSmearedConstant(zero, vectorSize);
4861 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4862 case glslang::EOpConvInt64ToBool:
4863 case glslang::EOpConvUint64ToBool:
4864 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004865 zero = makeSmearedConstant(zero, vectorSize);
4866 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4867
4868 case glslang::EOpConvFloatToBool:
4869 zero = builder.makeFloatConstant(0.0F);
4870 zero = makeSmearedConstant(zero, vectorSize);
4871 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4872
4873 case glslang::EOpConvDoubleToBool:
4874 zero = builder.makeDoubleConstant(0.0);
4875 zero = makeSmearedConstant(zero, vectorSize);
4876 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4877
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004878 case glslang::EOpConvFloat16ToBool:
4879 zero = builder.makeFloat16Constant(0.0F);
4880 zero = makeSmearedConstant(zero, vectorSize);
4881 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004882
John Kessenich140f3df2015-06-26 16:58:36 -06004883 case glslang::EOpConvBoolToFloat:
4884 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004885 zero = builder.makeFloatConstant(0.0F);
4886 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004887 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004888
John Kessenich140f3df2015-06-26 16:58:36 -06004889 case glslang::EOpConvBoolToDouble:
4890 convOp = spv::OpSelect;
4891 zero = builder.makeDoubleConstant(0.0);
4892 one = builder.makeDoubleConstant(1.0);
4893 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004894
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004895 case glslang::EOpConvBoolToFloat16:
4896 convOp = spv::OpSelect;
4897 zero = builder.makeFloat16Constant(0.0F);
4898 one = builder.makeFloat16Constant(1.0F);
4899 break;
John Kessenich66011cb2018-03-06 16:12:04 -07004900
4901 case glslang::EOpConvBoolToInt8:
4902 zero = builder.makeInt8Constant(0);
4903 one = builder.makeInt8Constant(1);
4904 convOp = spv::OpSelect;
4905 break;
4906
4907 case glslang::EOpConvBoolToUint8:
4908 zero = builder.makeUint8Constant(0);
4909 one = builder.makeUint8Constant(1);
4910 convOp = spv::OpSelect;
4911 break;
4912
4913 case glslang::EOpConvBoolToInt16:
4914 zero = builder.makeInt16Constant(0);
4915 one = builder.makeInt16Constant(1);
4916 convOp = spv::OpSelect;
4917 break;
4918
4919 case glslang::EOpConvBoolToUint16:
4920 zero = builder.makeUint16Constant(0);
4921 one = builder.makeUint16Constant(1);
4922 convOp = spv::OpSelect;
4923 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004924
John Kessenich140f3df2015-06-26 16:58:36 -06004925 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004926 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004927 if (op == glslang::EOpConvBoolToInt64)
4928 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08004929 else
4930 zero = builder.makeIntConstant(0);
4931
4932 if (op == glslang::EOpConvBoolToInt64)
4933 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08004934 else
4935 one = builder.makeIntConstant(1);
4936
John Kessenich140f3df2015-06-26 16:58:36 -06004937 convOp = spv::OpSelect;
4938 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004939
John Kessenich140f3df2015-06-26 16:58:36 -06004940 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004941 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004942 if (op == glslang::EOpConvBoolToUint64)
4943 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08004944 else
4945 zero = builder.makeUintConstant(0);
4946
4947 if (op == glslang::EOpConvBoolToUint64)
4948 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08004949 else
4950 one = builder.makeUintConstant(1);
4951
John Kessenich140f3df2015-06-26 16:58:36 -06004952 convOp = spv::OpSelect;
4953 break;
4954
John Kessenich66011cb2018-03-06 16:12:04 -07004955 case glslang::EOpConvInt8ToFloat16:
4956 case glslang::EOpConvInt8ToFloat:
4957 case glslang::EOpConvInt8ToDouble:
4958 case glslang::EOpConvInt16ToFloat16:
4959 case glslang::EOpConvInt16ToFloat:
4960 case glslang::EOpConvInt16ToDouble:
4961 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06004962 case glslang::EOpConvIntToFloat:
4963 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004964 case glslang::EOpConvInt64ToFloat:
4965 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004966 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06004967 convOp = spv::OpConvertSToF;
4968 break;
4969
John Kessenich66011cb2018-03-06 16:12:04 -07004970 case glslang::EOpConvUint8ToFloat16:
4971 case glslang::EOpConvUint8ToFloat:
4972 case glslang::EOpConvUint8ToDouble:
4973 case glslang::EOpConvUint16ToFloat16:
4974 case glslang::EOpConvUint16ToFloat:
4975 case glslang::EOpConvUint16ToDouble:
4976 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06004977 case glslang::EOpConvUintToFloat:
4978 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004979 case glslang::EOpConvUint64ToFloat:
4980 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004981 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06004982 convOp = spv::OpConvertUToF;
4983 break;
4984
4985 case glslang::EOpConvDoubleToFloat:
4986 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004987 case glslang::EOpConvDoubleToFloat16:
4988 case glslang::EOpConvFloat16ToDouble:
4989 case glslang::EOpConvFloatToFloat16:
4990 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06004991 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004992 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06004993 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004994 break;
4995
John Kessenich66011cb2018-03-06 16:12:04 -07004996 case glslang::EOpConvFloat16ToInt8:
4997 case glslang::EOpConvFloatToInt8:
4998 case glslang::EOpConvDoubleToInt8:
4999 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005000 case glslang::EOpConvFloatToInt16:
5001 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005002 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005003 case glslang::EOpConvFloatToInt:
5004 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005005 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005006 case glslang::EOpConvFloatToInt64:
5007 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005008 convOp = spv::OpConvertFToS;
5009 break;
5010
John Kessenich66011cb2018-03-06 16:12:04 -07005011 case glslang::EOpConvUint8ToInt8:
5012 case glslang::EOpConvInt8ToUint8:
5013 case glslang::EOpConvUint16ToInt16:
5014 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005015 case glslang::EOpConvUintToInt:
5016 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005017 case glslang::EOpConvUint64ToInt64:
5018 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005019 if (builder.isInSpecConstCodeGenMode()) {
5020 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005021 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5022 zero = builder.makeUint8Constant(0);
5023 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005024 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005025 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5026 zero = builder.makeUint64Constant(0);
5027 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005028 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005029 }
qining189b2032016-04-12 23:16:20 -04005030 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005031 // Use OpIAdd, instead of OpBitcast to do the conversion when
5032 // generating for OpSpecConstantOp instruction.
5033 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5034 }
5035 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005036 convOp = spv::OpBitcast;
5037 break;
5038
John Kessenich66011cb2018-03-06 16:12:04 -07005039 case glslang::EOpConvFloat16ToUint8:
5040 case glslang::EOpConvFloatToUint8:
5041 case glslang::EOpConvDoubleToUint8:
5042 case glslang::EOpConvFloat16ToUint16:
5043 case glslang::EOpConvFloatToUint16:
5044 case glslang::EOpConvDoubleToUint16:
5045 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005046 case glslang::EOpConvFloatToUint:
5047 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005048 case glslang::EOpConvFloatToUint64:
5049 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005050 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005051 convOp = spv::OpConvertFToU;
5052 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005053
John Kessenich66011cb2018-03-06 16:12:04 -07005054 case glslang::EOpConvInt8ToInt16:
5055 case glslang::EOpConvInt8ToInt:
5056 case glslang::EOpConvInt8ToInt64:
5057 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005058 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005059 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005060 case glslang::EOpConvIntToInt8:
5061 case glslang::EOpConvIntToInt16:
5062 case glslang::EOpConvIntToInt64:
5063 case glslang::EOpConvInt64ToInt8:
5064 case glslang::EOpConvInt64ToInt16:
5065 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005066 convOp = spv::OpSConvert;
5067 break;
5068
John Kessenich66011cb2018-03-06 16:12:04 -07005069 case glslang::EOpConvUint8ToUint16:
5070 case glslang::EOpConvUint8ToUint:
5071 case glslang::EOpConvUint8ToUint64:
5072 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005073 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005074 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005075 case glslang::EOpConvUintToUint8:
5076 case glslang::EOpConvUintToUint16:
5077 case glslang::EOpConvUintToUint64:
5078 case glslang::EOpConvUint64ToUint8:
5079 case glslang::EOpConvUint64ToUint16:
5080 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005081 convOp = spv::OpUConvert;
5082 break;
5083
John Kessenich66011cb2018-03-06 16:12:04 -07005084 case glslang::EOpConvInt8ToUint16:
5085 case glslang::EOpConvInt8ToUint:
5086 case glslang::EOpConvInt8ToUint64:
5087 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005088 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005089 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005090 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005091 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005092 case glslang::EOpConvIntToUint64:
5093 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005094 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005095 case glslang::EOpConvInt64ToUint:
5096 case glslang::EOpConvUint8ToInt16:
5097 case glslang::EOpConvUint8ToInt:
5098 case glslang::EOpConvUint8ToInt64:
5099 case glslang::EOpConvUint16ToInt8:
5100 case glslang::EOpConvUint16ToInt:
5101 case glslang::EOpConvUint16ToInt64:
5102 case glslang::EOpConvUintToInt8:
5103 case glslang::EOpConvUintToInt16:
5104 case glslang::EOpConvUintToInt64:
5105 case glslang::EOpConvUint64ToInt8:
5106 case glslang::EOpConvUint64ToInt16:
5107 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005108 // OpSConvert/OpUConvert + OpBitCast
John Kessenich66011cb2018-03-06 16:12:04 -07005109 operand = createConversionOperation(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005110
5111 if (builder.isInSpecConstCodeGenMode()) {
5112 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005113 switch(op) {
5114 case glslang::EOpConvInt16ToUint8:
5115 case glslang::EOpConvIntToUint8:
5116 case glslang::EOpConvInt64ToUint8:
5117 case glslang::EOpConvUint16ToInt8:
5118 case glslang::EOpConvUintToInt8:
5119 case glslang::EOpConvUint64ToInt8:
5120 zero = builder.makeUint8Constant(0);
5121 break;
5122 case glslang::EOpConvInt8ToUint16:
5123 case glslang::EOpConvIntToUint16:
5124 case glslang::EOpConvInt64ToUint16:
5125 case glslang::EOpConvUint8ToInt16:
5126 case glslang::EOpConvUintToInt16:
5127 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005128 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005129 break;
5130 case glslang::EOpConvInt8ToUint:
5131 case glslang::EOpConvInt16ToUint:
5132 case glslang::EOpConvInt64ToUint:
5133 case glslang::EOpConvUint8ToInt:
5134 case glslang::EOpConvUint16ToInt:
5135 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005136 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005137 break;
5138 case glslang::EOpConvInt8ToUint64:
5139 case glslang::EOpConvInt16ToUint64:
5140 case glslang::EOpConvIntToUint64:
5141 case glslang::EOpConvUint8ToInt64:
5142 case glslang::EOpConvUint16ToInt64:
5143 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005144 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005145 break;
5146 default:
5147 assert(false && "Default missing");
5148 break;
5149 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005150 zero = makeSmearedConstant(zero, vectorSize);
5151 // Use OpIAdd, instead of OpBitcast to do the conversion when
5152 // generating for OpSpecConstantOp instruction.
5153 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5154 }
5155 // For normal run-time conversion instruction, use OpBitcast.
5156 convOp = spv::OpBitcast;
5157 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005158 default:
5159 break;
5160 }
5161
5162 spv::Id result = 0;
5163 if (convOp == spv::OpNop)
5164 return result;
5165
5166 if (convOp == spv::OpSelect) {
5167 zero = makeSmearedConstant(zero, vectorSize);
5168 one = makeSmearedConstant(one, vectorSize);
5169 result = builder.createTriOp(convOp, destType, operand, one, zero);
5170 } else
5171 result = builder.createUnaryOp(convOp, destType, operand);
5172
John Kessenichead86222018-03-28 18:01:20 -06005173 result = builder.setPrecision(result, decorations.precision);
5174 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06005175}
5176
5177spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
5178{
5179 if (vectorSize == 0)
5180 return constant;
5181
5182 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
5183 std::vector<spv::Id> components;
5184 for (int c = 0; c < vectorSize; ++c)
5185 components.push_back(constant);
5186 return builder.makeCompositeConstant(vectorTypeId, components);
5187}
5188
John Kessenich426394d2015-07-23 10:22:48 -06005189// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07005190spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich426394d2015-07-23 10:22:48 -06005191{
5192 spv::Op opCode = spv::OpNop;
5193
5194 switch (op) {
5195 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08005196 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005197 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06005198 opCode = spv::OpAtomicIAdd;
5199 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06005200 case glslang::EOpAtomicCounterSubtract:
5201 opCode = spv::OpAtomicISub;
5202 break;
John Kessenich426394d2015-07-23 10:22:48 -06005203 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08005204 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005205 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08005206 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06005207 break;
5208 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08005209 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005210 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08005211 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06005212 break;
5213 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08005214 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005215 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06005216 opCode = spv::OpAtomicAnd;
5217 break;
5218 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08005219 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005220 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06005221 opCode = spv::OpAtomicOr;
5222 break;
5223 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08005224 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005225 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06005226 opCode = spv::OpAtomicXor;
5227 break;
5228 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08005229 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005230 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06005231 opCode = spv::OpAtomicExchange;
5232 break;
5233 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08005234 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005235 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06005236 opCode = spv::OpAtomicCompareExchange;
5237 break;
5238 case glslang::EOpAtomicCounterIncrement:
5239 opCode = spv::OpAtomicIIncrement;
5240 break;
5241 case glslang::EOpAtomicCounterDecrement:
5242 opCode = spv::OpAtomicIDecrement;
5243 break;
5244 case glslang::EOpAtomicCounter:
5245 opCode = spv::OpAtomicLoad;
5246 break;
5247 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005248 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06005249 break;
5250 }
5251
Rex Xue8fe8b02017-09-26 15:42:56 +08005252 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
5253 builder.addCapability(spv::CapabilityInt64Atomics);
5254
John Kessenich426394d2015-07-23 10:22:48 -06005255 // Sort out the operands
5256 // - mapping from glslang -> SPV
5257 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06005258 // - compare-exchange swaps the value and comparator
5259 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06005260 // - EOpAtomicCounterDecrement needs a post decrement
John Kessenich426394d2015-07-23 10:22:48 -06005261 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
5262 auto opIt = operands.begin(); // walk the glslang operands
5263 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08005264 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
5265 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
5266 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08005267 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
5268 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08005269 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06005270 spvAtomicOperands.push_back(*(opIt + 1));
5271 spvAtomicOperands.push_back(*opIt);
5272 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08005273 }
John Kessenich426394d2015-07-23 10:22:48 -06005274
John Kessenich3e60a6f2015-09-14 22:45:16 -06005275 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06005276 for (; opIt != operands.end(); ++opIt)
5277 spvAtomicOperands.push_back(*opIt);
5278
John Kessenich48d6e792017-10-06 21:21:48 -06005279 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
5280
5281 // GLSL and HLSL atomic-counter decrement return post-decrement value,
5282 // while SPIR-V returns pre-decrement value. Translate between these semantics.
5283 if (op == glslang::EOpAtomicCounterDecrement)
5284 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
5285
5286 return resultId;
John Kessenich426394d2015-07-23 10:22:48 -06005287}
5288
John Kessenich91cef522016-05-05 16:45:40 -06005289// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08005290spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06005291{
John Kessenich66011cb2018-03-06 16:12:04 -07005292 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5293 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08005294
Rex Xu51596642016-09-21 18:56:12 +08005295 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08005296 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08005297 spv::GroupOperation groupOperation = spv::GroupOperationMax;
5298
chaocf200da82016-12-20 12:44:35 -08005299 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
5300 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08005301 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
5302 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005303 } else if (op == glslang::EOpAnyInvocation ||
5304 op == glslang::EOpAllInvocations ||
5305 op == glslang::EOpAllInvocationsEqual) {
5306 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
5307 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08005308 } else {
5309 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04005310#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08005311 if (op == glslang::EOpMinInvocationsNonUniform ||
5312 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08005313 op == glslang::EOpAddInvocationsNonUniform ||
5314 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5315 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5316 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
5317 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
5318 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
5319 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08005320 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04005321#endif
Rex Xu51596642016-09-21 18:56:12 +08005322
5323 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08005324#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08005325 switch (op) {
5326 case glslang::EOpMinInvocations:
5327 case glslang::EOpMaxInvocations:
5328 case glslang::EOpAddInvocations:
5329 case glslang::EOpMinInvocationsNonUniform:
5330 case glslang::EOpMaxInvocationsNonUniform:
5331 case glslang::EOpAddInvocationsNonUniform:
5332 groupOperation = spv::GroupOperationReduce;
5333 spvGroupOperands.push_back(groupOperation);
5334 break;
5335 case glslang::EOpMinInvocationsInclusiveScan:
5336 case glslang::EOpMaxInvocationsInclusiveScan:
5337 case glslang::EOpAddInvocationsInclusiveScan:
5338 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5339 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5340 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5341 groupOperation = spv::GroupOperationInclusiveScan;
5342 spvGroupOperands.push_back(groupOperation);
5343 break;
5344 case glslang::EOpMinInvocationsExclusiveScan:
5345 case glslang::EOpMaxInvocationsExclusiveScan:
5346 case glslang::EOpAddInvocationsExclusiveScan:
5347 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5348 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5349 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5350 groupOperation = spv::GroupOperationExclusiveScan;
5351 spvGroupOperands.push_back(groupOperation);
5352 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07005353 default:
5354 break;
Rex Xu430ef402016-10-14 17:22:23 +08005355 }
Rex Xu9d93a232016-05-05 12:30:44 +08005356#endif
Rex Xu51596642016-09-21 18:56:12 +08005357 }
5358
5359 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
5360 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06005361
5362 switch (op) {
5363 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005364 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08005365 break;
John Kessenich91cef522016-05-05 16:45:40 -06005366 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005367 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08005368 break;
John Kessenich91cef522016-05-05 16:45:40 -06005369 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005370 opCode = spv::OpSubgroupAllEqualKHR;
5371 break;
Rex Xu51596642016-09-21 18:56:12 +08005372 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08005373 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08005374 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005375 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005376 break;
5377 case glslang::EOpReadFirstInvocation:
5378 opCode = spv::OpSubgroupFirstInvocationKHR;
5379 break;
5380 case glslang::EOpBallot:
5381 {
5382 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
5383 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
5384 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
5385 //
5386 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
5387 //
5388 spv::Id uintType = builder.makeUintType(32);
5389 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
5390 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
5391
5392 std::vector<spv::Id> components;
5393 components.push_back(builder.createCompositeExtract(result, uintType, 0));
5394 components.push_back(builder.createCompositeExtract(result, uintType, 1));
5395
5396 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
5397 return builder.createUnaryOp(spv::OpBitcast, typeId,
5398 builder.createCompositeConstruct(uvec2Type, components));
5399 }
5400
Rex Xu9d93a232016-05-05 12:30:44 +08005401#ifdef AMD_EXTENSIONS
5402 case glslang::EOpMinInvocations:
5403 case glslang::EOpMaxInvocations:
5404 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08005405 case glslang::EOpMinInvocationsInclusiveScan:
5406 case glslang::EOpMaxInvocationsInclusiveScan:
5407 case glslang::EOpAddInvocationsInclusiveScan:
5408 case glslang::EOpMinInvocationsExclusiveScan:
5409 case glslang::EOpMaxInvocationsExclusiveScan:
5410 case glslang::EOpAddInvocationsExclusiveScan:
5411 if (op == glslang::EOpMinInvocations ||
5412 op == glslang::EOpMinInvocationsInclusiveScan ||
5413 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005414 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005415 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005416 else {
5417 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005418 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005419 else
Rex Xu51596642016-09-21 18:56:12 +08005420 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005421 }
Rex Xu430ef402016-10-14 17:22:23 +08005422 } else if (op == glslang::EOpMaxInvocations ||
5423 op == glslang::EOpMaxInvocationsInclusiveScan ||
5424 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005425 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005426 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005427 else {
5428 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005429 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005430 else
Rex Xu51596642016-09-21 18:56:12 +08005431 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005432 }
5433 } else {
5434 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005435 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005436 else
Rex Xu51596642016-09-21 18:56:12 +08005437 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005438 }
5439
Rex Xu2bbbe062016-08-23 15:41:05 +08005440 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005441 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005442
5443 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005444 case glslang::EOpMinInvocationsNonUniform:
5445 case glslang::EOpMaxInvocationsNonUniform:
5446 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005447 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5448 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5449 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5450 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5451 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5452 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5453 if (op == glslang::EOpMinInvocationsNonUniform ||
5454 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5455 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005456 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005457 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005458 else {
5459 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005460 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005461 else
Rex Xu51596642016-09-21 18:56:12 +08005462 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005463 }
5464 }
Rex Xu430ef402016-10-14 17:22:23 +08005465 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5466 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5467 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005468 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005469 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005470 else {
5471 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005472 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005473 else
Rex Xu51596642016-09-21 18:56:12 +08005474 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005475 }
5476 }
5477 else {
5478 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005479 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005480 else
Rex Xu51596642016-09-21 18:56:12 +08005481 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005482 }
5483
Rex Xu2bbbe062016-08-23 15:41:05 +08005484 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005485 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005486
5487 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005488#endif
John Kessenich91cef522016-05-05 16:45:40 -06005489 default:
5490 logger->missingFunctionality("invocation operation");
5491 return spv::NoResult;
5492 }
Rex Xu51596642016-09-21 18:56:12 +08005493
5494 assert(opCode != spv::OpNop);
5495 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005496}
5497
Rex Xu2bbbe062016-08-23 15:41:05 +08005498// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005499spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005500{
Rex Xub7072052016-09-26 15:53:40 +08005501#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005502 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5503 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005504 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005505 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005506 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5507 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5508 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005509#else
5510 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5511 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005512 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5513 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005514#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005515
5516 // Handle group invocation operations scalar by scalar.
5517 // The result type is the same type as the original type.
5518 // The algorithm is to:
5519 // - break the vector into scalars
5520 // - apply the operation to each scalar
5521 // - make a vector out the scalar results
5522
5523 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005524 int numComponents = builder.getNumComponents(operands[0]);
5525 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005526 std::vector<spv::Id> results;
5527
5528 // do each scalar op
5529 for (int comp = 0; comp < numComponents; ++comp) {
5530 std::vector<unsigned int> indexes;
5531 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005532 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005533 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005534 if (op == spv::OpSubgroupReadInvocationKHR) {
5535 spvGroupOperands.push_back(scalar);
5536 spvGroupOperands.push_back(operands[1]);
5537 } else if (op == spv::OpGroupBroadcast) {
5538 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005539 spvGroupOperands.push_back(scalar);
5540 spvGroupOperands.push_back(operands[1]);
5541 } else {
chaocf200da82016-12-20 12:44:35 -08005542 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005543 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005544 spvGroupOperands.push_back(scalar);
5545 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005546
Rex Xub7072052016-09-26 15:53:40 +08005547 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005548 }
5549
5550 // put the pieces together
5551 return builder.createCompositeConstruct(typeId, results);
5552}
Rex Xu2bbbe062016-08-23 15:41:05 +08005553
John Kessenich66011cb2018-03-06 16:12:04 -07005554// Create subgroup invocation operations.
5555spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
5556{
5557 // Add the required capabilities.
5558 switch (op) {
5559 case glslang::EOpSubgroupElect:
5560 builder.addCapability(spv::CapabilityGroupNonUniform);
5561 break;
5562 case glslang::EOpSubgroupAll:
5563 case glslang::EOpSubgroupAny:
5564 case glslang::EOpSubgroupAllEqual:
5565 builder.addCapability(spv::CapabilityGroupNonUniform);
5566 builder.addCapability(spv::CapabilityGroupNonUniformVote);
5567 break;
5568 case glslang::EOpSubgroupBroadcast:
5569 case glslang::EOpSubgroupBroadcastFirst:
5570 case glslang::EOpSubgroupBallot:
5571 case glslang::EOpSubgroupInverseBallot:
5572 case glslang::EOpSubgroupBallotBitExtract:
5573 case glslang::EOpSubgroupBallotBitCount:
5574 case glslang::EOpSubgroupBallotInclusiveBitCount:
5575 case glslang::EOpSubgroupBallotExclusiveBitCount:
5576 case glslang::EOpSubgroupBallotFindLSB:
5577 case glslang::EOpSubgroupBallotFindMSB:
5578 builder.addCapability(spv::CapabilityGroupNonUniform);
5579 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
5580 break;
5581 case glslang::EOpSubgroupShuffle:
5582 case glslang::EOpSubgroupShuffleXor:
5583 builder.addCapability(spv::CapabilityGroupNonUniform);
5584 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
5585 break;
5586 case glslang::EOpSubgroupShuffleUp:
5587 case glslang::EOpSubgroupShuffleDown:
5588 builder.addCapability(spv::CapabilityGroupNonUniform);
5589 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
5590 break;
5591 case glslang::EOpSubgroupAdd:
5592 case glslang::EOpSubgroupMul:
5593 case glslang::EOpSubgroupMin:
5594 case glslang::EOpSubgroupMax:
5595 case glslang::EOpSubgroupAnd:
5596 case glslang::EOpSubgroupOr:
5597 case glslang::EOpSubgroupXor:
5598 case glslang::EOpSubgroupInclusiveAdd:
5599 case glslang::EOpSubgroupInclusiveMul:
5600 case glslang::EOpSubgroupInclusiveMin:
5601 case glslang::EOpSubgroupInclusiveMax:
5602 case glslang::EOpSubgroupInclusiveAnd:
5603 case glslang::EOpSubgroupInclusiveOr:
5604 case glslang::EOpSubgroupInclusiveXor:
5605 case glslang::EOpSubgroupExclusiveAdd:
5606 case glslang::EOpSubgroupExclusiveMul:
5607 case glslang::EOpSubgroupExclusiveMin:
5608 case glslang::EOpSubgroupExclusiveMax:
5609 case glslang::EOpSubgroupExclusiveAnd:
5610 case glslang::EOpSubgroupExclusiveOr:
5611 case glslang::EOpSubgroupExclusiveXor:
5612 builder.addCapability(spv::CapabilityGroupNonUniform);
5613 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
5614 break;
5615 case glslang::EOpSubgroupClusteredAdd:
5616 case glslang::EOpSubgroupClusteredMul:
5617 case glslang::EOpSubgroupClusteredMin:
5618 case glslang::EOpSubgroupClusteredMax:
5619 case glslang::EOpSubgroupClusteredAnd:
5620 case glslang::EOpSubgroupClusteredOr:
5621 case glslang::EOpSubgroupClusteredXor:
5622 builder.addCapability(spv::CapabilityGroupNonUniform);
5623 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
5624 break;
5625 case glslang::EOpSubgroupQuadBroadcast:
5626 case glslang::EOpSubgroupQuadSwapHorizontal:
5627 case glslang::EOpSubgroupQuadSwapVertical:
5628 case glslang::EOpSubgroupQuadSwapDiagonal:
5629 builder.addCapability(spv::CapabilityGroupNonUniform);
5630 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
5631 break;
5632 default: assert(0 && "Unhandled subgroup operation!");
5633 }
5634
5635 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
5636 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
5637 const bool isBool = typeProxy == glslang::EbtBool;
5638
5639 spv::Op opCode = spv::OpNop;
5640
5641 // Figure out which opcode to use.
5642 switch (op) {
5643 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
5644 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
5645 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
5646 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
5647 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
5648 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
5649 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
5650 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
5651 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
5652 case glslang::EOpSubgroupBallotBitCount:
5653 case glslang::EOpSubgroupBallotInclusiveBitCount:
5654 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
5655 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
5656 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
5657 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
5658 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
5659 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
5660 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
5661 case glslang::EOpSubgroupAdd:
5662 case glslang::EOpSubgroupInclusiveAdd:
5663 case glslang::EOpSubgroupExclusiveAdd:
5664 case glslang::EOpSubgroupClusteredAdd:
5665 if (isFloat) {
5666 opCode = spv::OpGroupNonUniformFAdd;
5667 } else {
5668 opCode = spv::OpGroupNonUniformIAdd;
5669 }
5670 break;
5671 case glslang::EOpSubgroupMul:
5672 case glslang::EOpSubgroupInclusiveMul:
5673 case glslang::EOpSubgroupExclusiveMul:
5674 case glslang::EOpSubgroupClusteredMul:
5675 if (isFloat) {
5676 opCode = spv::OpGroupNonUniformFMul;
5677 } else {
5678 opCode = spv::OpGroupNonUniformIMul;
5679 }
5680 break;
5681 case glslang::EOpSubgroupMin:
5682 case glslang::EOpSubgroupInclusiveMin:
5683 case glslang::EOpSubgroupExclusiveMin:
5684 case glslang::EOpSubgroupClusteredMin:
5685 if (isFloat) {
5686 opCode = spv::OpGroupNonUniformFMin;
5687 } else if (isUnsigned) {
5688 opCode = spv::OpGroupNonUniformUMin;
5689 } else {
5690 opCode = spv::OpGroupNonUniformSMin;
5691 }
5692 break;
5693 case glslang::EOpSubgroupMax:
5694 case glslang::EOpSubgroupInclusiveMax:
5695 case glslang::EOpSubgroupExclusiveMax:
5696 case glslang::EOpSubgroupClusteredMax:
5697 if (isFloat) {
5698 opCode = spv::OpGroupNonUniformFMax;
5699 } else if (isUnsigned) {
5700 opCode = spv::OpGroupNonUniformUMax;
5701 } else {
5702 opCode = spv::OpGroupNonUniformSMax;
5703 }
5704 break;
5705 case glslang::EOpSubgroupAnd:
5706 case glslang::EOpSubgroupInclusiveAnd:
5707 case glslang::EOpSubgroupExclusiveAnd:
5708 case glslang::EOpSubgroupClusteredAnd:
5709 if (isBool) {
5710 opCode = spv::OpGroupNonUniformLogicalAnd;
5711 } else {
5712 opCode = spv::OpGroupNonUniformBitwiseAnd;
5713 }
5714 break;
5715 case glslang::EOpSubgroupOr:
5716 case glslang::EOpSubgroupInclusiveOr:
5717 case glslang::EOpSubgroupExclusiveOr:
5718 case glslang::EOpSubgroupClusteredOr:
5719 if (isBool) {
5720 opCode = spv::OpGroupNonUniformLogicalOr;
5721 } else {
5722 opCode = spv::OpGroupNonUniformBitwiseOr;
5723 }
5724 break;
5725 case glslang::EOpSubgroupXor:
5726 case glslang::EOpSubgroupInclusiveXor:
5727 case glslang::EOpSubgroupExclusiveXor:
5728 case glslang::EOpSubgroupClusteredXor:
5729 if (isBool) {
5730 opCode = spv::OpGroupNonUniformLogicalXor;
5731 } else {
5732 opCode = spv::OpGroupNonUniformBitwiseXor;
5733 }
5734 break;
5735 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
5736 case glslang::EOpSubgroupQuadSwapHorizontal:
5737 case glslang::EOpSubgroupQuadSwapVertical:
5738 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
5739 default: assert(0 && "Unhandled subgroup operation!");
5740 }
5741
5742 std::vector<spv::Id> spvGroupOperands;
5743
5744 // Every operation begins with the Execution Scope operand.
5745 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
5746
5747 // Next, for all operations that use a Group Operation, push that as an operand.
5748 switch (op) {
5749 default: break;
5750 case glslang::EOpSubgroupBallotBitCount:
5751 case glslang::EOpSubgroupAdd:
5752 case glslang::EOpSubgroupMul:
5753 case glslang::EOpSubgroupMin:
5754 case glslang::EOpSubgroupMax:
5755 case glslang::EOpSubgroupAnd:
5756 case glslang::EOpSubgroupOr:
5757 case glslang::EOpSubgroupXor:
5758 spvGroupOperands.push_back(spv::GroupOperationReduce);
5759 break;
5760 case glslang::EOpSubgroupBallotInclusiveBitCount:
5761 case glslang::EOpSubgroupInclusiveAdd:
5762 case glslang::EOpSubgroupInclusiveMul:
5763 case glslang::EOpSubgroupInclusiveMin:
5764 case glslang::EOpSubgroupInclusiveMax:
5765 case glslang::EOpSubgroupInclusiveAnd:
5766 case glslang::EOpSubgroupInclusiveOr:
5767 case glslang::EOpSubgroupInclusiveXor:
5768 spvGroupOperands.push_back(spv::GroupOperationInclusiveScan);
5769 break;
5770 case glslang::EOpSubgroupBallotExclusiveBitCount:
5771 case glslang::EOpSubgroupExclusiveAdd:
5772 case glslang::EOpSubgroupExclusiveMul:
5773 case glslang::EOpSubgroupExclusiveMin:
5774 case glslang::EOpSubgroupExclusiveMax:
5775 case glslang::EOpSubgroupExclusiveAnd:
5776 case glslang::EOpSubgroupExclusiveOr:
5777 case glslang::EOpSubgroupExclusiveXor:
5778 spvGroupOperands.push_back(spv::GroupOperationExclusiveScan);
5779 break;
5780 case glslang::EOpSubgroupClusteredAdd:
5781 case glslang::EOpSubgroupClusteredMul:
5782 case glslang::EOpSubgroupClusteredMin:
5783 case glslang::EOpSubgroupClusteredMax:
5784 case glslang::EOpSubgroupClusteredAnd:
5785 case glslang::EOpSubgroupClusteredOr:
5786 case glslang::EOpSubgroupClusteredXor:
5787 spvGroupOperands.push_back(spv::GroupOperationClusteredReduce);
5788 break;
5789 }
5790
5791 // Push back the operands next.
5792 for (auto opIt : operands) {
5793 spvGroupOperands.push_back(opIt);
5794 }
5795
5796 // Some opcodes have additional operands.
5797 switch (op) {
5798 default: break;
5799 case glslang::EOpSubgroupQuadSwapHorizontal: spvGroupOperands.push_back(builder.makeUintConstant(0)); break;
5800 case glslang::EOpSubgroupQuadSwapVertical: spvGroupOperands.push_back(builder.makeUintConstant(1)); break;
5801 case glslang::EOpSubgroupQuadSwapDiagonal: spvGroupOperands.push_back(builder.makeUintConstant(2)); break;
5802 }
5803
5804 return builder.createOp(opCode, typeId, spvGroupOperands);
5805}
5806
John Kessenich5e4b1242015-08-06 22:53:06 -06005807spv::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 -06005808{
John Kessenich66011cb2018-03-06 16:12:04 -07005809 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5810 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06005811
John Kessenich140f3df2015-06-26 16:58:36 -06005812 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005813 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005814 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005815 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005816 spv::Id typeId0 = 0;
5817 if (consumedOperands > 0)
5818 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005819 spv::Id typeId1 = 0;
5820 if (consumedOperands > 1)
5821 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005822 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005823
5824 switch (op) {
5825 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005826 if (isFloat)
5827 libCall = spv::GLSLstd450FMin;
5828 else if (isUnsigned)
5829 libCall = spv::GLSLstd450UMin;
5830 else
5831 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005832 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005833 break;
5834 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06005835 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06005836 break;
5837 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06005838 if (isFloat)
5839 libCall = spv::GLSLstd450FMax;
5840 else if (isUnsigned)
5841 libCall = spv::GLSLstd450UMax;
5842 else
5843 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005844 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005845 break;
5846 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005847 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005848 break;
5849 case glslang::EOpDot:
5850 opCode = spv::OpDot;
5851 break;
5852 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005853 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005854 break;
5855
5856 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005857 if (isFloat)
5858 libCall = spv::GLSLstd450FClamp;
5859 else if (isUnsigned)
5860 libCall = spv::GLSLstd450UClamp;
5861 else
5862 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005863 builder.promoteScalar(precision, operands.front(), operands[1]);
5864 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005865 break;
5866 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005867 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5868 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005869 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005870 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005871 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005872 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005873 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005874 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005875 break;
5876 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005877 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005878 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005879 break;
5880 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005881 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005882 builder.promoteScalar(precision, operands[0], operands[2]);
5883 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005884 break;
5885
5886 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005887 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005888 break;
5889 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005890 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005891 break;
5892 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005893 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005894 break;
5895 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005896 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005897 break;
5898 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005899 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005900 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005901 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005902 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005903 libCall = spv::GLSLstd450InterpolateAtSample;
5904 break;
5905 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005906 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005907 libCall = spv::GLSLstd450InterpolateAtOffset;
5908 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005909 case glslang::EOpAddCarry:
5910 opCode = spv::OpIAddCarry;
5911 typeId = builder.makeStructResultType(typeId0, typeId0);
5912 consumedOperands = 2;
5913 break;
5914 case glslang::EOpSubBorrow:
5915 opCode = spv::OpISubBorrow;
5916 typeId = builder.makeStructResultType(typeId0, typeId0);
5917 consumedOperands = 2;
5918 break;
5919 case glslang::EOpUMulExtended:
5920 opCode = spv::OpUMulExtended;
5921 typeId = builder.makeStructResultType(typeId0, typeId0);
5922 consumedOperands = 2;
5923 break;
5924 case glslang::EOpIMulExtended:
5925 opCode = spv::OpSMulExtended;
5926 typeId = builder.makeStructResultType(typeId0, typeId0);
5927 consumedOperands = 2;
5928 break;
5929 case glslang::EOpBitfieldExtract:
5930 if (isUnsigned)
5931 opCode = spv::OpBitFieldUExtract;
5932 else
5933 opCode = spv::OpBitFieldSExtract;
5934 break;
5935 case glslang::EOpBitfieldInsert:
5936 opCode = spv::OpBitFieldInsert;
5937 break;
5938
5939 case glslang::EOpFma:
5940 libCall = spv::GLSLstd450Fma;
5941 break;
5942 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005943 {
5944 libCall = spv::GLSLstd450FrexpStruct;
5945 assert(builder.isPointerType(typeId1));
5946 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08005947 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08005948 if (builder.getNumComponents(operands[0]) == 1)
5949 frexpIntType = builder.makeIntegerType(width, true);
5950 else
5951 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5952 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5953 consumedOperands = 1;
5954 }
John Kessenich55e7d112015-11-15 21:33:39 -07005955 break;
5956 case glslang::EOpLdexp:
5957 libCall = spv::GLSLstd450Ldexp;
5958 break;
5959
Rex Xu574ab042016-04-14 16:53:07 +08005960 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005961 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005962
John Kessenich66011cb2018-03-06 16:12:04 -07005963 case glslang::EOpSubgroupBroadcast:
5964 case glslang::EOpSubgroupBallotBitExtract:
5965 case glslang::EOpSubgroupShuffle:
5966 case glslang::EOpSubgroupShuffleXor:
5967 case glslang::EOpSubgroupShuffleUp:
5968 case glslang::EOpSubgroupShuffleDown:
5969 case glslang::EOpSubgroupClusteredAdd:
5970 case glslang::EOpSubgroupClusteredMul:
5971 case glslang::EOpSubgroupClusteredMin:
5972 case glslang::EOpSubgroupClusteredMax:
5973 case glslang::EOpSubgroupClusteredAnd:
5974 case glslang::EOpSubgroupClusteredOr:
5975 case glslang::EOpSubgroupClusteredXor:
5976 case glslang::EOpSubgroupQuadBroadcast:
5977 return createSubgroupOperation(op, typeId, operands, typeProxy);
5978
Rex Xu9d93a232016-05-05 12:30:44 +08005979#ifdef AMD_EXTENSIONS
5980 case glslang::EOpSwizzleInvocations:
5981 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5982 libCall = spv::SwizzleInvocationsAMD;
5983 break;
5984 case glslang::EOpSwizzleInvocationsMasked:
5985 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5986 libCall = spv::SwizzleInvocationsMaskedAMD;
5987 break;
5988 case glslang::EOpWriteInvocation:
5989 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5990 libCall = spv::WriteInvocationAMD;
5991 break;
5992
5993 case glslang::EOpMin3:
5994 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5995 if (isFloat)
5996 libCall = spv::FMin3AMD;
5997 else {
5998 if (isUnsigned)
5999 libCall = spv::UMin3AMD;
6000 else
6001 libCall = spv::SMin3AMD;
6002 }
6003 break;
6004 case glslang::EOpMax3:
6005 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6006 if (isFloat)
6007 libCall = spv::FMax3AMD;
6008 else {
6009 if (isUnsigned)
6010 libCall = spv::UMax3AMD;
6011 else
6012 libCall = spv::SMax3AMD;
6013 }
6014 break;
6015 case glslang::EOpMid3:
6016 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6017 if (isFloat)
6018 libCall = spv::FMid3AMD;
6019 else {
6020 if (isUnsigned)
6021 libCall = spv::UMid3AMD;
6022 else
6023 libCall = spv::SMid3AMD;
6024 }
6025 break;
6026
6027 case glslang::EOpInterpolateAtVertex:
6028 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
6029 libCall = spv::InterpolateAtVertexAMD;
6030 break;
6031#endif
6032
John Kessenich140f3df2015-06-26 16:58:36 -06006033 default:
6034 return 0;
6035 }
6036
6037 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07006038 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05006039 // Use an extended instruction from the standard library.
6040 // Construct the call arguments, without modifying the original operands vector.
6041 // We might need the remaining arguments, e.g. in the EOpFrexp case.
6042 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08006043 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07006044 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07006045 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06006046 case 0:
6047 // should all be handled by visitAggregate and createNoArgOperation
6048 assert(0);
6049 return 0;
6050 case 1:
6051 // should all be handled by createUnaryOperation
6052 assert(0);
6053 return 0;
6054 case 2:
6055 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
6056 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006057 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006058 // anything 3 or over doesn't have l-value operands, so all should be consumed
6059 assert(consumedOperands == operands.size());
6060 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06006061 break;
6062 }
6063 }
6064
John Kessenich55e7d112015-11-15 21:33:39 -07006065 // Decode the return types that were structures
6066 switch (op) {
6067 case glslang::EOpAddCarry:
6068 case glslang::EOpSubBorrow:
6069 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6070 id = builder.createCompositeExtract(id, typeId0, 0);
6071 break;
6072 case glslang::EOpUMulExtended:
6073 case glslang::EOpIMulExtended:
6074 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
6075 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6076 break;
6077 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006078 {
6079 assert(operands.size() == 2);
6080 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
6081 // "exp" is floating-point type (from HLSL intrinsic)
6082 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
6083 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
6084 builder.createStore(member1, operands[1]);
6085 } else
6086 // "exp" is integer type (from GLSL built-in function)
6087 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
6088 id = builder.createCompositeExtract(id, typeId0, 0);
6089 }
John Kessenich55e7d112015-11-15 21:33:39 -07006090 break;
6091 default:
6092 break;
6093 }
6094
John Kessenich32cfd492016-02-02 12:37:46 -07006095 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006096}
6097
Rex Xu9d93a232016-05-05 12:30:44 +08006098// Intrinsics with no arguments (or no return value, and no precision).
6099spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06006100{
6101 // TODO: get the barrier operands correct
6102
6103 switch (op) {
6104 case glslang::EOpEmitVertex:
6105 builder.createNoResultOp(spv::OpEmitVertex);
6106 return 0;
6107 case glslang::EOpEndPrimitive:
6108 builder.createNoResultOp(spv::OpEndPrimitive);
6109 return 0;
6110 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006111 if (glslangIntermediate->getStage() == EShLangTessControl) {
6112 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
6113 // TODO: prefer the following, when available:
6114 // builder.createControlBarrier(spv::ScopePatch, spv::ScopePatch,
6115 // spv::MemorySemanticsPatchMask |
6116 // spv::MemorySemanticsAcquireReleaseMask);
6117 } else {
6118 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6119 spv::MemorySemanticsWorkgroupMemoryMask |
6120 spv::MemorySemanticsAcquireReleaseMask);
6121 }
John Kessenich140f3df2015-06-26 16:58:36 -06006122 return 0;
6123 case glslang::EOpMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006124 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory |
6125 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006126 return 0;
6127 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich82979362017-12-11 04:02:24 -07006128 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask |
6129 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006130 return 0;
6131 case glslang::EOpMemoryBarrierBuffer:
John Kessenich82979362017-12-11 04:02:24 -07006132 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6133 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006134 return 0;
6135 case glslang::EOpMemoryBarrierImage:
John Kessenich82979362017-12-11 04:02:24 -07006136 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask |
6137 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006138 return 0;
6139 case glslang::EOpMemoryBarrierShared:
John Kessenich82979362017-12-11 04:02:24 -07006140 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask |
6141 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006142 return 0;
6143 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006144 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
6145 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006146 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06006147 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006148 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07006149 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07006150 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006151 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07006152 case glslang::EOpDeviceMemoryBarrier:
6153 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6154 spv::MemorySemanticsImageMemoryMask |
6155 spv::MemorySemanticsAcquireReleaseMask);
6156 return 0;
6157 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
6158 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6159 spv::MemorySemanticsImageMemoryMask |
6160 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006161 return 0;
6162 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07006163 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6164 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006165 return 0;
6166 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006167 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6168 spv::MemorySemanticsWorkgroupMemoryMask |
6169 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006170 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07006171 case glslang::EOpSubgroupBarrier:
6172 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6173 spv::MemorySemanticsAcquireReleaseMask);
6174 return spv::NoResult;
6175 case glslang::EOpSubgroupMemoryBarrier:
6176 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6177 spv::MemorySemanticsAcquireReleaseMask);
6178 return spv::NoResult;
6179 case glslang::EOpSubgroupMemoryBarrierBuffer:
6180 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
6181 spv::MemorySemanticsAcquireReleaseMask);
6182 return spv::NoResult;
6183 case glslang::EOpSubgroupMemoryBarrierImage:
6184 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
6185 spv::MemorySemanticsAcquireReleaseMask);
6186 return spv::NoResult;
6187 case glslang::EOpSubgroupMemoryBarrierShared:
6188 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6189 spv::MemorySemanticsAcquireReleaseMask);
6190 return spv::NoResult;
6191 case glslang::EOpSubgroupElect: {
6192 std::vector<spv::Id> operands;
6193 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
6194 }
Rex Xu9d93a232016-05-05 12:30:44 +08006195#ifdef AMD_EXTENSIONS
6196 case glslang::EOpTime:
6197 {
6198 std::vector<spv::Id> args; // Dummy arguments
6199 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
6200 return builder.setPrecision(id, precision);
6201 }
6202#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006203 default:
Lei Zhang17535f72016-05-04 15:55:59 -04006204 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06006205 return 0;
6206 }
6207}
6208
6209spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
6210{
John Kessenich2f273362015-07-18 22:34:27 -06006211 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06006212 spv::Id id;
6213 if (symbolValues.end() != iter) {
6214 id = iter->second;
6215 return id;
6216 }
6217
6218 // it was not found, create it
6219 id = createSpvVariable(symbol);
6220 symbolValues[symbol->getId()] = id;
6221
Rex Xuc884b4a2016-06-29 15:03:44 +08006222 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006223 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
6224 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
6225 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07006226 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07006227 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06006228 if (symbol->getQualifier().hasIndex())
6229 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
6230 if (symbol->getQualifier().hasComponent())
6231 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06006232 // atomic counters use this:
6233 if (symbol->getQualifier().hasOffset())
6234 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006235 }
6236
scygan2c864272016-05-18 18:09:17 +02006237 if (symbol->getQualifier().hasLocation())
6238 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07006239 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07006240 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07006241 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06006242 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07006243 }
John Kessenich140f3df2015-06-26 16:58:36 -06006244 if (symbol->getQualifier().hasSet())
6245 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07006246 else if (IsDescriptorResource(symbol->getType())) {
6247 // default to 0
6248 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
6249 }
John Kessenich140f3df2015-06-26 16:58:36 -06006250 if (symbol->getQualifier().hasBinding())
6251 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07006252 if (symbol->getQualifier().hasAttachment())
6253 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06006254 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07006255 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06006256 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06006257 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07006258 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06006259 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07006260 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
6261 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
6262 builder.addDecoration(id, spv::DecorationXfbStride, stride);
6263 }
6264 if (symbol->getQualifier().hasXfbOffset())
6265 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006266 }
6267
Rex Xu1da878f2016-02-21 20:59:01 +08006268 if (symbol->getType().isImage()) {
6269 std::vector<spv::Decoration> memory;
6270 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
6271 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07006272 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08006273 }
6274
John Kessenich140f3df2015-06-26 16:58:36 -06006275 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06006276 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06006277 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07006278 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06006279
John Kessenichecba76f2017-01-06 00:34:48 -07006280#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08006281 if (builtIn == spv::BuiltInSampleMask) {
6282 spv::Decoration decoration;
6283 // GL_NV_sample_mask_override_coverage extension
6284 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08006285 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08006286 else
6287 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07006288 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08006289 if (decoration != spv::DecorationMax) {
6290 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
6291 }
6292 }
chaoc771d89f2017-01-13 01:10:53 -08006293 else if (builtIn == spv::BuiltInLayer) {
6294 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06006295 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006296 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08006297 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
6298 builder.addExtension(spv::E_SPV_NV_viewport_array2);
6299 }
John Kessenichb41bff62017-08-11 13:07:17 -06006300 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006301 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
6302 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08006303 builder.addCapability(spv::CapabilityShaderStereoViewNV);
6304 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
6305 }
6306 }
6307
chaoc6e5acae2016-12-20 13:28:52 -08006308 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006309 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08006310 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08006311 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
6312 }
chaoc0ad6a4e2016-12-19 16:29:34 -08006313#endif
6314
John Kessenich5d610ee2018-03-07 18:05:55 -07006315 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
6316 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
6317 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
6318 symbol->getType().getQualifier().semanticName);
6319 }
6320
John Kessenich140f3df2015-06-26 16:58:36 -06006321 return id;
6322}
6323
John Kessenich55e7d112015-11-15 21:33:39 -07006324// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07006325// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07006326//
6327// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
6328//
6329// Recursively walk the nodes. The nodes form a tree whose leaves are
6330// regular constants, which themselves are trees that createSpvConstant()
6331// recursively walks. So, this function walks the "top" of the tree:
6332// - emit specialization constant-building instructions for specConstant
6333// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04006334spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07006335{
John Kessenich7cc0e282016-03-20 00:46:02 -06006336 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07006337
qining4f4bb812016-04-03 23:55:17 -04006338 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07006339 if (! node.getQualifier().specConstant) {
6340 // hand off to the non-spec-constant path
6341 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
6342 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04006343 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07006344 nextConst, false);
6345 }
6346
6347 // We now know we have a specialization constant to build
6348
John Kessenichd94c0032016-05-30 19:29:40 -06006349 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04006350 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
6351 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
6352 std::vector<spv::Id> dimConstId;
6353 for (int dim = 0; dim < 3; ++dim) {
6354 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
6355 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07006356 if (specConst) {
6357 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
6358 glslangIntermediate->getLocalSizeSpecId(dim));
6359 }
qining4f4bb812016-04-03 23:55:17 -04006360 }
6361 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
6362 }
6363
6364 // An AST node labelled as specialization constant should be a symbol node.
6365 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
6366 if (auto* sn = node.getAsSymbolNode()) {
6367 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04006368 // Traverse the constant constructor sub tree like generating normal run-time instructions.
6369 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
6370 // will set the builder into spec constant op instruction generating mode.
6371 sub_tree->traverse(this);
6372 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04006373 } else if (auto* const_union_array = &sn->getConstArray()){
6374 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01006375 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
6376 builder.addName(id, sn->getName().c_str());
6377 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07006378 }
6379 }
qining4f4bb812016-04-03 23:55:17 -04006380
6381 // Neither a front-end constant node, nor a specialization constant node with constant union array or
6382 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04006383 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04006384 exit(1);
6385 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07006386}
6387
John Kessenich140f3df2015-06-26 16:58:36 -06006388// Use 'consts' as the flattened glslang source of scalar constants to recursively
6389// build the aggregate SPIR-V constant.
6390//
6391// If there are not enough elements present in 'consts', 0 will be substituted;
6392// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
6393//
qining08408382016-03-21 09:51:37 -04006394spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06006395{
6396 // vector of constants for SPIR-V
6397 std::vector<spv::Id> spvConsts;
6398
6399 // Type is used for struct and array constants
6400 spv::Id typeId = convertGlslangToSpvType(glslangType);
6401
6402 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006403 glslang::TType elementType(glslangType, 0);
6404 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04006405 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006406 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006407 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06006408 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04006409 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006410 } else if (glslangType.getStruct()) {
6411 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
6412 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04006413 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06006414 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06006415 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
6416 bool zero = nextConst >= consts.size();
6417 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006418 case glslang::EbtInt8:
6419 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
6420 break;
6421 case glslang::EbtUint8:
6422 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
6423 break;
6424 case glslang::EbtInt16:
6425 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
6426 break;
6427 case glslang::EbtUint16:
6428 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
6429 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006430 case glslang::EbtInt:
6431 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
6432 break;
6433 case glslang::EbtUint:
6434 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
6435 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006436 case glslang::EbtInt64:
6437 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
6438 break;
6439 case glslang::EbtUint64:
6440 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
6441 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006442 case glslang::EbtFloat:
6443 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
6444 break;
6445 case glslang::EbtDouble:
6446 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
6447 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006448 case glslang::EbtFloat16:
6449 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
6450 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006451 case glslang::EbtBool:
6452 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
6453 break;
6454 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006455 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06006456 break;
6457 }
6458 ++nextConst;
6459 }
6460 } else {
6461 // we have a non-aggregate (scalar) constant
6462 bool zero = nextConst >= consts.size();
6463 spv::Id scalar = 0;
6464 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006465 case glslang::EbtInt8:
6466 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
6467 break;
6468 case glslang::EbtUint8:
6469 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
6470 break;
6471 case glslang::EbtInt16:
6472 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
6473 break;
6474 case glslang::EbtUint16:
6475 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
6476 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006477 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07006478 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006479 break;
6480 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07006481 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006482 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006483 case glslang::EbtInt64:
6484 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
6485 break;
6486 case glslang::EbtUint64:
6487 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
6488 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006489 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07006490 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006491 break;
6492 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07006493 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006494 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006495 case glslang::EbtFloat16:
6496 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
6497 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006498 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07006499 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006500 break;
6501 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006502 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06006503 break;
6504 }
6505 ++nextConst;
6506 return scalar;
6507 }
6508
6509 return builder.makeCompositeConstant(typeId, spvConsts);
6510}
6511
John Kessenich7c1aa102015-10-15 13:29:11 -06006512// Return true if the node is a constant or symbol whose reading has no
6513// non-trivial observable cost or effect.
6514bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
6515{
6516 // don't know what this is
6517 if (node == nullptr)
6518 return false;
6519
6520 // a constant is safe
6521 if (node->getAsConstantUnion() != nullptr)
6522 return true;
6523
6524 // not a symbol means non-trivial
6525 if (node->getAsSymbolNode() == nullptr)
6526 return false;
6527
6528 // a symbol, depends on what's being read
6529 switch (node->getType().getQualifier().storage) {
6530 case glslang::EvqTemporary:
6531 case glslang::EvqGlobal:
6532 case glslang::EvqIn:
6533 case glslang::EvqInOut:
6534 case glslang::EvqConst:
6535 case glslang::EvqConstReadOnly:
6536 case glslang::EvqUniform:
6537 return true;
6538 default:
6539 return false;
6540 }
qining25262b32016-05-06 17:25:16 -04006541}
John Kessenich7c1aa102015-10-15 13:29:11 -06006542
6543// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06006544// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06006545// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06006546// Return true if trivial.
6547bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
6548{
6549 if (node == nullptr)
6550 return false;
6551
John Kessenich84cc15f2017-05-24 16:44:47 -06006552 // count non scalars as trivial, as well as anything coming from HLSL
6553 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06006554 return true;
6555
John Kessenich7c1aa102015-10-15 13:29:11 -06006556 // symbols and constants are trivial
6557 if (isTrivialLeaf(node))
6558 return true;
6559
6560 // otherwise, it needs to be a simple operation or one or two leaf nodes
6561
6562 // not a simple operation
6563 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
6564 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
6565 if (binaryNode == nullptr && unaryNode == nullptr)
6566 return false;
6567
6568 // not on leaf nodes
6569 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
6570 return false;
6571
6572 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
6573 return false;
6574 }
6575
6576 switch (node->getAsOperator()->getOp()) {
6577 case glslang::EOpLogicalNot:
6578 case glslang::EOpConvIntToBool:
6579 case glslang::EOpConvUintToBool:
6580 case glslang::EOpConvFloatToBool:
6581 case glslang::EOpConvDoubleToBool:
6582 case glslang::EOpEqual:
6583 case glslang::EOpNotEqual:
6584 case glslang::EOpLessThan:
6585 case glslang::EOpGreaterThan:
6586 case glslang::EOpLessThanEqual:
6587 case glslang::EOpGreaterThanEqual:
6588 case glslang::EOpIndexDirect:
6589 case glslang::EOpIndexDirectStruct:
6590 case glslang::EOpLogicalXor:
6591 case glslang::EOpAny:
6592 case glslang::EOpAll:
6593 return true;
6594 default:
6595 return false;
6596 }
6597}
6598
6599// Emit short-circuiting code, where 'right' is never evaluated unless
6600// the left side is true (for &&) or false (for ||).
6601spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
6602{
6603 spv::Id boolTypeId = builder.makeBoolType();
6604
6605 // emit left operand
6606 builder.clearAccessChain();
6607 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006608 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006609
6610 // Operands to accumulate OpPhi operands
6611 std::vector<spv::Id> phiOperands;
6612 // accumulate left operand's phi information
6613 phiOperands.push_back(leftId);
6614 phiOperands.push_back(builder.getBuildPoint()->getId());
6615
6616 // Make the two kinds of operation symmetric with a "!"
6617 // || => emit "if (! left) result = right"
6618 // && => emit "if ( left) result = right"
6619 //
6620 // TODO: this runtime "not" for || could be avoided by adding functionality
6621 // to 'builder' to have an "else" without an "then"
6622 if (op == glslang::EOpLogicalOr)
6623 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
6624
6625 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08006626 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06006627
6628 // emit right operand as the "then" part of the "if"
6629 builder.clearAccessChain();
6630 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006631 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006632
6633 // accumulate left operand's phi information
6634 phiOperands.push_back(rightId);
6635 phiOperands.push_back(builder.getBuildPoint()->getId());
6636
6637 // finish the "if"
6638 ifBuilder.makeEndIf();
6639
6640 // phi together the two results
6641 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
6642}
6643
Frank Henigman541f7bb2018-01-16 00:18:26 -05006644#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08006645// Return type Id of the imported set of extended instructions corresponds to the name.
6646// Import this set if it has not been imported yet.
6647spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
6648{
6649 if (extBuiltinMap.find(name) != extBuiltinMap.end())
6650 return extBuiltinMap[name];
6651 else {
Rex Xu51596642016-09-21 18:56:12 +08006652 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08006653 spv::Id extBuiltins = builder.import(name);
6654 extBuiltinMap[name] = extBuiltins;
6655 return extBuiltins;
6656 }
6657}
Frank Henigman541f7bb2018-01-16 00:18:26 -05006658#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006659
John Kessenich140f3df2015-06-26 16:58:36 -06006660}; // end anonymous namespace
6661
6662namespace glslang {
6663
John Kessenich68d78fd2015-07-12 19:28:10 -06006664void GetSpirvVersion(std::string& version)
6665{
John Kessenich9e55f632015-07-15 10:03:39 -06006666 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06006667 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07006668 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06006669 version = buf;
6670}
6671
John Kessenicha372a3e2017-11-02 22:32:14 -06006672// For low-order part of the generator's magic number. Bump up
6673// when there is a change in the style (e.g., if SSA form changes,
6674// or a different instruction sequence to do something gets used).
6675int GetSpirvGeneratorVersion()
6676{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07006677 // return 1; // start
6678 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07006679 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07006680 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07006681 // return 5; // make OpArrayLength result type be an int with signedness of 0
6682 return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
6683 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenicha372a3e2017-11-02 22:32:14 -06006684}
6685
John Kessenich140f3df2015-06-26 16:58:36 -06006686// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006687void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06006688{
6689 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06006690 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006691 if (out.fail())
6692 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06006693 for (int i = 0; i < (int)spirv.size(); ++i) {
6694 unsigned int word = spirv[i];
6695 out.write((const char*)&word, 4);
6696 }
6697 out.close();
6698}
6699
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006700// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08006701void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006702{
6703 std::ofstream out;
6704 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006705 if (out.fail())
6706 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07006707 out << "\t// " <<
6708 glslang::GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
6709 std::endl;
Flavio15017db2017-02-15 14:29:33 -08006710 if (varName != nullptr) {
6711 out << "\t #pragma once" << std::endl;
6712 out << "const uint32_t " << varName << "[] = {" << std::endl;
6713 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006714 const int WORDS_PER_LINE = 8;
6715 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
6716 out << "\t";
6717 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
6718 const unsigned int word = spirv[i + j];
6719 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
6720 if (i + j + 1 < (int)spirv.size()) {
6721 out << ",";
6722 }
6723 }
6724 out << std::endl;
6725 }
Flavio15017db2017-02-15 14:29:33 -08006726 if (varName != nullptr) {
6727 out << "};";
6728 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006729 out.close();
6730}
6731
John Kessenich140f3df2015-06-26 16:58:36 -06006732//
6733// Set up the glslang traversal
6734//
John Kessenich121853f2017-05-31 17:11:16 -06006735void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06006736{
Lei Zhang17535f72016-05-04 15:55:59 -04006737 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06006738 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04006739}
6740
John Kessenich121853f2017-05-31 17:11:16 -06006741void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
6742 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04006743{
John Kessenich140f3df2015-06-26 16:58:36 -06006744 TIntermNode* root = intermediate.getTreeRoot();
6745
6746 if (root == 0)
6747 return;
6748
John Kessenich121853f2017-05-31 17:11:16 -06006749 glslang::SpvOptions defaultOptions;
6750 if (options == nullptr)
6751 options = &defaultOptions;
6752
John Kessenich140f3df2015-06-26 16:58:36 -06006753 glslang::GetThreadPoolAllocator().push();
6754
John Kessenich2b5ea9f2018-01-31 18:35:56 -07006755 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06006756 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07006757 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06006758 it.dumpSpv(spirv);
6759
GregFfb03a552018-03-29 11:49:14 -06006760#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06006761 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
6762 // eg. forward and remove memory writes of opaque types.
6763 if ((intermediate.getSource() == EShSourceHlsl ||
6764 options->optimizeSize) &&
6765 !options->disableOptimizer) {
6766 spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
6767
6768 spvtools::Optimizer optimizer(target_env);
6769 optimizer.SetMessageConsumer([](spv_message_level_t level,
6770 const char* source,
6771 const spv_position_t& position,
6772 const char* message) {
6773 std::cerr << StringifyMessage(level, source, position, message)
6774 << std::endl;
6775 });
6776
GregFeecb8742018-03-26 12:11:55 -06006777 optimizer.RegisterPass(CreateMergeReturnPass());
GregFcd1f1692017-09-21 18:40:22 -06006778 optimizer.RegisterPass(CreateInlineExhaustivePass());
GregFe0639282017-12-21 10:55:57 -07006779 optimizer.RegisterPass(CreateEliminateDeadFunctionsPass());
6780 optimizer.RegisterPass(CreateScalarReplacementPass());
GregFcd1f1692017-09-21 18:40:22 -06006781 optimizer.RegisterPass(CreateLocalAccessChainConvertPass());
6782 optimizer.RegisterPass(CreateLocalSingleBlockLoadStoreElimPass());
6783 optimizer.RegisterPass(CreateLocalSingleStoreElimPass());
GregFeecb8742018-03-26 12:11:55 -06006784 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFcd1f1692017-09-21 18:40:22 -06006785 optimizer.RegisterPass(CreateInsertExtractElimPass());
GregF8a4848f2018-02-07 16:04:42 -07006786 optimizer.RegisterPass(CreateDeadInsertElimPass());
GregFcd1f1692017-09-21 18:40:22 -06006787 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFeecb8742018-03-26 12:11:55 -06006788 optimizer.RegisterPass(CreateCCPPass());
6789 optimizer.RegisterPass(CreateSimplificationPass());
GregFcd1f1692017-09-21 18:40:22 -06006790 optimizer.RegisterPass(CreateDeadBranchElimPass());
GregFcc80d802017-10-23 16:48:42 -06006791 optimizer.RegisterPass(CreateCFGCleanupPass());
GregFcd1f1692017-09-21 18:40:22 -06006792 optimizer.RegisterPass(CreateBlockMergePass());
6793 optimizer.RegisterPass(CreateLocalMultiStoreElimPass());
GregFeecb8742018-03-26 12:11:55 -06006794 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFcd1f1692017-09-21 18:40:22 -06006795 optimizer.RegisterPass(CreateInsertExtractElimPass());
GregF8a4848f2018-02-07 16:04:42 -07006796 optimizer.RegisterPass(CreateDeadInsertElimPass());
6797 if (options->optimizeSize) {
6798 optimizer.RegisterPass(CreateRedundancyEliminationPass());
6799 // TODO(greg-lunarg): Add this when AMD driver issues are resolved
6800 // optimizer.RegisterPass(CreateCommonUniformElimPass());
6801 }
GregFcd1f1692017-09-21 18:40:22 -06006802 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFcd1f1692017-09-21 18:40:22 -06006803
6804 if (!optimizer.Run(spirv.data(), spirv.size(), &spirv))
6805 return;
GregFcd1f1692017-09-21 18:40:22 -06006806 }
6807#endif
6808
John Kessenich140f3df2015-06-26 16:58:36 -06006809 glslang::GetThreadPoolAllocator().pop();
6810}
6811
6812}; // end namespace glslang