blob: 5d7350f90b2bbf15c630b284fb9f9f088a729227 [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
GregFcd1f1692017-09-21 18:40:22 -060057#ifdef ENABLE_OPT
58 #include "spirv-tools/optimizer.hpp"
59 #include "message.h"
60 #include "SPVRemapper.h"
61#endif
62
63#ifdef ENABLE_OPT
64using namespace spvtools;
65#endif
66
John Kessenich140f3df2015-06-26 16:58:36 -060067// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020068#include "../glslang/MachineIndependent/localintermediate.h"
69#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060070#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050071#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060072
John Kessenich140f3df2015-06-26 16:58:36 -060073#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050074#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040075#include <list>
76#include <map>
77#include <stack>
78#include <string>
79#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060080
81namespace {
82
qining4c912612016-04-01 10:35:16 -040083namespace {
84class SpecConstantOpModeGuard {
85public:
86 SpecConstantOpModeGuard(spv::Builder* builder)
87 : builder_(builder) {
88 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040089 }
90 ~SpecConstantOpModeGuard() {
91 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
92 : builder_->setToNormalCodeGenMode();
93 }
qining40887662016-04-03 22:20:42 -040094 void turnOnSpecConstantOpMode() {
95 builder_->setToSpecConstCodeGenMode();
96 }
qining4c912612016-04-01 10:35:16 -040097
98private:
99 spv::Builder* builder_;
100 bool previous_flag_;
101};
John Kessenichead86222018-03-28 18:01:20 -0600102
103struct OpDecorations {
104 spv::Decoration precision;
105 spv::Decoration noContraction;
106};
107
108} // namespace
qining4c912612016-04-01 10:35:16 -0400109
John Kessenich140f3df2015-06-26 16:58:36 -0600110//
111// The main holder of information for translating glslang to SPIR-V.
112//
113// Derives from the AST walking base class.
114//
115class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
116public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700117 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
118 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700119 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600120
121 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
122 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
123 void visitConstantUnion(glslang::TIntermConstantUnion*);
124 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
125 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
126 void visitSymbol(glslang::TIntermSymbol* symbol);
127 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
128 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
129 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
130
John Kessenichfca82622016-11-26 13:23:20 -0700131 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700132 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600133
134protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700135 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
136 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
137
Rex Xu17ff3432016-10-14 17:41:45 +0800138 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800139 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100140 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700141 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700142 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
143 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenicha2858d92018-01-31 08:11:18 -0700144 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, unsigned int& dependencyLength) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600145 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich140f3df2015-06-26 16:58:36 -0600146 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
147 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600148 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
149 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
150 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600151 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kessenichead86222018-03-28 18:01:20 -0600152 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
153 bool lastBufferBlockMember);
John Kessenich0e737842017-03-24 18:38:16 -0600154 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600155 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
156 glslang::TLayoutPacking, const glslang::TQualifier&);
157 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
158 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700159 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700160 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800161 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600162 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700163 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700164 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
165 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700166 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
167 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100168 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600169
John Kessenich6fccb3c2016-09-19 16:01:41 -0600170 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd41993d2017-09-10 15:21:05 -0600171 bool writableParam(glslang::TStorageQualifier);
172 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600173 void makeFunctions(const glslang::TIntermSequence&);
174 void makeGlobalInitializers(const glslang::TIntermSequence&);
175 void visitFunctions(const glslang::TIntermSequence&);
176 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800177 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600178 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
179 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600180 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
181
John Kessenichead86222018-03-28 18:01:20 -0600182 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
183 glslang::TBasicType typeProxy, bool reduceComparison = true);
184 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
185 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
186 glslang::TBasicType typeProxy);
187 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
188 glslang::TBasicType typeProxy);
189 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
190 glslang::TBasicType typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -0700191 spv::Id createConversionOperation(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600192 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800193 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 +0800194 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800195 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700196 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600197 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 +0800198 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600199 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
qining08408382016-03-21 09:51:37 -0400200 spv::Id createSpvConstant(const glslang::TIntermTyped&);
201 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600202 bool isTrivialLeaf(const glslang::TIntermTyped* node);
203 bool isTrivial(const glslang::TIntermTyped* node);
204 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500205#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800206 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500207#endif
John Kessenich66011cb2018-03-06 16:12:04 -0700208 void addPre13Extension(const char* ext)
209 {
210 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
211 builder.addExtension(ext);
212 }
John Kessenich140f3df2015-06-26 16:58:36 -0600213
John Kessenich121853f2017-05-31 17:11:16 -0600214 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600215 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600216 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700217 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600218 int sequenceDepth;
219
Lei Zhang17535f72016-05-04 15:55:59 -0400220 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400221
John Kessenich140f3df2015-06-26 16:58:36 -0600222 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
223 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700224 bool inEntryPoint;
225 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700226 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 -0700227 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600228 const glslang::TIntermediate* glslangIntermediate;
229 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800230 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600231
John Kessenich2f273362015-07-18 22:34:27 -0600232 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600233 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600234 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700235 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700236 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
237 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600238 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700239 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
John Kessenich140f3df2015-06-26 16:58:36 -0600240};
241
242//
243// Helper functions for translating glslang representations to SPIR-V enumerants.
244//
245
246// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700247spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600248{
John Kessenich66e2faf2016-03-12 18:34:36 -0700249 switch (source) {
250 case glslang::EShSourceGlsl:
251 switch (profile) {
252 case ENoProfile:
253 case ECoreProfile:
254 case ECompatibilityProfile:
255 return spv::SourceLanguageGLSL;
256 case EEsProfile:
257 return spv::SourceLanguageESSL;
258 default:
259 return spv::SourceLanguageUnknown;
260 }
261 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600262 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600263 default:
264 return spv::SourceLanguageUnknown;
265 }
266}
267
268// Translate glslang language (stage) to SPIR-V execution model.
269spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
270{
271 switch (stage) {
272 case EShLangVertex: return spv::ExecutionModelVertex;
273 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
274 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
275 case EShLangGeometry: return spv::ExecutionModelGeometry;
276 case EShLangFragment: return spv::ExecutionModelFragment;
277 case EShLangCompute: return spv::ExecutionModelGLCompute;
278 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700279 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600280 return spv::ExecutionModelFragment;
281 }
282}
283
John Kessenich140f3df2015-06-26 16:58:36 -0600284// Translate glslang sampler type to SPIR-V dimensionality.
285spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
286{
287 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700288 case glslang::Esd1D: return spv::Dim1D;
289 case glslang::Esd2D: return spv::Dim2D;
290 case glslang::Esd3D: return spv::Dim3D;
291 case glslang::EsdCube: return spv::DimCube;
292 case glslang::EsdRect: return spv::DimRect;
293 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700294 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600295 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700296 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600297 return spv::Dim2D;
298 }
299}
300
John Kessenichf6640762016-08-01 19:44:00 -0600301// Translate glslang precision to SPIR-V precision decorations.
302spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600303{
John Kessenichf6640762016-08-01 19:44:00 -0600304 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700305 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600306 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600307 default:
308 return spv::NoPrecision;
309 }
310}
311
John Kessenichf6640762016-08-01 19:44:00 -0600312// Translate glslang type to SPIR-V precision decorations.
313spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
314{
315 return TranslatePrecisionDecoration(type.getQualifier().precision);
316}
317
John Kessenich140f3df2015-06-26 16:58:36 -0600318// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600319spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600320{
321 if (type.getBasicType() == glslang::EbtBlock) {
322 switch (type.getQualifier().storage) {
323 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600324 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600325 case glslang::EvqVaryingIn: return spv::DecorationBlock;
326 case glslang::EvqVaryingOut: return spv::DecorationBlock;
327 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700328 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600329 break;
330 }
331 }
332
John Kessenich4016e382016-07-15 11:53:56 -0600333 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600334}
335
Rex Xu1da878f2016-02-21 20:59:01 +0800336// Translate glslang type to SPIR-V memory decorations.
337void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
338{
339 if (qualifier.coherent)
340 memory.push_back(spv::DecorationCoherent);
341 if (qualifier.volatil)
342 memory.push_back(spv::DecorationVolatile);
343 if (qualifier.restrict)
344 memory.push_back(spv::DecorationRestrict);
345 if (qualifier.readonly)
346 memory.push_back(spv::DecorationNonWritable);
347 if (qualifier.writeonly)
348 memory.push_back(spv::DecorationNonReadable);
349}
350
John Kessenich140f3df2015-06-26 16:58:36 -0600351// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700352spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600353{
354 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700355 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600356 case glslang::ElmRowMajor:
357 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700358 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600359 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700360 default:
361 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600362 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600363 }
364 } else {
365 switch (type.getBasicType()) {
366 default:
John Kessenich4016e382016-07-15 11:53:56 -0600367 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600368 break;
369 case glslang::EbtBlock:
370 switch (type.getQualifier().storage) {
371 case glslang::EvqUniform:
372 case glslang::EvqBuffer:
373 switch (type.getQualifier().layoutPacking) {
374 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600375 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
376 default:
John Kessenich4016e382016-07-15 11:53:56 -0600377 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600378 }
379 case glslang::EvqVaryingIn:
380 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700381 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600382 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600383 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700384 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600385 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600386 }
387 }
388 }
389}
390
391// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600392// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700393// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800394spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600395{
Rex Xubbceed72016-05-21 09:40:44 +0800396 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700397 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600398 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800399 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700400 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700401 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600402 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800403#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800404 else if (qualifier.explicitInterp) {
405 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800406 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800407 }
Rex Xu9d93a232016-05-05 12:30:44 +0800408#endif
Rex Xubbceed72016-05-21 09:40:44 +0800409 else
John Kessenich4016e382016-07-15 11:53:56 -0600410 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800411}
412
413// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600414// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800415// should be applied.
416spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
417{
418 if (qualifier.patch)
419 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700420 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600421 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700422 else if (qualifier.sample) {
423 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600424 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700425 } else
John Kessenich4016e382016-07-15 11:53:56 -0600426 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600427}
428
John Kessenich92187592016-02-01 13:45:25 -0700429// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700430spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600431{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700432 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600433 return spv::DecorationInvariant;
434 else
John Kessenich4016e382016-07-15 11:53:56 -0600435 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600436}
437
qining9220dbb2016-05-04 17:34:38 -0400438// If glslang type is noContraction, return SPIR-V NoContraction decoration.
439spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
440{
441 if (qualifier.noContraction)
442 return spv::DecorationNoContraction;
443 else
John Kessenich4016e382016-07-15 11:53:56 -0600444 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400445}
446
David Netoa901ffe2016-06-08 14:11:40 +0100447// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
448// associated capabilities when required. For some built-in variables, a capability
449// is generated only when using the variable in an executable instruction, but not when
450// just declaring a struct member variable with it. This is true for PointSize,
451// ClipDistance, and CullDistance.
452spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600453{
454 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700455 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600456 // Defer adding the capability until the built-in is actually used.
457 if (! memberDeclaration) {
458 switch (glslangIntermediate->getStage()) {
459 case EShLangGeometry:
460 builder.addCapability(spv::CapabilityGeometryPointSize);
461 break;
462 case EShLangTessControl:
463 case EShLangTessEvaluation:
464 builder.addCapability(spv::CapabilityTessellationPointSize);
465 break;
466 default:
467 break;
468 }
John Kessenich92187592016-02-01 13:45:25 -0700469 }
470 return spv::BuiltInPointSize;
471
John Kessenichebb50532016-05-16 19:22:05 -0600472 // These *Distance capabilities logically belong here, but if the member is declared and
473 // then never used, consumers of SPIR-V prefer the capability not be declared.
474 // They are now generated when used, rather than here when declared.
475 // Potentially, the specification should be more clear what the minimum
476 // use needed is to trigger the capability.
477 //
John Kessenich92187592016-02-01 13:45:25 -0700478 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100479 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800480 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700481 return spv::BuiltInClipDistance;
482
483 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100484 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800485 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700486 return spv::BuiltInCullDistance;
487
488 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600489 builder.addCapability(spv::CapabilityMultiViewport);
490 if (glslangIntermediate->getStage() == EShLangVertex ||
491 glslangIntermediate->getStage() == EShLangTessControl ||
492 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800493
John Kessenichba6a3c22017-09-13 13:22:50 -0600494 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
495 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800496 }
John Kessenich92187592016-02-01 13:45:25 -0700497 return spv::BuiltInViewportIndex;
498
John Kessenich5e801132016-02-15 11:09:46 -0700499 case glslang::EbvSampleId:
500 builder.addCapability(spv::CapabilitySampleRateShading);
501 return spv::BuiltInSampleId;
502
503 case glslang::EbvSamplePosition:
504 builder.addCapability(spv::CapabilitySampleRateShading);
505 return spv::BuiltInSamplePosition;
506
507 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700508 return spv::BuiltInSampleMask;
509
John Kessenich78a45572016-07-08 14:05:15 -0600510 case glslang::EbvLayer:
John Kessenichba6a3c22017-09-13 13:22:50 -0600511 builder.addCapability(spv::CapabilityGeometry);
512 if (glslangIntermediate->getStage() == EShLangVertex ||
513 glslangIntermediate->getStage() == EShLangTessControl ||
514 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800515
John Kessenichba6a3c22017-09-13 13:22:50 -0600516 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
517 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800518 }
John Kessenich78a45572016-07-08 14:05:15 -0600519 return spv::BuiltInLayer;
520
John Kessenich140f3df2015-06-26 16:58:36 -0600521 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600522 case glslang::EbvVertexId: return spv::BuiltInVertexId;
523 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700524 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
525 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800526
John Kessenichda581a22015-10-14 14:10:30 -0600527 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700528 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800529 builder.addCapability(spv::CapabilityDrawParameters);
530 return spv::BuiltInBaseVertex;
531
John Kessenichda581a22015-10-14 14:10:30 -0600532 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700533 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800534 builder.addCapability(spv::CapabilityDrawParameters);
535 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200536
John Kessenichda581a22015-10-14 14:10:30 -0600537 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700538 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800539 builder.addCapability(spv::CapabilityDrawParameters);
540 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200541
542 case glslang::EbvPrimitiveId:
543 if (glslangIntermediate->getStage() == EShLangFragment)
544 builder.addCapability(spv::CapabilityGeometry);
545 return spv::BuiltInPrimitiveId;
546
Rex Xu37cdcee2017-06-29 17:46:34 +0800547 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800548 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
549 builder.addCapability(spv::CapabilityStencilExportEXT);
550 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800551
John Kessenich140f3df2015-06-26 16:58:36 -0600552 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600553 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
554 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
555 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
556 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
557 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
558 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
559 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600560 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
561 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
562 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
563 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
564 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
565 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
566 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
567 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800568
Rex Xu574ab042016-04-14 16:53:07 +0800569 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800570 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800571 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
572 return spv::BuiltInSubgroupSize;
573
Rex Xu574ab042016-04-14 16:53:07 +0800574 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800575 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800576 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
577 return spv::BuiltInSubgroupLocalInvocationId;
578
Rex Xu574ab042016-04-14 16:53:07 +0800579 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800580 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
581 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
582 return spv::BuiltInSubgroupEqMaskKHR;
583
Rex Xu574ab042016-04-14 16:53:07 +0800584 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800585 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
586 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
587 return spv::BuiltInSubgroupGeMaskKHR;
588
Rex Xu574ab042016-04-14 16:53:07 +0800589 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800590 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
591 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
592 return spv::BuiltInSubgroupGtMaskKHR;
593
Rex Xu574ab042016-04-14 16:53:07 +0800594 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800595 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
596 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
597 return spv::BuiltInSubgroupLeMaskKHR;
598
Rex Xu574ab042016-04-14 16:53:07 +0800599 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800600 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
601 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
602 return spv::BuiltInSubgroupLtMaskKHR;
603
John Kessenich66011cb2018-03-06 16:12:04 -0700604 case glslang::EbvNumSubgroups:
605 builder.addCapability(spv::CapabilityGroupNonUniform);
606 return spv::BuiltInNumSubgroups;
607
608 case glslang::EbvSubgroupID:
609 builder.addCapability(spv::CapabilityGroupNonUniform);
610 return spv::BuiltInSubgroupId;
611
612 case glslang::EbvSubgroupSize2:
613 builder.addCapability(spv::CapabilityGroupNonUniform);
614 return spv::BuiltInSubgroupSize;
615
616 case glslang::EbvSubgroupInvocation2:
617 builder.addCapability(spv::CapabilityGroupNonUniform);
618 return spv::BuiltInSubgroupLocalInvocationId;
619
620 case glslang::EbvSubgroupEqMask2:
621 builder.addCapability(spv::CapabilityGroupNonUniform);
622 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
623 return spv::BuiltInSubgroupEqMask;
624
625 case glslang::EbvSubgroupGeMask2:
626 builder.addCapability(spv::CapabilityGroupNonUniform);
627 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
628 return spv::BuiltInSubgroupGeMask;
629
630 case glslang::EbvSubgroupGtMask2:
631 builder.addCapability(spv::CapabilityGroupNonUniform);
632 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
633 return spv::BuiltInSubgroupGtMask;
634
635 case glslang::EbvSubgroupLeMask2:
636 builder.addCapability(spv::CapabilityGroupNonUniform);
637 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
638 return spv::BuiltInSubgroupLeMask;
639
640 case glslang::EbvSubgroupLtMask2:
641 builder.addCapability(spv::CapabilityGroupNonUniform);
642 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
643 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800644#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800645 case glslang::EbvBaryCoordNoPersp:
646 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
647 return spv::BuiltInBaryCoordNoPerspAMD;
648
649 case glslang::EbvBaryCoordNoPerspCentroid:
650 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
651 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
652
653 case glslang::EbvBaryCoordNoPerspSample:
654 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
655 return spv::BuiltInBaryCoordNoPerspSampleAMD;
656
657 case glslang::EbvBaryCoordSmooth:
658 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
659 return spv::BuiltInBaryCoordSmoothAMD;
660
661 case glslang::EbvBaryCoordSmoothCentroid:
662 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
663 return spv::BuiltInBaryCoordSmoothCentroidAMD;
664
665 case glslang::EbvBaryCoordSmoothSample:
666 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
667 return spv::BuiltInBaryCoordSmoothSampleAMD;
668
669 case glslang::EbvBaryCoordPullModel:
670 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
671 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800672#endif
chaoc771d89f2017-01-13 01:10:53 -0800673
John Kessenich6c8aaac2017-02-27 01:20:51 -0700674 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700675 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700676 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700677 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700678
679 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700680 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700681 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700682 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700683
chaoc771d89f2017-01-13 01:10:53 -0800684#ifdef NV_EXTENSIONS
685 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800686 if (!memberDeclaration) {
687 builder.addExtension(spv::E_SPV_NV_viewport_array2);
688 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
689 }
chaoc771d89f2017-01-13 01:10:53 -0800690 return spv::BuiltInViewportMaskNV;
691 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800692 if (!memberDeclaration) {
693 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
694 builder.addCapability(spv::CapabilityShaderStereoViewNV);
695 }
chaoc771d89f2017-01-13 01:10:53 -0800696 return spv::BuiltInSecondaryPositionNV;
697 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800698 if (!memberDeclaration) {
699 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
700 builder.addCapability(spv::CapabilityShaderStereoViewNV);
701 }
chaoc771d89f2017-01-13 01:10:53 -0800702 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800703 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800704 if (!memberDeclaration) {
705 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
706 builder.addCapability(spv::CapabilityPerViewAttributesNV);
707 }
chaocdf3956c2017-02-14 14:52:34 -0800708 return spv::BuiltInPositionPerViewNV;
709 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800710 if (!memberDeclaration) {
711 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
712 builder.addCapability(spv::CapabilityPerViewAttributesNV);
713 }
chaocdf3956c2017-02-14 14:52:34 -0800714 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700715 case glslang::EbvFragFullyCoveredNV:
716 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
717 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
718 return spv::BuiltInFullyCoveredEXT;
chaoc771d89f2017-01-13 01:10:53 -0800719#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800720 default:
721 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600722 }
723}
724
Rex Xufc618912015-09-09 16:42:49 +0800725// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700726spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800727{
728 assert(type.getBasicType() == glslang::EbtSampler);
729
John Kessenich5d0fa972016-02-15 11:57:00 -0700730 // Check for capabilities
731 switch (type.getQualifier().layoutFormat) {
732 case glslang::ElfRg32f:
733 case glslang::ElfRg16f:
734 case glslang::ElfR11fG11fB10f:
735 case glslang::ElfR16f:
736 case glslang::ElfRgba16:
737 case glslang::ElfRgb10A2:
738 case glslang::ElfRg16:
739 case glslang::ElfRg8:
740 case glslang::ElfR16:
741 case glslang::ElfR8:
742 case glslang::ElfRgba16Snorm:
743 case glslang::ElfRg16Snorm:
744 case glslang::ElfRg8Snorm:
745 case glslang::ElfR16Snorm:
746 case glslang::ElfR8Snorm:
747
748 case glslang::ElfRg32i:
749 case glslang::ElfRg16i:
750 case glslang::ElfRg8i:
751 case glslang::ElfR16i:
752 case glslang::ElfR8i:
753
754 case glslang::ElfRgb10a2ui:
755 case glslang::ElfRg32ui:
756 case glslang::ElfRg16ui:
757 case glslang::ElfRg8ui:
758 case glslang::ElfR16ui:
759 case glslang::ElfR8ui:
760 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
761 break;
762
763 default:
764 break;
765 }
766
767 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800768 switch (type.getQualifier().layoutFormat) {
769 case glslang::ElfNone: return spv::ImageFormatUnknown;
770 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
771 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
772 case glslang::ElfR32f: return spv::ImageFormatR32f;
773 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
774 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
775 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
776 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
777 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
778 case glslang::ElfR16f: return spv::ImageFormatR16f;
779 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
780 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
781 case glslang::ElfRg16: return spv::ImageFormatRg16;
782 case glslang::ElfRg8: return spv::ImageFormatRg8;
783 case glslang::ElfR16: return spv::ImageFormatR16;
784 case glslang::ElfR8: return spv::ImageFormatR8;
785 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
786 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
787 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
788 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
789 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
790 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
791 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
792 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
793 case glslang::ElfR32i: return spv::ImageFormatR32i;
794 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
795 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
796 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
797 case glslang::ElfR16i: return spv::ImageFormatR16i;
798 case glslang::ElfR8i: return spv::ImageFormatR8i;
799 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
800 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
801 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
802 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
803 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
804 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
805 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
806 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
807 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
808 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600809 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800810 }
811}
812
John Kesseniche18fd202018-01-30 11:01:39 -0700813spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +0800814{
John Kesseniche18fd202018-01-30 11:01:39 -0700815 if (selectionNode.getFlatten())
816 return spv::SelectionControlFlattenMask;
817 if (selectionNode.getDontFlatten())
818 return spv::SelectionControlDontFlattenMask;
819 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +0800820}
821
John Kesseniche18fd202018-01-30 11:01:39 -0700822spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -0600823{
John Kesseniche18fd202018-01-30 11:01:39 -0700824 if (switchNode.getFlatten())
825 return spv::SelectionControlFlattenMask;
826 if (switchNode.getDontFlatten())
827 return spv::SelectionControlDontFlattenMask;
828 return spv::SelectionControlMaskNone;
829}
830
John Kessenicha2858d92018-01-31 08:11:18 -0700831// return a non-0 dependency if the dependency argument must be set
832spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
833 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -0700834{
835 spv::LoopControlMask control = spv::LoopControlMaskNone;
836
837 if (loopNode.getDontUnroll())
838 control = control | spv::LoopControlDontUnrollMask;
839 if (loopNode.getUnroll())
840 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -0700841 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -0700842 control = control | spv::LoopControlDependencyInfiniteMask;
843 else if (loopNode.getLoopDependency() > 0) {
844 control = control | spv::LoopControlDependencyLengthMask;
845 dependencyLength = loopNode.getLoopDependency();
846 }
John Kesseniche18fd202018-01-30 11:01:39 -0700847
848 return control;
steve-lunargf1709e72017-05-02 20:14:50 -0600849}
850
John Kessenicha5c5fb62017-05-05 05:09:58 -0600851// Translate glslang type to SPIR-V storage class.
852spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
853{
854 if (type.getQualifier().isPipeInput())
855 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600856 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -0600857 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600858
859 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
860 type.getQualifier().storage == glslang::EvqUniform) {
861 if (type.getBasicType() == glslang::EbtAtomicUint)
862 return spv::StorageClassAtomicCounter;
863 if (type.containsOpaque())
864 return spv::StorageClassUniformConstant;
865 }
866
867 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -0700868 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -0600869 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600870 }
871
872 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600873 if (type.getQualifier().layoutPushConstant)
874 return spv::StorageClassPushConstant;
875 if (type.getBasicType() == glslang::EbtBlock)
876 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600877 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600878 }
John Kessenichbed4e4f2017-09-08 02:38:07 -0600879
880 switch (type.getQualifier().storage) {
881 case glslang::EvqShared: return spv::StorageClassWorkgroup;
882 case glslang::EvqGlobal: return spv::StorageClassPrivate;
883 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
884 case glslang::EvqTemporary: return spv::StorageClassFunction;
885 default:
886 assert(0);
887 break;
888 }
889
890 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600891}
892
qining25262b32016-05-06 17:25:16 -0400893// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700894// descriptor set.
895bool IsDescriptorResource(const glslang::TType& type)
896{
John Kessenichf7497e22016-03-08 21:36:22 -0700897 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700898 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700899 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700900
901 // non block...
902 // basically samplerXXX/subpass/sampler/texture are all included
903 // if they are the global-scope-class, not the function parameter
904 // (or local, if they ever exist) class.
905 if (type.getBasicType() == glslang::EbtSampler)
906 return type.getQualifier().isUniformOrBuffer();
907
908 // None of the above.
909 return false;
910}
911
John Kesseniche0b6cad2015-12-24 10:30:13 -0700912void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
913{
914 if (child.layoutMatrix == glslang::ElmNone)
915 child.layoutMatrix = parent.layoutMatrix;
916
917 if (parent.invariant)
918 child.invariant = true;
919 if (parent.nopersp)
920 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800921#ifdef AMD_EXTENSIONS
922 if (parent.explicitInterp)
923 child.explicitInterp = true;
924#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700925 if (parent.flat)
926 child.flat = true;
927 if (parent.centroid)
928 child.centroid = true;
929 if (parent.patch)
930 child.patch = true;
931 if (parent.sample)
932 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800933 if (parent.coherent)
934 child.coherent = true;
935 if (parent.volatil)
936 child.volatil = true;
937 if (parent.restrict)
938 child.restrict = true;
939 if (parent.readonly)
940 child.readonly = true;
941 if (parent.writeonly)
942 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700943}
944
John Kessenichf2b7f332016-09-01 17:05:23 -0600945bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700946{
John Kessenich7b9fa252016-01-21 18:56:57 -0700947 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600948 // - struct members might inherit from a struct declaration
949 // (note that non-block structs don't explicitly inherit,
950 // only implicitly, meaning no decoration involved)
951 // - affect decorations on the struct members
952 // (note smooth does not, and expecting something like volatile
953 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700954 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600955 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700956}
957
John Kessenich140f3df2015-06-26 16:58:36 -0600958//
959// Implement the TGlslangToSpvTraverser class.
960//
961
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700962TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -0600963 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
964 : TIntermTraverser(true, false, true),
965 options(options),
966 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600967 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700968 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700969 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600970 glslangIntermediate(glslangIntermediate)
971{
972 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
973
974 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -0600975 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
976 glslangIntermediate->getVersion());
977
John Kessenich121853f2017-05-31 17:11:16 -0600978 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -0600979 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -0600980 builder.setSourceFile(glslangIntermediate->getSourceFile());
981
982 // Set the source shader's text. If for SPV version 1.0, include
983 // a preamble in comments stating the OpModuleProcessed instructions.
984 // Otherwise, emit those as actual instructions.
985 std::string text;
986 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
987 for (int p = 0; p < (int)processes.size(); ++p) {
988 if (glslangIntermediate->getSpv().spv < 0x00010100) {
989 text.append("// OpModuleProcessed ");
990 text.append(processes[p]);
991 text.append("\n");
992 } else
993 builder.addModuleProcessed(processes[p]);
994 }
995 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
996 text.append("#line 1\n");
997 text.append(glslangIntermediate->getSourceText());
998 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -0600999 }
John Kessenich140f3df2015-06-26 16:58:36 -06001000 stdBuiltins = builder.import("GLSL.std.450");
1001 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -06001002 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1003 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001004
1005 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001006 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1007 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001008 builder.addSourceExtension(it->c_str());
1009
1010 // Add the top-level modes for this shader.
1011
John Kessenich92187592016-02-01 13:45:25 -07001012 if (glslangIntermediate->getXfbMode()) {
1013 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001014 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001015 }
John Kessenich140f3df2015-06-26 16:58:36 -06001016
1017 unsigned int mode;
1018 switch (glslangIntermediate->getStage()) {
1019 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001020 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001021 break;
1022
steve-lunarge7412492017-03-23 11:56:07 -06001023 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001024 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001025 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001026
steve-lunarge7412492017-03-23 11:56:07 -06001027 glslang::TLayoutGeometry primitive;
1028
1029 if (glslangIntermediate->getStage() == EShLangTessControl) {
1030 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1031 primitive = glslangIntermediate->getOutputPrimitive();
1032 } else {
1033 primitive = glslangIntermediate->getInputPrimitive();
1034 }
1035
1036 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001037 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1038 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1039 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001040 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001041 }
John Kessenich4016e382016-07-15 11:53:56 -06001042 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001043 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1044
John Kesseniche6903322015-10-13 16:29:02 -06001045 switch (glslangIntermediate->getVertexSpacing()) {
1046 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1047 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1048 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001049 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001050 }
John Kessenich4016e382016-07-15 11:53:56 -06001051 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001052 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1053
1054 switch (glslangIntermediate->getVertexOrder()) {
1055 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1056 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001057 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001058 }
John Kessenich4016e382016-07-15 11:53:56 -06001059 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001060 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1061
1062 if (glslangIntermediate->getPointMode())
1063 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001064 break;
1065
1066 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001067 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001068 switch (glslangIntermediate->getInputPrimitive()) {
1069 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1070 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1071 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001072 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001073 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001074 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001075 }
John Kessenich4016e382016-07-15 11:53:56 -06001076 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001077 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001078
John Kessenich140f3df2015-06-26 16:58:36 -06001079 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1080
1081 switch (glslangIntermediate->getOutputPrimitive()) {
1082 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1083 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1084 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001085 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001086 }
John Kessenich4016e382016-07-15 11:53:56 -06001087 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001088 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1089 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1090 break;
1091
1092 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001093 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001094 if (glslangIntermediate->getPixelCenterInteger())
1095 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001096
John Kessenich140f3df2015-06-26 16:58:36 -06001097 if (glslangIntermediate->getOriginUpperLeft())
1098 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001099 else
1100 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001101
1102 if (glslangIntermediate->getEarlyFragmentTests())
1103 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1104
chaocc1204522017-06-30 17:14:30 -07001105 if (glslangIntermediate->getPostDepthCoverage()) {
1106 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1107 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1108 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1109 }
1110
John Kesseniche6903322015-10-13 16:29:02 -06001111 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001112 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1113 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001114 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001115 }
John Kessenich4016e382016-07-15 11:53:56 -06001116 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001117 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1118
1119 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1120 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001121 break;
1122
1123 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001124 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001125 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1126 glslangIntermediate->getLocalSize(1),
1127 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001128 break;
1129
1130 default:
1131 break;
1132 }
John Kessenich140f3df2015-06-26 16:58:36 -06001133}
1134
John Kessenichfca82622016-11-26 13:23:20 -07001135// Finish creating SPV, after the traversal is complete.
1136void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001137{
John Kessenich517fe7a2016-11-26 13:31:47 -07001138 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001139 builder.setBuildPoint(shaderEntry->getLastBlock());
1140 builder.leaveFunction();
1141 }
1142
John Kessenich7ba63412015-12-20 17:37:07 -07001143 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001144 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1145 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001146
qiningda397332016-03-09 19:54:03 -05001147 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001148}
1149
John Kessenichfca82622016-11-26 13:23:20 -07001150// Write the SPV into 'out'.
1151void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001152{
John Kessenichfca82622016-11-26 13:23:20 -07001153 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001154}
1155
1156//
1157// Implement the traversal functions.
1158//
1159// Return true from interior nodes to have the external traversal
1160// continue on to children. Return false if children were
1161// already processed.
1162//
1163
1164//
qining25262b32016-05-06 17:25:16 -04001165// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001166// - uniform/input reads
1167// - output writes
1168// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1169// - something simple that degenerates into the last bullet
1170//
1171void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1172{
qining75d1d802016-04-06 14:42:01 -04001173 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1174 if (symbol->getType().getQualifier().isSpecConstant())
1175 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1176
John Kessenich140f3df2015-06-26 16:58:36 -06001177 // getSymbolId() will set up all the IO decorations on the first call.
1178 // Formal function parameters were mapped during makeFunctions().
1179 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001180
1181 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1182 if (builder.isPointer(id)) {
1183 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001184 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1185 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1186 iOSet.insert(id);
1187 }
John Kessenich7ba63412015-12-20 17:37:07 -07001188 }
1189
1190 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001191 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001192 // Prepare to generate code for the access
1193
1194 // L-value chains will be computed left to right. We're on the symbol now,
1195 // which is the left-most part of the access chain, so now is "clear" time,
1196 // followed by setting the base.
1197 builder.clearAccessChain();
1198
1199 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001200 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001201 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001202 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001203 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001204 // These are also pure R-values.
1205 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001206 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001207 builder.setAccessChainRValue(id);
1208 else
1209 builder.setAccessChainLValue(id);
1210 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001211
1212 // Process linkage-only nodes for any special additional interface work.
1213 if (linkageOnly) {
1214 if (glslangIntermediate->getHlslFunctionality1()) {
1215 // Map implicit counter buffers to their originating buffers, which should have been
1216 // seen by now, given earlier pruning of unused counters, and preservation of order
1217 // of declaration.
1218 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1219 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1220 // Save possible originating buffers for counter buffers, keyed by
1221 // making the potential counter-buffer name.
1222 std::string keyName = symbol->getName().c_str();
1223 keyName = glslangIntermediate->addCounterBufferName(keyName);
1224 counterOriginator[keyName] = symbol;
1225 } else {
1226 // Handle a counter buffer, by finding the saved originating buffer.
1227 std::string keyName = symbol->getName().c_str();
1228 auto it = counterOriginator.find(keyName);
1229 if (it != counterOriginator.end()) {
1230 id = getSymbolId(it->second);
1231 if (id != spv::NoResult) {
1232 spv::Id counterId = getSymbolId(symbol);
1233 if (counterId != spv::NoResult)
1234 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
1235 }
1236 }
1237 }
1238 }
1239 }
1240 }
John Kessenich140f3df2015-06-26 16:58:36 -06001241}
1242
1243bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1244{
John Kesseniche485c7a2017-05-31 18:50:53 -06001245 builder.setLine(node->getLoc().line);
1246
qining40887662016-04-03 22:20:42 -04001247 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1248 if (node->getType().getQualifier().isSpecConstant())
1249 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1250
John Kessenich140f3df2015-06-26 16:58:36 -06001251 // First, handle special cases
1252 switch (node->getOp()) {
1253 case glslang::EOpAssign:
1254 case glslang::EOpAddAssign:
1255 case glslang::EOpSubAssign:
1256 case glslang::EOpMulAssign:
1257 case glslang::EOpVectorTimesMatrixAssign:
1258 case glslang::EOpVectorTimesScalarAssign:
1259 case glslang::EOpMatrixTimesScalarAssign:
1260 case glslang::EOpMatrixTimesMatrixAssign:
1261 case glslang::EOpDivAssign:
1262 case glslang::EOpModAssign:
1263 case glslang::EOpAndAssign:
1264 case glslang::EOpInclusiveOrAssign:
1265 case glslang::EOpExclusiveOrAssign:
1266 case glslang::EOpLeftShiftAssign:
1267 case glslang::EOpRightShiftAssign:
1268 // A bin-op assign "a += b" means the same thing as "a = a + b"
1269 // where a is evaluated before b. For a simple assignment, GLSL
1270 // says to evaluate the left before the right. So, always, left
1271 // node then right node.
1272 {
1273 // get the left l-value, save it away
1274 builder.clearAccessChain();
1275 node->getLeft()->traverse(this);
1276 spv::Builder::AccessChain lValue = builder.getAccessChain();
1277
1278 // evaluate the right
1279 builder.clearAccessChain();
1280 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001281 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001282
1283 if (node->getOp() != glslang::EOpAssign) {
1284 // the left is also an r-value
1285 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001286 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001287
1288 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001289 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
1290 TranslateNoContractionDecoration(node->getType().getQualifier()) };
1291 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001292 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1293 node->getType().getBasicType());
1294
1295 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001296 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001297 }
1298
1299 // store the result
1300 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001301 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001302
1303 // assignments are expressions having an rValue after they are evaluated...
1304 builder.clearAccessChain();
1305 builder.setAccessChainRValue(rValue);
1306 }
1307 return false;
1308 case glslang::EOpIndexDirect:
1309 case glslang::EOpIndexDirectStruct:
1310 {
1311 // Get the left part of the access chain.
1312 node->getLeft()->traverse(this);
1313
1314 // Add the next element in the chain
1315
David Netoa901ffe2016-06-08 14:11:40 +01001316 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001317 if (! node->getLeft()->getType().isArray() &&
1318 node->getLeft()->getType().isVector() &&
1319 node->getOp() == glslang::EOpIndexDirect) {
1320 // This is essentially a hard-coded vector swizzle of size 1,
1321 // so short circuit the access-chain stuff with a swizzle.
1322 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001323 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001324 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001325 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001326 int spvIndex = glslangIndex;
1327 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1328 node->getOp() == glslang::EOpIndexDirectStruct)
1329 {
1330 // This may be, e.g., an anonymous block-member selection, which generally need
1331 // index remapping due to hidden members in anonymous blocks.
1332 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1333 assert(remapper.size() > 0);
1334 spvIndex = remapper[glslangIndex];
1335 }
John Kessenichebb50532016-05-16 19:22:05 -06001336
David Netoa901ffe2016-06-08 14:11:40 +01001337 // normal case for indexing array or structure or block
1338 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1339
1340 // Add capabilities here for accessing PointSize and clip/cull distance.
1341 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001342 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001343 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001344 }
1345 }
1346 return false;
1347 case glslang::EOpIndexIndirect:
1348 {
1349 // Structure or array or vector indirection.
1350 // Will use native SPIR-V access-chain for struct and array indirection;
1351 // matrices are arrays of vectors, so will also work for a matrix.
1352 // Will use the access chain's 'component' for variable index into a vector.
1353
1354 // This adapter is building access chains left to right.
1355 // Set up the access chain to the left.
1356 node->getLeft()->traverse(this);
1357
1358 // save it so that computing the right side doesn't trash it
1359 spv::Builder::AccessChain partial = builder.getAccessChain();
1360
1361 // compute the next index in the chain
1362 builder.clearAccessChain();
1363 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001364 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001365
1366 // restore the saved access chain
1367 builder.setAccessChain(partial);
1368
1369 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001370 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001371 else
John Kessenichfa668da2015-09-13 14:46:30 -06001372 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001373 }
1374 return false;
1375 case glslang::EOpVectorSwizzle:
1376 {
1377 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001378 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001379 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001380 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001381 }
1382 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001383 case glslang::EOpMatrixSwizzle:
1384 logger->missingFunctionality("matrix swizzle");
1385 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001386 case glslang::EOpLogicalOr:
1387 case glslang::EOpLogicalAnd:
1388 {
1389
1390 // These may require short circuiting, but can sometimes be done as straight
1391 // binary operations. The right operand must be short circuited if it has
1392 // side effects, and should probably be if it is complex.
1393 if (isTrivial(node->getRight()->getAsTyped()))
1394 break; // handle below as a normal binary operation
1395 // otherwise, we need to do dynamic short circuiting on the right operand
1396 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1397 builder.clearAccessChain();
1398 builder.setAccessChainRValue(result);
1399 }
1400 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001401 default:
1402 break;
1403 }
1404
1405 // Assume generic binary op...
1406
John Kessenich32cfd492016-02-02 12:37:46 -07001407 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001408 builder.clearAccessChain();
1409 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001410 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001411
John Kessenich32cfd492016-02-02 12:37:46 -07001412 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001413 builder.clearAccessChain();
1414 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001415 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001416
John Kessenich32cfd492016-02-02 12:37:46 -07001417 // get result
John Kessenichead86222018-03-28 18:01:20 -06001418 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
1419 TranslateNoContractionDecoration(node->getType().getQualifier()) };
1420 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001421 convertGlslangToSpvType(node->getType()), left, right,
1422 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001423
John Kessenich50e57562015-12-21 21:21:11 -07001424 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001425 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001426 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001427 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001428 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001429 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001430 return false;
1431 }
John Kessenich140f3df2015-06-26 16:58:36 -06001432}
1433
1434bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1435{
John Kesseniche485c7a2017-05-31 18:50:53 -06001436 builder.setLine(node->getLoc().line);
1437
qining40887662016-04-03 22:20:42 -04001438 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1439 if (node->getType().getQualifier().isSpecConstant())
1440 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1441
John Kessenichfc51d282015-08-19 13:34:18 -06001442 spv::Id result = spv::NoResult;
1443
1444 // try texturing first
1445 result = createImageTextureFunctionCall(node);
1446 if (result != spv::NoResult) {
1447 builder.clearAccessChain();
1448 builder.setAccessChainRValue(result);
1449
1450 return false; // done with this node
1451 }
1452
1453 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001454
1455 if (node->getOp() == glslang::EOpArrayLength) {
1456 // Quite special; won't want to evaluate the operand.
1457
1458 // Normal .length() would have been constant folded by the front-end.
1459 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001460 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001461
John Kessenichc9a80832015-09-12 12:17:44 -06001462 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1463 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001464 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1465 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001466
1467 builder.clearAccessChain();
1468 builder.setAccessChainRValue(length);
1469
1470 return false;
1471 }
1472
John Kessenichfc51d282015-08-19 13:34:18 -06001473 // Start by evaluating the operand
1474
John Kessenich8c8505c2016-07-26 12:50:38 -06001475 // Does it need a swizzle inversion? If so, evaluation is inverted;
1476 // operate first on the swizzle base, then apply the swizzle.
1477 spv::Id invertedType = spv::NoType;
1478 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1479 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1480 invertedType = getInvertedSwizzleType(*node->getOperand());
1481
John Kessenich140f3df2015-06-26 16:58:36 -06001482 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001483 if (invertedType != spv::NoType)
1484 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1485 else
1486 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001487
Rex Xufc618912015-09-09 16:42:49 +08001488 spv::Id operand = spv::NoResult;
1489
1490 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1491 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001492 node->getOp() == glslang::EOpAtomicCounter ||
1493 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001494 operand = builder.accessChainGetLValue(); // Special case l-value operands
1495 else
John Kessenich32cfd492016-02-02 12:37:46 -07001496 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001497
John Kessenichead86222018-03-28 18:01:20 -06001498 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
1499 TranslateNoContractionDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001500
1501 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001502 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001503 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001504
1505 // if not, then possibly an operation
1506 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001507 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001508
1509 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001510 if (invertedType)
John Kessenichead86222018-03-28 18:01:20 -06001511 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich8c8505c2016-07-26 12:50:38 -06001512
John Kessenich140f3df2015-06-26 16:58:36 -06001513 builder.clearAccessChain();
1514 builder.setAccessChainRValue(result);
1515
1516 return false; // done with this node
1517 }
1518
1519 // it must be a special case, check...
1520 switch (node->getOp()) {
1521 case glslang::EOpPostIncrement:
1522 case glslang::EOpPostDecrement:
1523 case glslang::EOpPreIncrement:
1524 case glslang::EOpPreDecrement:
1525 {
1526 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001527 spv::Id one = 0;
1528 if (node->getBasicType() == glslang::EbtFloat)
1529 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001530 else if (node->getBasicType() == glslang::EbtDouble)
1531 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001532 else if (node->getBasicType() == glslang::EbtFloat16)
1533 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001534 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1535 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001536 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1537 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001538 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1539 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001540 else
1541 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001542 glslang::TOperator op;
1543 if (node->getOp() == glslang::EOpPreIncrement ||
1544 node->getOp() == glslang::EOpPostIncrement)
1545 op = glslang::EOpAdd;
1546 else
1547 op = glslang::EOpSub;
1548
John Kessenichead86222018-03-28 18:01:20 -06001549 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001550 convertGlslangToSpvType(node->getType()), operand, one,
1551 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001552 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001553
1554 // The result of operation is always stored, but conditionally the
1555 // consumed result. The consumed result is always an r-value.
1556 builder.accessChainStore(result);
1557 builder.clearAccessChain();
1558 if (node->getOp() == glslang::EOpPreIncrement ||
1559 node->getOp() == glslang::EOpPreDecrement)
1560 builder.setAccessChainRValue(result);
1561 else
1562 builder.setAccessChainRValue(operand);
1563 }
1564
1565 return false;
1566
1567 case glslang::EOpEmitStreamVertex:
1568 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1569 return false;
1570 case glslang::EOpEndStreamPrimitive:
1571 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1572 return false;
1573
1574 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001575 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001576 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001577 }
John Kessenich140f3df2015-06-26 16:58:36 -06001578}
1579
1580bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1581{
qining27e04a02016-04-14 16:40:20 -04001582 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1583 if (node->getType().getQualifier().isSpecConstant())
1584 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1585
John Kessenichfc51d282015-08-19 13:34:18 -06001586 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001587 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1588 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001589
1590 // try texturing
1591 result = createImageTextureFunctionCall(node);
1592 if (result != spv::NoResult) {
1593 builder.clearAccessChain();
1594 builder.setAccessChainRValue(result);
1595
1596 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001597#ifdef AMD_EXTENSIONS
1598 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1599#else
John Kessenich56bab042015-09-16 10:54:31 -06001600 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001601#endif
Rex Xufc618912015-09-09 16:42:49 +08001602 // "imageStore" is a special case, which has no result
1603 return false;
1604 }
John Kessenichfc51d282015-08-19 13:34:18 -06001605
John Kessenich140f3df2015-06-26 16:58:36 -06001606 glslang::TOperator binOp = glslang::EOpNull;
1607 bool reduceComparison = true;
1608 bool isMatrix = false;
1609 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001610 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001611
1612 assert(node->getOp());
1613
John Kessenichf6640762016-08-01 19:44:00 -06001614 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001615
1616 switch (node->getOp()) {
1617 case glslang::EOpSequence:
1618 {
1619 if (preVisit)
1620 ++sequenceDepth;
1621 else
1622 --sequenceDepth;
1623
1624 if (sequenceDepth == 1) {
1625 // If this is the parent node of all the functions, we want to see them
1626 // early, so all call points have actual SPIR-V functions to reference.
1627 // In all cases, still let the traverser visit the children for us.
1628 makeFunctions(node->getAsAggregate()->getSequence());
1629
John Kessenich6fccb3c2016-09-19 16:01:41 -06001630 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001631 // anything else gets there, so visit out of order, doing them all now.
1632 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1633
John Kessenich6a60c2f2016-12-08 21:01:59 -07001634 // 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 -06001635 // so do them manually.
1636 visitFunctions(node->getAsAggregate()->getSequence());
1637
1638 return false;
1639 }
1640
1641 return true;
1642 }
1643 case glslang::EOpLinkerObjects:
1644 {
1645 if (visit == glslang::EvPreVisit)
1646 linkageOnly = true;
1647 else
1648 linkageOnly = false;
1649
1650 return true;
1651 }
1652 case glslang::EOpComma:
1653 {
1654 // processing from left to right naturally leaves the right-most
1655 // lying around in the access chain
1656 glslang::TIntermSequence& glslangOperands = node->getSequence();
1657 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1658 glslangOperands[i]->traverse(this);
1659
1660 return false;
1661 }
1662 case glslang::EOpFunction:
1663 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001664 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001665 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001666 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001667 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001668 } else {
1669 handleFunctionEntry(node);
1670 }
1671 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001672 if (inEntryPoint)
1673 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001674 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001675 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001676 }
1677
1678 return true;
1679 case glslang::EOpParameters:
1680 // Parameters will have been consumed by EOpFunction processing, but not
1681 // the body, so we still visited the function node's children, making this
1682 // child redundant.
1683 return false;
1684 case glslang::EOpFunctionCall:
1685 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001686 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001687 if (node->isUserDefined())
1688 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001689 // 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 -07001690 if (result) {
1691 builder.clearAccessChain();
1692 builder.setAccessChainRValue(result);
1693 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001694 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001695
1696 return false;
1697 }
1698 case glslang::EOpConstructMat2x2:
1699 case glslang::EOpConstructMat2x3:
1700 case glslang::EOpConstructMat2x4:
1701 case glslang::EOpConstructMat3x2:
1702 case glslang::EOpConstructMat3x3:
1703 case glslang::EOpConstructMat3x4:
1704 case glslang::EOpConstructMat4x2:
1705 case glslang::EOpConstructMat4x3:
1706 case glslang::EOpConstructMat4x4:
1707 case glslang::EOpConstructDMat2x2:
1708 case glslang::EOpConstructDMat2x3:
1709 case glslang::EOpConstructDMat2x4:
1710 case glslang::EOpConstructDMat3x2:
1711 case glslang::EOpConstructDMat3x3:
1712 case glslang::EOpConstructDMat3x4:
1713 case glslang::EOpConstructDMat4x2:
1714 case glslang::EOpConstructDMat4x3:
1715 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001716 case glslang::EOpConstructIMat2x2:
1717 case glslang::EOpConstructIMat2x3:
1718 case glslang::EOpConstructIMat2x4:
1719 case glslang::EOpConstructIMat3x2:
1720 case glslang::EOpConstructIMat3x3:
1721 case glslang::EOpConstructIMat3x4:
1722 case glslang::EOpConstructIMat4x2:
1723 case glslang::EOpConstructIMat4x3:
1724 case glslang::EOpConstructIMat4x4:
1725 case glslang::EOpConstructUMat2x2:
1726 case glslang::EOpConstructUMat2x3:
1727 case glslang::EOpConstructUMat2x4:
1728 case glslang::EOpConstructUMat3x2:
1729 case glslang::EOpConstructUMat3x3:
1730 case glslang::EOpConstructUMat3x4:
1731 case glslang::EOpConstructUMat4x2:
1732 case glslang::EOpConstructUMat4x3:
1733 case glslang::EOpConstructUMat4x4:
1734 case glslang::EOpConstructBMat2x2:
1735 case glslang::EOpConstructBMat2x3:
1736 case glslang::EOpConstructBMat2x4:
1737 case glslang::EOpConstructBMat3x2:
1738 case glslang::EOpConstructBMat3x3:
1739 case glslang::EOpConstructBMat3x4:
1740 case glslang::EOpConstructBMat4x2:
1741 case glslang::EOpConstructBMat4x3:
1742 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001743 case glslang::EOpConstructF16Mat2x2:
1744 case glslang::EOpConstructF16Mat2x3:
1745 case glslang::EOpConstructF16Mat2x4:
1746 case glslang::EOpConstructF16Mat3x2:
1747 case glslang::EOpConstructF16Mat3x3:
1748 case glslang::EOpConstructF16Mat3x4:
1749 case glslang::EOpConstructF16Mat4x2:
1750 case glslang::EOpConstructF16Mat4x3:
1751 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06001752 isMatrix = true;
1753 // fall through
1754 case glslang::EOpConstructFloat:
1755 case glslang::EOpConstructVec2:
1756 case glslang::EOpConstructVec3:
1757 case glslang::EOpConstructVec4:
1758 case glslang::EOpConstructDouble:
1759 case glslang::EOpConstructDVec2:
1760 case glslang::EOpConstructDVec3:
1761 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001762 case glslang::EOpConstructFloat16:
1763 case glslang::EOpConstructF16Vec2:
1764 case glslang::EOpConstructF16Vec3:
1765 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001766 case glslang::EOpConstructBool:
1767 case glslang::EOpConstructBVec2:
1768 case glslang::EOpConstructBVec3:
1769 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07001770 case glslang::EOpConstructInt8:
1771 case glslang::EOpConstructI8Vec2:
1772 case glslang::EOpConstructI8Vec3:
1773 case glslang::EOpConstructI8Vec4:
1774 case glslang::EOpConstructUint8:
1775 case glslang::EOpConstructU8Vec2:
1776 case glslang::EOpConstructU8Vec3:
1777 case glslang::EOpConstructU8Vec4:
1778 case glslang::EOpConstructInt16:
1779 case glslang::EOpConstructI16Vec2:
1780 case glslang::EOpConstructI16Vec3:
1781 case glslang::EOpConstructI16Vec4:
1782 case glslang::EOpConstructUint16:
1783 case glslang::EOpConstructU16Vec2:
1784 case glslang::EOpConstructU16Vec3:
1785 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001786 case glslang::EOpConstructInt:
1787 case glslang::EOpConstructIVec2:
1788 case glslang::EOpConstructIVec3:
1789 case glslang::EOpConstructIVec4:
1790 case glslang::EOpConstructUint:
1791 case glslang::EOpConstructUVec2:
1792 case glslang::EOpConstructUVec3:
1793 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001794 case glslang::EOpConstructInt64:
1795 case glslang::EOpConstructI64Vec2:
1796 case glslang::EOpConstructI64Vec3:
1797 case glslang::EOpConstructI64Vec4:
1798 case glslang::EOpConstructUint64:
1799 case glslang::EOpConstructU64Vec2:
1800 case glslang::EOpConstructU64Vec3:
1801 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001802 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001803 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001804 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001805 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001806 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001807 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001808 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001809 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001810 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001811 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001812 std::vector<spv::Id> constituents;
1813 for (int c = 0; c < (int)arguments.size(); ++c)
1814 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001815 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001816 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001817 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001818 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001819 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001820
1821 builder.clearAccessChain();
1822 builder.setAccessChainRValue(constructed);
1823
1824 return false;
1825 }
1826
1827 // These six are component-wise compares with component-wise results.
1828 // Forward on to createBinaryOperation(), requesting a vector result.
1829 case glslang::EOpLessThan:
1830 case glslang::EOpGreaterThan:
1831 case glslang::EOpLessThanEqual:
1832 case glslang::EOpGreaterThanEqual:
1833 case glslang::EOpVectorEqual:
1834 case glslang::EOpVectorNotEqual:
1835 {
1836 // Map the operation to a binary
1837 binOp = node->getOp();
1838 reduceComparison = false;
1839 switch (node->getOp()) {
1840 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1841 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1842 default: binOp = node->getOp(); break;
1843 }
1844
1845 break;
1846 }
1847 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001848 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001849 binOp = glslang::EOpMul;
1850 break;
1851 case glslang::EOpOuterProduct:
1852 // two vectors multiplied to make a matrix
1853 binOp = glslang::EOpOuterProduct;
1854 break;
1855 case glslang::EOpDot:
1856 {
qining25262b32016-05-06 17:25:16 -04001857 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001858 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001859 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001860 binOp = glslang::EOpMul;
1861 break;
1862 }
1863 case glslang::EOpMod:
1864 // when an aggregate, this is the floating-point mod built-in function,
1865 // which can be emitted by the one in createBinaryOperation()
1866 binOp = glslang::EOpMod;
1867 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001868 case glslang::EOpEmitVertex:
1869 case glslang::EOpEndPrimitive:
1870 case glslang::EOpBarrier:
1871 case glslang::EOpMemoryBarrier:
1872 case glslang::EOpMemoryBarrierAtomicCounter:
1873 case glslang::EOpMemoryBarrierBuffer:
1874 case glslang::EOpMemoryBarrierImage:
1875 case glslang::EOpMemoryBarrierShared:
1876 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07001877 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001878 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07001879 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001880 case glslang::EOpWorkgroupMemoryBarrier:
1881 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07001882 case glslang::EOpSubgroupBarrier:
1883 case glslang::EOpSubgroupMemoryBarrier:
1884 case glslang::EOpSubgroupMemoryBarrierBuffer:
1885 case glslang::EOpSubgroupMemoryBarrierImage:
1886 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06001887 noReturnValue = true;
1888 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1889 break;
1890
John Kessenich426394d2015-07-23 10:22:48 -06001891 case glslang::EOpAtomicAdd:
1892 case glslang::EOpAtomicMin:
1893 case glslang::EOpAtomicMax:
1894 case glslang::EOpAtomicAnd:
1895 case glslang::EOpAtomicOr:
1896 case glslang::EOpAtomicXor:
1897 case glslang::EOpAtomicExchange:
1898 case glslang::EOpAtomicCompSwap:
1899 atomic = true;
1900 break;
1901
John Kessenich0d0c6d32017-07-23 16:08:26 -06001902 case glslang::EOpAtomicCounterAdd:
1903 case glslang::EOpAtomicCounterSubtract:
1904 case glslang::EOpAtomicCounterMin:
1905 case glslang::EOpAtomicCounterMax:
1906 case glslang::EOpAtomicCounterAnd:
1907 case glslang::EOpAtomicCounterOr:
1908 case glslang::EOpAtomicCounterXor:
1909 case glslang::EOpAtomicCounterExchange:
1910 case glslang::EOpAtomicCounterCompSwap:
1911 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1912 builder.addCapability(spv::CapabilityAtomicStorageOps);
1913 atomic = true;
1914 break;
1915
John Kessenich140f3df2015-06-26 16:58:36 -06001916 default:
1917 break;
1918 }
1919
1920 //
1921 // See if it maps to a regular operation.
1922 //
John Kessenich140f3df2015-06-26 16:58:36 -06001923 if (binOp != glslang::EOpNull) {
1924 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1925 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1926 assert(left && right);
1927
1928 builder.clearAccessChain();
1929 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001930 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001931
1932 builder.clearAccessChain();
1933 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001934 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001935
John Kesseniche485c7a2017-05-31 18:50:53 -06001936 builder.setLine(node->getLoc().line);
John Kessenichead86222018-03-28 18:01:20 -06001937 OpDecorations decorations = { precision,
1938 TranslateNoContractionDecoration(node->getType().getQualifier()) };
1939 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06001940 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001941 left->getType().getBasicType(), reduceComparison);
1942
1943 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001944 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001945 builder.clearAccessChain();
1946 builder.setAccessChainRValue(result);
1947
1948 return false;
1949 }
1950
John Kessenich426394d2015-07-23 10:22:48 -06001951 //
1952 // Create the list of operands.
1953 //
John Kessenich140f3df2015-06-26 16:58:36 -06001954 glslang::TIntermSequence& glslangOperands = node->getSequence();
1955 std::vector<spv::Id> operands;
1956 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001957 // special case l-value operands; there are just a few
1958 bool lvalue = false;
1959 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001960 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001961 case glslang::EOpModf:
1962 if (arg == 1)
1963 lvalue = true;
1964 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001965 case glslang::EOpInterpolateAtSample:
1966 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001967#ifdef AMD_EXTENSIONS
1968 case glslang::EOpInterpolateAtVertex:
1969#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001970 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001971 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001972
1973 // Does it need a swizzle inversion? If so, evaluation is inverted;
1974 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001975 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001976 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1977 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1978 }
Rex Xu7a26c172015-12-08 17:12:09 +08001979 break;
Rex Xud4782c12015-09-06 16:30:11 +08001980 case glslang::EOpAtomicAdd:
1981 case glslang::EOpAtomicMin:
1982 case glslang::EOpAtomicMax:
1983 case glslang::EOpAtomicAnd:
1984 case glslang::EOpAtomicOr:
1985 case glslang::EOpAtomicXor:
1986 case glslang::EOpAtomicExchange:
1987 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06001988 case glslang::EOpAtomicCounterAdd:
1989 case glslang::EOpAtomicCounterSubtract:
1990 case glslang::EOpAtomicCounterMin:
1991 case glslang::EOpAtomicCounterMax:
1992 case glslang::EOpAtomicCounterAnd:
1993 case glslang::EOpAtomicCounterOr:
1994 case glslang::EOpAtomicCounterXor:
1995 case glslang::EOpAtomicCounterExchange:
1996 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08001997 if (arg == 0)
1998 lvalue = true;
1999 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002000 case glslang::EOpAddCarry:
2001 case glslang::EOpSubBorrow:
2002 if (arg == 2)
2003 lvalue = true;
2004 break;
2005 case glslang::EOpUMulExtended:
2006 case glslang::EOpIMulExtended:
2007 if (arg >= 2)
2008 lvalue = true;
2009 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002010 default:
2011 break;
2012 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002013 builder.clearAccessChain();
2014 if (invertedType != spv::NoType && arg == 0)
2015 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2016 else
2017 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002018 if (lvalue)
2019 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002020 else {
2021 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07002022 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002023 }
John Kessenich140f3df2015-06-26 16:58:36 -06002024 }
John Kessenich426394d2015-07-23 10:22:48 -06002025
John Kesseniche485c7a2017-05-31 18:50:53 -06002026 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06002027 if (atomic) {
2028 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002029 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002030 } else {
2031 // Pass through to generic operations.
2032 switch (glslangOperands.size()) {
2033 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002034 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002035 break;
2036 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002037 {
2038 OpDecorations decorations = { precision,
2039 TranslateNoContractionDecoration(node->getType().getQualifier()) };
2040 result = createUnaryOperation(
2041 node->getOp(), decorations,
2042 resultType(), operands.front(),
2043 glslangOperands[0]->getAsTyped()->getBasicType());
2044 }
John Kessenich426394d2015-07-23 10:22:48 -06002045 break;
2046 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002047 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002048 break;
2049 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002050 if (invertedType)
2051 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002052 }
2053
2054 if (noReturnValue)
2055 return false;
2056
2057 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002058 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002059 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002060 } else {
2061 builder.clearAccessChain();
2062 builder.setAccessChainRValue(result);
2063 return false;
2064 }
2065}
2066
John Kessenich433e9ff2017-01-26 20:31:11 -07002067// This path handles both if-then-else and ?:
2068// The if-then-else has a node type of void, while
2069// ?: has either a void or a non-void node type
2070//
2071// Leaving the result, when not void:
2072// GLSL only has r-values as the result of a :?, but
2073// if we have an l-value, that can be more efficient if it will
2074// become the base of a complex r-value expression, because the
2075// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002076bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2077{
John Kessenich4bee5312018-02-20 21:29:05 -07002078 // See if it simple and safe, or required, to execute both sides.
2079 // Crucially, side effects must be either semantically required or avoided,
2080 // and there are performance trade-offs.
2081 // Return true if required or a good idea (and safe) to execute both sides,
2082 // false otherwise.
2083 const auto bothSidesPolicy = [&]() -> bool {
2084 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002085 if (node->getTrueBlock() == nullptr ||
2086 node->getFalseBlock() == nullptr)
2087 return false;
2088
John Kessenich4bee5312018-02-20 21:29:05 -07002089 // required? (unless we write additional code to look for side effects
2090 // and make performance trade-offs if none are present)
2091 if (!node->getShortCircuit())
2092 return true;
2093
2094 // if not required to execute both, decide based on performance/practicality...
2095
2096 // see if OpSelect can handle it
2097 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2098 node->getBasicType() == glslang::EbtVoid)
2099 return false;
2100
John Kessenich433e9ff2017-01-26 20:31:11 -07002101 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2102 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2103
2104 // return true if a single operand to ? : is okay for OpSelect
2105 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002106 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002107 };
2108
2109 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2110 operandOkay(node->getFalseBlock()->getAsTyped());
2111 };
2112
John Kessenich4bee5312018-02-20 21:29:05 -07002113 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2114 // emit the condition before doing anything with selection
2115 node->getCondition()->traverse(this);
2116 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2117
2118 // Find a way of executing both sides and selecting the right result.
2119 const auto executeBothSides = [&]() -> void {
2120 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002121 node->getTrueBlock()->traverse(this);
2122 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2123 node->getFalseBlock()->traverse(this);
2124 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2125
John Kesseniche485c7a2017-05-31 18:50:53 -06002126 builder.setLine(node->getLoc().line);
2127
John Kessenich4bee5312018-02-20 21:29:05 -07002128 // done if void
2129 if (node->getBasicType() == glslang::EbtVoid)
2130 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002131
John Kessenich4bee5312018-02-20 21:29:05 -07002132 // emit code to select between trueValue and falseValue
2133
2134 // see if OpSelect can handle it
2135 if (node->getType().isScalar() || node->getType().isVector()) {
2136 // Emit OpSelect for this selection.
2137
2138 // smear condition to vector, if necessary (AST is always scalar)
2139 if (builder.isVector(trueValue))
2140 condition = builder.smearScalar(spv::NoPrecision, condition,
2141 builder.makeVectorType(builder.makeBoolType(),
2142 builder.getNumComponents(trueValue)));
2143
2144 // OpSelect
2145 result = builder.createTriOp(spv::OpSelect,
2146 convertGlslangToSpvType(node->getType()), condition,
2147 trueValue, falseValue);
2148
2149 builder.clearAccessChain();
2150 builder.setAccessChainRValue(result);
2151 } else {
2152 // We need control flow to select the result.
2153 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2154 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2155
2156 // Selection control:
2157 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2158
2159 // make an "if" based on the value created by the condition
2160 spv::Builder::If ifBuilder(condition, control, builder);
2161
2162 // emit the "then" statement
2163 builder.createStore(trueValue, result);
2164 ifBuilder.makeBeginElse();
2165 // emit the "else" statement
2166 builder.createStore(falseValue, result);
2167
2168 // finish off the control flow
2169 ifBuilder.makeEndIf();
2170
2171 builder.clearAccessChain();
2172 builder.setAccessChainLValue(result);
2173 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002174 };
2175
John Kessenich4bee5312018-02-20 21:29:05 -07002176 // Execute the one side needed, as per the condition
2177 const auto executeOneSide = [&]() {
2178 // Always emit control flow.
2179 if (node->getBasicType() != glslang::EbtVoid)
2180 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002181
John Kessenich4bee5312018-02-20 21:29:05 -07002182 // Selection control:
2183 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2184
2185 // make an "if" based on the value created by the condition
2186 spv::Builder::If ifBuilder(condition, control, builder);
2187
2188 // emit the "then" statement
2189 if (node->getTrueBlock() != nullptr) {
2190 node->getTrueBlock()->traverse(this);
2191 if (result != spv::NoResult)
2192 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2193 }
2194
2195 if (node->getFalseBlock() != nullptr) {
2196 ifBuilder.makeBeginElse();
2197 // emit the "else" statement
2198 node->getFalseBlock()->traverse(this);
2199 if (result != spv::NoResult)
2200 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2201 }
2202
2203 // finish off the control flow
2204 ifBuilder.makeEndIf();
2205
2206 if (result != spv::NoResult) {
2207 builder.clearAccessChain();
2208 builder.setAccessChainLValue(result);
2209 }
2210 };
2211
2212 // Try for OpSelect (or a requirement to execute both sides)
2213 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002214 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2215 if (node->getType().getQualifier().isSpecConstant())
2216 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002217 executeBothSides();
2218 } else
2219 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002220
2221 return false;
2222}
2223
2224bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2225{
2226 // emit and get the condition before doing anything with switch
2227 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002228 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002229
Rex Xu57e65922017-07-04 23:23:40 +08002230 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002231 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002232
John Kessenich140f3df2015-06-26 16:58:36 -06002233 // browse the children to sort out code segments
2234 int defaultSegment = -1;
2235 std::vector<TIntermNode*> codeSegments;
2236 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2237 std::vector<int> caseValues;
2238 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2239 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2240 TIntermNode* child = *c;
2241 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002242 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002243 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002244 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002245 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2246 } else
2247 codeSegments.push_back(child);
2248 }
2249
qining25262b32016-05-06 17:25:16 -04002250 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002251 // statements between the last case and the end of the switch statement
2252 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2253 (int)codeSegments.size() == defaultSegment)
2254 codeSegments.push_back(nullptr);
2255
2256 // make the switch statement
2257 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002258 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002259
2260 // emit all the code in the segments
2261 breakForLoop.push(false);
2262 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2263 builder.nextSwitchSegment(segmentBlocks, s);
2264 if (codeSegments[s])
2265 codeSegments[s]->traverse(this);
2266 else
2267 builder.addSwitchBreak();
2268 }
2269 breakForLoop.pop();
2270
2271 builder.endSwitch(segmentBlocks);
2272
2273 return false;
2274}
2275
2276void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2277{
2278 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002279 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002280
2281 builder.clearAccessChain();
2282 builder.setAccessChainRValue(constant);
2283}
2284
2285bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2286{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002287 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002288 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002289
2290 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002291 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2292 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002293
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002294 // Spec requires back edges to target header blocks, and every header block
2295 // must dominate its merge block. Make a header block first to ensure these
2296 // conditions are met. By definition, it will contain OpLoopMerge, followed
2297 // by a block-ending branch. But we don't want to put any other body/test
2298 // instructions in it, since the body/test may have arbitrary instructions,
2299 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002300 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002301 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002302 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002303 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002304 spv::Block& test = builder.makeNewBlock();
2305 builder.createBranch(&test);
2306
2307 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002308 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002309 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002310 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2311
2312 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002313 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002314 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002315 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002316 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002317 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002318
2319 builder.setBuildPoint(&blocks.continue_target);
2320 if (node->getTerminal())
2321 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002322 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002323 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002324 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002325 builder.createBranch(&blocks.body);
2326
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002327 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002328 builder.setBuildPoint(&blocks.body);
2329 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002330 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002331 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002332 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002333
2334 builder.setBuildPoint(&blocks.continue_target);
2335 if (node->getTerminal())
2336 node->getTerminal()->traverse(this);
2337 if (node->getTest()) {
2338 node->getTest()->traverse(this);
2339 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002340 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002341 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002342 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002343 // TODO: unless there was a break/return/discard instruction
2344 // somewhere in the body, this is an infinite loop, so we should
2345 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002346 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002347 }
John Kessenich140f3df2015-06-26 16:58:36 -06002348 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002349 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002350 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002351 return false;
2352}
2353
2354bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2355{
2356 if (node->getExpression())
2357 node->getExpression()->traverse(this);
2358
John Kesseniche485c7a2017-05-31 18:50:53 -06002359 builder.setLine(node->getLoc().line);
2360
John Kessenich140f3df2015-06-26 16:58:36 -06002361 switch (node->getFlowOp()) {
2362 case glslang::EOpKill:
2363 builder.makeDiscard();
2364 break;
2365 case glslang::EOpBreak:
2366 if (breakForLoop.top())
2367 builder.createLoopExit();
2368 else
2369 builder.addSwitchBreak();
2370 break;
2371 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002372 builder.createLoopContinue();
2373 break;
2374 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002375 if (node->getExpression()) {
2376 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2377 spv::Id returnId = accessChainLoad(glslangReturnType);
2378 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2379 builder.clearAccessChain();
2380 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2381 builder.setAccessChainLValue(copyId);
2382 multiTypeStore(glslangReturnType, returnId);
2383 returnId = builder.createLoad(copyId);
2384 }
2385 builder.makeReturn(false, returnId);
2386 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002387 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002388
2389 builder.clearAccessChain();
2390 break;
2391
2392 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002393 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002394 break;
2395 }
2396
2397 return false;
2398}
2399
2400spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2401{
qining25262b32016-05-06 17:25:16 -04002402 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002403 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002404 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002405 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002406 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002407 }
2408
2409 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002410 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002411 spv::Id spvType = convertGlslangToSpvType(node->getType());
2412
Rex Xucabbb782017-03-24 13:41:14 +08002413 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2414 node->getType().containsBasicType(glslang::EbtInt16) ||
2415 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002416 if (contains16BitType) {
2417 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
John Kessenich66011cb2018-03-06 16:12:04 -07002418 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002419 builder.addCapability(spv::CapabilityStorageInputOutput16);
2420 } else if (storageClass == spv::StorageClassPushConstant) {
John Kessenich66011cb2018-03-06 16:12:04 -07002421 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002422 builder.addCapability(spv::CapabilityStoragePushConstant16);
2423 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich66011cb2018-03-06 16:12:04 -07002424 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002425 builder.addCapability(spv::CapabilityStorageUniform16);
2426 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2427 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2428 }
2429 }
Rex Xuf89ad982017-04-07 23:22:33 +08002430
John Kessenich140f3df2015-06-26 16:58:36 -06002431 const char* name = node->getName().c_str();
2432 if (glslang::IsAnonymous(name))
2433 name = "";
2434
2435 return builder.createVariable(storageClass, spvType, name);
2436}
2437
2438// Return type Id of the sampled type.
2439spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2440{
2441 switch (sampler.type) {
2442 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08002443#ifdef AMD_EXTENSIONS
2444 case glslang::EbtFloat16:
2445 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
2446 builder.addCapability(spv::CapabilityFloat16ImageAMD);
2447 return builder.makeFloatType(16);
2448#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002449 case glslang::EbtInt: return builder.makeIntType(32);
2450 case glslang::EbtUint: return builder.makeUintType(32);
2451 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002452 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002453 return builder.makeFloatType(32);
2454 }
2455}
2456
John Kessenich8c8505c2016-07-26 12:50:38 -06002457// If node is a swizzle operation, return the type that should be used if
2458// the swizzle base is first consumed by another operation, before the swizzle
2459// is applied.
2460spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2461{
John Kessenichecba76f2017-01-06 00:34:48 -07002462 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002463 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2464 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2465 else
2466 return spv::NoType;
2467}
2468
2469// When inverting a swizzle with a parent op, this function
2470// will apply the swizzle operation to a completed parent operation.
2471spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2472{
2473 std::vector<unsigned> swizzle;
2474 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2475 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2476}
2477
John Kessenich8c8505c2016-07-26 12:50:38 -06002478// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2479void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2480{
2481 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2482 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2483 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2484}
2485
John Kessenich3ac051e2015-12-20 11:29:16 -07002486// Convert from a glslang type to an SPV type, by calling into a
2487// recursive version of this function. This establishes the inherited
2488// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002489spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2490{
John Kessenichead86222018-03-28 18:01:20 -06002491 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false);
John Kessenich31ed4832015-09-09 17:51:38 -06002492}
2493
2494// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002495// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002496// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06002497spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
2498 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier, bool lastBufferBlockMember)
John Kessenich31ed4832015-09-09 17:51:38 -06002499{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002500 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002501
2502 switch (type.getBasicType()) {
2503 case glslang::EbtVoid:
2504 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002505 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002506 break;
2507 case glslang::EbtFloat:
2508 spvType = builder.makeFloatType(32);
2509 break;
2510 case glslang::EbtDouble:
2511 spvType = builder.makeFloatType(64);
2512 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002513 case glslang::EbtFloat16:
John Kessenich66011cb2018-03-06 16:12:04 -07002514 builder.addCapability(spv::CapabilityFloat16);
2515#if AMD_EXTENSIONS
2516 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2517 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
2518#endif
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002519 spvType = builder.makeFloatType(16);
2520 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002521 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002522 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2523 // a 32-bit int where non-0 means true.
2524 if (explicitLayout != glslang::ElpNone)
2525 spvType = builder.makeUintType(32);
2526 else
2527 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002528 break;
John Kessenich66011cb2018-03-06 16:12:04 -07002529 case glslang::EbtInt8:
2530 builder.addCapability(spv::CapabilityInt8);
2531 spvType = builder.makeIntType(8);
2532 break;
2533 case glslang::EbtUint8:
2534 builder.addCapability(spv::CapabilityInt8);
2535 spvType = builder.makeUintType(8);
2536 break;
2537 case glslang::EbtInt16:
2538 builder.addCapability(spv::CapabilityInt16);
2539#ifdef AMD_EXTENSIONS
2540 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2541 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2542#endif
2543 spvType = builder.makeIntType(16);
2544 break;
2545 case glslang::EbtUint16:
2546 builder.addCapability(spv::CapabilityInt16);
2547#ifdef AMD_EXTENSIONS
2548 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2549 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2550#endif
2551 spvType = builder.makeUintType(16);
2552 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002553 case glslang::EbtInt:
2554 spvType = builder.makeIntType(32);
2555 break;
2556 case glslang::EbtUint:
2557 spvType = builder.makeUintType(32);
2558 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002559 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002560 spvType = builder.makeIntType(64);
2561 break;
2562 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002563 spvType = builder.makeUintType(64);
2564 break;
John Kessenich426394d2015-07-23 10:22:48 -06002565 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002566 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002567 spvType = builder.makeUintType(32);
2568 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002569 case glslang::EbtSampler:
2570 {
2571 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002572 if (sampler.sampler) {
2573 // pure sampler
2574 spvType = builder.makeSamplerType();
2575 } else {
2576 // an image is present, make its type
2577 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2578 sampler.image ? 2 : 1, TranslateImageFormat(type));
2579 if (sampler.combined) {
2580 // already has both image and sampler, make the combined type
2581 spvType = builder.makeSampledImageType(spvType);
2582 }
John Kessenich55e7d112015-11-15 21:33:39 -07002583 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002584 }
John Kessenich140f3df2015-06-26 16:58:36 -06002585 break;
2586 case glslang::EbtStruct:
2587 case glslang::EbtBlock:
2588 {
2589 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002590 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002591
2592 // Try to share structs for different layouts, but not yet for other
2593 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002594 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002595 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002596 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002597 break;
2598
2599 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002600 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002601 memberRemapper[glslangMembers].resize(glslangMembers->size());
2602 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002603 }
2604 break;
2605 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002606 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002607 break;
2608 }
2609
2610 if (type.isMatrix())
2611 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2612 else {
2613 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2614 if (type.getVectorSize() > 1)
2615 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2616 }
2617
2618 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002619 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2620
John Kessenichc9a80832015-09-12 12:17:44 -06002621 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002622 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002623 // We need to decorate array strides for types needing explicit layout, except blocks.
2624 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002625 // Use a dummy glslang type for querying internal strides of
2626 // arrays of arrays, but using just a one-dimensional array.
2627 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06002628 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
2629 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07002630
2631 // Will compute the higher-order strides here, rather than making a whole
2632 // pile of types and doing repetitive recursion on their contents.
2633 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2634 }
John Kessenichf8842e52016-01-04 19:22:56 -07002635
2636 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002637 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002638 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002639 if (stride > 0)
2640 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002641 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002642 }
2643 } else {
2644 // single-dimensional array, and don't yet have stride
2645
John Kessenichf8842e52016-01-04 19:22:56 -07002646 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002647 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2648 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002649 }
John Kessenich31ed4832015-09-09 17:51:38 -06002650
John Kessenichead86222018-03-28 18:01:20 -06002651 // Do the outer dimension, which might not be known for a runtime-sized array.
2652 // (Unsized arrays that survive through linking will be runtime-sized arrays)
2653 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07002654 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichead86222018-03-28 18:01:20 -06002655 else
2656 spvType = builder.makeRuntimeArray(spvType);
John Kessenichc9e0a422015-12-29 21:27:24 -07002657 if (stride > 0)
2658 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002659 }
2660
2661 return spvType;
2662}
2663
John Kessenich0e737842017-03-24 18:38:16 -06002664// TODO: this functionality should exist at a higher level, in creating the AST
2665//
2666// Identify interface members that don't have their required extension turned on.
2667//
2668bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2669{
2670 auto& extensions = glslangIntermediate->getRequestedExtensions();
2671
Rex Xubcf291a2017-03-29 23:01:36 +08002672 if (member.getFieldName() == "gl_ViewportMask" &&
2673 extensions.find("GL_NV_viewport_array2") == extensions.end())
2674 return true;
2675 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2676 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2677 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002678 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2679 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2680 return true;
2681 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2682 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2683 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002684 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2685 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2686 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002687
2688 return false;
2689};
2690
John Kessenich6090df02016-06-30 21:18:02 -06002691// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2692// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2693// Mutually recursive with convertGlslangToSpvType().
2694spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2695 const glslang::TTypeList* glslangMembers,
2696 glslang::TLayoutPacking explicitLayout,
2697 const glslang::TQualifier& qualifier)
2698{
2699 // Create a vector of struct types for SPIR-V to consume
2700 std::vector<spv::Id> spvMembers;
2701 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 -06002702 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2703 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2704 if (glslangMember.hiddenMember()) {
2705 ++memberDelta;
2706 if (type.getBasicType() == glslang::EbtBlock)
2707 memberRemapper[glslangMembers][i] = -1;
2708 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002709 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002710 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002711 if (filterMember(glslangMember))
2712 continue;
2713 }
John Kessenich6090df02016-06-30 21:18:02 -06002714 // modify just this child's view of the qualifier
2715 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2716 InheritQualifiers(memberQualifier, qualifier);
2717
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002718 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002719 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002720 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002721
2722 // recurse
John Kessenichead86222018-03-28 18:01:20 -06002723 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
2724 i == (int)glslangMembers->size() - 1;
2725 spvMembers.push_back(
2726 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember));
John Kessenich6090df02016-06-30 21:18:02 -06002727 }
2728 }
2729
2730 // Make the SPIR-V type
2731 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002732 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002733 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2734
2735 // Decorate it
2736 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2737
2738 return spvType;
2739}
2740
2741void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2742 const glslang::TTypeList* glslangMembers,
2743 glslang::TLayoutPacking explicitLayout,
2744 const glslang::TQualifier& qualifier,
2745 spv::Id spvType)
2746{
2747 // Name and decorate the non-hidden members
2748 int offset = -1;
2749 int locationOffset = 0; // for use within the members of this struct
2750 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2751 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2752 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002753 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002754 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002755 if (filterMember(glslangMember))
2756 continue;
2757 }
John Kessenich6090df02016-06-30 21:18:02 -06002758
2759 // modify just this child's view of the qualifier
2760 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2761 InheritQualifiers(memberQualifier, qualifier);
2762
2763 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07002764 if (member < 0)
2765 continue;
2766
2767 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2768 builder.addMemberDecoration(spvType, member,
2769 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2770 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2771 // Add interpolation and auxiliary storage decorations only to
2772 // top-level members of Input and Output storage classes
2773 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2774 type.getQualifier().storage == glslang::EvqVaryingOut) {
2775 if (type.getBasicType() == glslang::EbtBlock ||
2776 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
2777 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2778 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002779 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002780 }
2781 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002782
John Kessenich5d610ee2018-03-07 18:05:55 -07002783 if (type.getBasicType() == glslang::EbtBlock &&
2784 qualifier.storage == glslang::EvqBuffer) {
2785 // Add memory decorations only to top-level members of shader storage block
2786 std::vector<spv::Decoration> memory;
2787 TranslateMemoryDecoration(memberQualifier, memory);
2788 for (unsigned int i = 0; i < memory.size(); ++i)
2789 builder.addMemberDecoration(spvType, member, memory[i]);
2790 }
John Kessenich6090df02016-06-30 21:18:02 -06002791
John Kessenich5d610ee2018-03-07 18:05:55 -07002792 // Location assignment was already completed correctly by the front end,
2793 // just track whether a member needs to be decorated.
2794 // Ignore member locations if the container is an array, as that's
2795 // ill-specified and decisions have been made to not allow this.
2796 if (! type.isArray() && memberQualifier.hasLocation())
2797 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002798
John Kessenich5d610ee2018-03-07 18:05:55 -07002799 if (qualifier.hasLocation()) // track for upcoming inheritance
2800 locationOffset += glslangIntermediate->computeTypeLocationSize(
2801 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06002802
John Kessenich5d610ee2018-03-07 18:05:55 -07002803 // component, XFB, others
2804 if (glslangMember.getQualifier().hasComponent())
2805 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
2806 glslangMember.getQualifier().layoutComponent);
2807 if (glslangMember.getQualifier().hasXfbOffset())
2808 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
2809 glslangMember.getQualifier().layoutXfbOffset);
2810 else if (explicitLayout != glslang::ElpNone) {
2811 // figure out what to do with offset, which is accumulating
2812 int nextOffset;
2813 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2814 if (offset >= 0)
2815 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2816 offset = nextOffset;
2817 }
John Kessenich6090df02016-06-30 21:18:02 -06002818
John Kessenich5d610ee2018-03-07 18:05:55 -07002819 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2820 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
2821 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06002822
John Kessenich5d610ee2018-03-07 18:05:55 -07002823 // built-in variable decorations
2824 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
2825 if (builtIn != spv::BuiltInMax)
2826 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002827
John Kessenichead86222018-03-28 18:01:20 -06002828 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
2829 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
2830 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
2831 memberQualifier.semanticName);
2832 }
2833
chaoc771d89f2017-01-13 01:10:53 -08002834#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07002835 if (builtIn == spv::BuiltInLayer) {
2836 // SPV_NV_viewport_array2 extension
2837 if (glslangMember.getQualifier().layoutViewportRelative){
2838 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2839 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2840 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08002841 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002842 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2843 builder.addMemberDecoration(spvType, member,
2844 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
2845 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2846 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2847 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08002848 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002849 }
2850 if (glslangMember.getQualifier().layoutPassthrough) {
2851 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2852 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2853 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2854 }
chaoc771d89f2017-01-13 01:10:53 -08002855#endif
John Kessenich6090df02016-06-30 21:18:02 -06002856 }
2857
2858 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07002859 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2860 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002861 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2862 builder.addCapability(spv::CapabilityGeometryStreams);
2863 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2864 }
John Kessenich6090df02016-06-30 21:18:02 -06002865}
2866
John Kessenich6c292d32016-02-15 20:58:50 -07002867// Turn the expression forming the array size into an id.
2868// This is not quite trivial, because of specialization constants.
2869// Sometimes, a raw constant is turned into an Id, and sometimes
2870// a specialization constant expression is.
2871spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2872{
2873 // First, see if this is sized with a node, meaning a specialization constant:
2874 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2875 if (specNode != nullptr) {
2876 builder.clearAccessChain();
2877 specNode->traverse(this);
2878 return accessChainLoad(specNode->getAsTyped()->getType());
2879 }
qining25262b32016-05-06 17:25:16 -04002880
John Kessenich6c292d32016-02-15 20:58:50 -07002881 // Otherwise, need a compile-time (front end) size, get it:
2882 int size = arraySizes.getDimSize(dim);
2883 assert(size > 0);
2884 return builder.makeUintConstant(size);
2885}
2886
John Kessenich103bef92016-02-08 21:38:15 -07002887// Wrap the builder's accessChainLoad to:
2888// - localize handling of RelaxedPrecision
2889// - use the SPIR-V inferred type instead of another conversion of the glslang type
2890// (avoids unnecessary work and possible type punning for structures)
2891// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002892spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2893{
John Kessenich103bef92016-02-08 21:38:15 -07002894 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2895 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2896
2897 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002898 if (type.getBasicType() == glslang::EbtBool) {
2899 if (builder.isScalarType(nominalTypeId)) {
2900 // Conversion for bool
2901 spv::Id boolType = builder.makeBoolType();
2902 if (nominalTypeId != boolType)
2903 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2904 } else if (builder.isVectorType(nominalTypeId)) {
2905 // Conversion for bvec
2906 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2907 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2908 if (nominalTypeId != bvecType)
2909 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2910 }
2911 }
John Kessenich103bef92016-02-08 21:38:15 -07002912
2913 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002914}
2915
Rex Xu27253232016-02-23 17:51:09 +08002916// Wrap the builder's accessChainStore to:
2917// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002918//
2919// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002920void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2921{
2922 // Need to convert to abstract types when necessary
2923 if (type.getBasicType() == glslang::EbtBool) {
2924 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2925
2926 if (builder.isScalarType(nominalTypeId)) {
2927 // Conversion for bool
2928 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002929 if (nominalTypeId != boolType) {
2930 // keep these outside arguments, for determinant order-of-evaluation
2931 spv::Id one = builder.makeUintConstant(1);
2932 spv::Id zero = builder.makeUintConstant(0);
2933 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2934 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002935 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002936 } else if (builder.isVectorType(nominalTypeId)) {
2937 // Conversion for bvec
2938 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2939 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002940 if (nominalTypeId != bvecType) {
2941 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002942 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2943 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2944 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002945 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002946 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2947 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002948 }
2949 }
2950
2951 builder.accessChainStore(rvalue);
2952}
2953
John Kessenich4bf71552016-09-02 11:20:21 -06002954// For storing when types match at the glslang level, but not might match at the
2955// SPIR-V level.
2956//
2957// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002958// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002959// as in a member-decorated way.
2960//
2961// NOTE: This function can handle any store request; if it's not special it
2962// simplifies to a simple OpStore.
2963//
2964// Implicitly uses the existing builder.accessChain as the storage target.
2965void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2966{
John Kessenichb3e24e42016-09-11 12:33:43 -06002967 // we only do the complex path here if it's an aggregate
2968 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002969 accessChainStore(type, rValue);
2970 return;
2971 }
2972
John Kessenichb3e24e42016-09-11 12:33:43 -06002973 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002974 spv::Id rType = builder.getTypeId(rValue);
2975 spv::Id lValue = builder.accessChainGetLValue();
2976 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2977 if (lType == rType) {
2978 accessChainStore(type, rValue);
2979 return;
2980 }
2981
John Kessenichb3e24e42016-09-11 12:33:43 -06002982 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002983 // where the two types were the same type in GLSL. This requires member
2984 // by member copy, recursively.
2985
John Kessenichb3e24e42016-09-11 12:33:43 -06002986 // If an array, copy element by element.
2987 if (type.isArray()) {
2988 glslang::TType glslangElementType(type, 0);
2989 spv::Id elementRType = builder.getContainedTypeId(rType);
2990 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2991 // get the source member
2992 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002993
John Kessenichb3e24e42016-09-11 12:33:43 -06002994 // set up the target storage
2995 builder.clearAccessChain();
2996 builder.setAccessChainLValue(lValue);
2997 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002998
John Kessenichb3e24e42016-09-11 12:33:43 -06002999 // store the member
3000 multiTypeStore(glslangElementType, elementRValue);
3001 }
3002 } else {
3003 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003004
John Kessenichb3e24e42016-09-11 12:33:43 -06003005 // loop over structure members
3006 const glslang::TTypeList& members = *type.getStruct();
3007 for (int m = 0; m < (int)members.size(); ++m) {
3008 const glslang::TType& glslangMemberType = *members[m].type;
3009
3010 // get the source member
3011 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3012 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3013
3014 // set up the target storage
3015 builder.clearAccessChain();
3016 builder.setAccessChainLValue(lValue);
3017 builder.accessChainPush(builder.makeIntConstant(m));
3018
3019 // store the member
3020 multiTypeStore(glslangMemberType, memberRValue);
3021 }
John Kessenich4bf71552016-09-02 11:20:21 -06003022 }
3023}
3024
John Kessenichf85e8062015-12-19 13:57:10 -07003025// Decide whether or not this type should be
3026// decorated with offsets and strides, and if so
3027// whether std140 or std430 rules should be applied.
3028glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003029{
John Kessenichf85e8062015-12-19 13:57:10 -07003030 // has to be a block
3031 if (type.getBasicType() != glslang::EbtBlock)
3032 return glslang::ElpNone;
3033
3034 // has to be a uniform or buffer block
3035 if (type.getQualifier().storage != glslang::EvqUniform &&
3036 type.getQualifier().storage != glslang::EvqBuffer)
3037 return glslang::ElpNone;
3038
3039 // return the layout to use
3040 switch (type.getQualifier().layoutPacking) {
3041 case glslang::ElpStd140:
3042 case glslang::ElpStd430:
3043 return type.getQualifier().layoutPacking;
3044 default:
3045 return glslang::ElpNone;
3046 }
John Kessenich31ed4832015-09-09 17:51:38 -06003047}
3048
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003049// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003050int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003051{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003052 int size;
John Kessenich49987892015-12-29 17:11:44 -07003053 int stride;
3054 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003055
3056 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003057}
3058
John Kessenich49987892015-12-29 17:11:44 -07003059// 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 -07003060// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003061int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003062{
John Kessenich49987892015-12-29 17:11:44 -07003063 glslang::TType elementType;
3064 elementType.shallowCopy(matrixType);
3065 elementType.clearArraySizes();
3066
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003067 int size;
John Kessenich49987892015-12-29 17:11:44 -07003068 int stride;
3069 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
3070
3071 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003072}
3073
John Kessenich5e4b1242015-08-06 22:53:06 -06003074// Given a member type of a struct, realign the current offset for it, and compute
3075// the next (not yet aligned) offset for the next member, which will get aligned
3076// on the next call.
3077// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3078// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3079// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003080void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003081 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003082{
3083 // this will get a positive value when deemed necessary
3084 nextOffset = -1;
3085
John Kessenich5e4b1242015-08-06 22:53:06 -06003086 // override anything in currentOffset with user-set offset
3087 if (memberType.getQualifier().hasOffset())
3088 currentOffset = memberType.getQualifier().layoutOffset;
3089
3090 // It could be that current linker usage in glslang updated all the layoutOffset,
3091 // in which case the following code does not matter. But, that's not quite right
3092 // once cross-compilation unit GLSL validation is done, as the original user
3093 // settings are needed in layoutOffset, and then the following will come into play.
3094
John Kessenichf85e8062015-12-19 13:57:10 -07003095 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003096 if (! memberType.getQualifier().hasOffset())
3097 currentOffset = -1;
3098
3099 return;
3100 }
3101
John Kessenichf85e8062015-12-19 13:57:10 -07003102 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003103 if (currentOffset < 0)
3104 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003105
John Kessenich5e4b1242015-08-06 22:53:06 -06003106 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3107 // but possibly not yet correctly aligned.
3108
3109 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003110 int dummyStride;
3111 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003112
3113 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003114 // TODO: make this consistent in early phases of code:
3115 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3116 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3117 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06003118 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003119 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003120 int dummySize;
3121 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3122 if (componentAlignment <= 4)
3123 memberAlignment = componentAlignment;
3124 }
3125
3126 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003127 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003128
3129 // Bump up to vec4 if there is a bad straddle
3130 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
3131 glslang::RoundToPow2(currentOffset, 16);
3132
John Kessenich5e4b1242015-08-06 22:53:06 -06003133 nextOffset = currentOffset + memberSize;
3134}
3135
David Netoa901ffe2016-06-08 14:11:40 +01003136void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003137{
David Netoa901ffe2016-06-08 14:11:40 +01003138 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3139 switch (glslangBuiltIn)
3140 {
3141 case glslang::EbvClipDistance:
3142 case glslang::EbvCullDistance:
3143 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003144#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003145 case glslang::EbvViewportMaskNV:
3146 case glslang::EbvSecondaryPositionNV:
3147 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003148 case glslang::EbvPositionPerViewNV:
3149 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08003150#endif
David Netoa901ffe2016-06-08 14:11:40 +01003151 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3152 // Alternately, we could just call this for any glslang built-in, since the
3153 // capability already guards against duplicates.
3154 TranslateBuiltInDecoration(glslangBuiltIn, false);
3155 break;
3156 default:
3157 // Capabilities were already generated when the struct was declared.
3158 break;
3159 }
John Kessenichebb50532016-05-16 19:22:05 -06003160}
3161
John Kessenich6fccb3c2016-09-19 16:01:41 -06003162bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003163{
John Kessenicheee9d532016-09-19 18:09:30 -06003164 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003165}
3166
John Kessenichd41993d2017-09-10 15:21:05 -06003167// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003168// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3169// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd41993d2017-09-10 15:21:05 -06003170bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier)
3171{
John Kessenich6a14f782017-12-04 02:48:10 -07003172 assert(qualifier == glslang::EvqIn ||
3173 qualifier == glslang::EvqOut ||
3174 qualifier == glslang::EvqInOut ||
3175 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003176 return qualifier != glslang::EvqConstReadOnly;
3177}
3178
3179// Is parameter pass-by-original?
3180bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3181 bool implicitThisParam)
3182{
3183 if (implicitThisParam) // implicit this
3184 return true;
3185 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003186 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003187 return paramType.containsOpaque() || // sampler, etc.
3188 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3189}
3190
John Kessenich140f3df2015-06-26 16:58:36 -06003191// Make all the functions, skeletally, without actually visiting their bodies.
3192void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3193{
John Kessenichfad62972017-07-18 02:35:46 -06003194 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
3195 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3196 if (paramPrecision != spv::NoPrecision)
3197 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06003198 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06003199 };
3200
John Kessenich140f3df2015-06-26 16:58:36 -06003201 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3202 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003203 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003204 continue;
3205
3206 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003207 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003208 //
qining25262b32016-05-06 17:25:16 -04003209 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003210 // function. What it is an address of varies:
3211 //
John Kessenich4bf71552016-09-02 11:20:21 -06003212 // - "in" parameters not marked as "const" can be written to without modifying the calling
3213 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003214 //
3215 // - "const in" parameters can just be the r-value, as no writes need occur.
3216 //
John Kessenich4bf71552016-09-02 11:20:21 -06003217 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3218 // 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 -06003219
3220 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003221 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003222 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3223
John Kessenichfad62972017-07-18 02:35:46 -06003224 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3225 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003226
John Kessenichfad62972017-07-18 02:35:46 -06003227 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003228 for (int p = 0; p < (int)parameters.size(); ++p) {
3229 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3230 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003231 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003232 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003233 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003234 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3235 else
John Kessenich4bf71552016-09-02 11:20:21 -06003236 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003237 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003238 paramTypes.push_back(typeId);
3239 }
3240
3241 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003242 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3243 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003244 glslFunction->getName().c_str(), paramTypes,
3245 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003246 if (implicitThis)
3247 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003248
3249 // Track function to emit/call later
3250 functionMap[glslFunction->getName().c_str()] = function;
3251
3252 // Set the parameter id's
3253 for (int p = 0; p < (int)parameters.size(); ++p) {
3254 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3255 // give a name too
3256 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3257 }
3258 }
3259}
3260
3261// Process all the initializers, while skipping the functions and link objects
3262void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3263{
3264 builder.setBuildPoint(shaderEntry->getLastBlock());
3265 for (int i = 0; i < (int)initializers.size(); ++i) {
3266 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3267 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3268
3269 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003270 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003271 initializer->traverse(this);
3272 }
3273 }
3274}
3275
3276// Process all the functions, while skipping initializers.
3277void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3278{
3279 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3280 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003281 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003282 node->traverse(this);
3283 }
3284}
3285
3286void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3287{
qining25262b32016-05-06 17:25:16 -04003288 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003289 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003290 currentFunction = functionMap[node->getName().c_str()];
3291 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003292 builder.setBuildPoint(functionBlock);
3293}
3294
Rex Xu04db3f52015-09-16 11:44:02 +08003295void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003296{
Rex Xufc618912015-09-09 16:42:49 +08003297 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003298
3299 glslang::TSampler sampler = {};
3300 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003301#ifdef AMD_EXTENSIONS
3302 bool f16ShadowCompare = false;
3303#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003304 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003305 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3306 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003307#ifdef AMD_EXTENSIONS
3308 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3309#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003310 }
3311
John Kessenich140f3df2015-06-26 16:58:36 -06003312 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3313 builder.clearAccessChain();
3314 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003315
3316 // Special case l-value operands
3317 bool lvalue = false;
3318 switch (node.getOp()) {
3319 case glslang::EOpImageAtomicAdd:
3320 case glslang::EOpImageAtomicMin:
3321 case glslang::EOpImageAtomicMax:
3322 case glslang::EOpImageAtomicAnd:
3323 case glslang::EOpImageAtomicOr:
3324 case glslang::EOpImageAtomicXor:
3325 case glslang::EOpImageAtomicExchange:
3326 case glslang::EOpImageAtomicCompSwap:
3327 if (i == 0)
3328 lvalue = true;
3329 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003330 case glslang::EOpSparseImageLoad:
3331 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3332 lvalue = true;
3333 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003334#ifdef AMD_EXTENSIONS
3335 case glslang::EOpSparseTexture:
3336 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3337 lvalue = true;
3338 break;
3339 case glslang::EOpSparseTextureClamp:
3340 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3341 lvalue = true;
3342 break;
3343 case glslang::EOpSparseTextureLod:
3344 case glslang::EOpSparseTextureOffset:
3345 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
3346 lvalue = true;
3347 break;
3348#else
Rex Xu48edadf2015-12-31 16:11:41 +08003349 case glslang::EOpSparseTexture:
3350 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3351 lvalue = true;
3352 break;
3353 case glslang::EOpSparseTextureClamp:
3354 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3355 lvalue = true;
3356 break;
3357 case glslang::EOpSparseTextureLod:
3358 case glslang::EOpSparseTextureOffset:
3359 if (i == 3)
3360 lvalue = true;
3361 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003362#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003363 case glslang::EOpSparseTextureFetch:
3364 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3365 lvalue = true;
3366 break;
3367 case glslang::EOpSparseTextureFetchOffset:
3368 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3369 lvalue = true;
3370 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003371#ifdef AMD_EXTENSIONS
3372 case glslang::EOpSparseTextureLodOffset:
3373 case glslang::EOpSparseTextureGrad:
3374 case glslang::EOpSparseTextureOffsetClamp:
3375 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
3376 lvalue = true;
3377 break;
3378 case glslang::EOpSparseTextureGradOffset:
3379 case glslang::EOpSparseTextureGradClamp:
3380 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
3381 lvalue = true;
3382 break;
3383 case glslang::EOpSparseTextureGradOffsetClamp:
3384 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
3385 lvalue = true;
3386 break;
3387#else
Rex Xu48edadf2015-12-31 16:11:41 +08003388 case glslang::EOpSparseTextureLodOffset:
3389 case glslang::EOpSparseTextureGrad:
3390 case glslang::EOpSparseTextureOffsetClamp:
3391 if (i == 4)
3392 lvalue = true;
3393 break;
3394 case glslang::EOpSparseTextureGradOffset:
3395 case glslang::EOpSparseTextureGradClamp:
3396 if (i == 5)
3397 lvalue = true;
3398 break;
3399 case glslang::EOpSparseTextureGradOffsetClamp:
3400 if (i == 6)
3401 lvalue = true;
3402 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003403#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08003404 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003405 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3406 lvalue = true;
3407 break;
3408 case glslang::EOpSparseTextureGatherOffset:
3409 case glslang::EOpSparseTextureGatherOffsets:
3410 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3411 lvalue = true;
3412 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003413#ifdef AMD_EXTENSIONS
3414 case glslang::EOpSparseTextureGatherLod:
3415 if (i == 3)
3416 lvalue = true;
3417 break;
3418 case glslang::EOpSparseTextureGatherLodOffset:
3419 case glslang::EOpSparseTextureGatherLodOffsets:
3420 if (i == 4)
3421 lvalue = true;
3422 break;
Rex Xu129799a2017-07-05 17:23:28 +08003423 case glslang::EOpSparseImageLoadLod:
3424 if (i == 3)
3425 lvalue = true;
3426 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003427#endif
Rex Xufc618912015-09-09 16:42:49 +08003428 default:
3429 break;
3430 }
3431
Rex Xu6b86d492015-09-16 17:48:22 +08003432 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003433 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003434 else
John Kessenich32cfd492016-02-02 12:37:46 -07003435 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003436 }
3437}
3438
John Kessenichfc51d282015-08-19 13:34:18 -06003439void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003440{
John Kessenichfc51d282015-08-19 13:34:18 -06003441 builder.clearAccessChain();
3442 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003443 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003444}
John Kessenich140f3df2015-06-26 16:58:36 -06003445
John Kessenichfc51d282015-08-19 13:34:18 -06003446spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3447{
John Kesseniche485c7a2017-05-31 18:50:53 -06003448 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003449 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003450
3451 builder.setLine(node->getLoc().line);
3452
John Kessenichfc51d282015-08-19 13:34:18 -06003453 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003454 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3455 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08003456#ifdef AMD_EXTENSIONS
3457 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
3458 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
3459 : false;
3460#endif
3461
John Kessenichfc51d282015-08-19 13:34:18 -06003462 std::vector<spv::Id> arguments;
3463 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003464 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003465 else
3466 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003467 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003468
3469 spv::Builder::TextureParameters params = { };
3470 params.sampler = arguments[0];
3471
Rex Xu04db3f52015-09-16 11:44:02 +08003472 glslang::TCrackedTextureOp cracked;
3473 node->crackTexture(sampler, cracked);
3474
amhagan05506bb2017-06-13 16:53:02 -04003475 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003476
John Kessenichfc51d282015-08-19 13:34:18 -06003477 // Check for queries
3478 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003479 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3480 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003481 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003482
John Kessenichfc51d282015-08-19 13:34:18 -06003483 switch (node->getOp()) {
3484 case glslang::EOpImageQuerySize:
3485 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003486 if (arguments.size() > 1) {
3487 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003488 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003489 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003490 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003491 case glslang::EOpImageQuerySamples:
3492 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003493 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003494 case glslang::EOpTextureQueryLod:
3495 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003496 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003497 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003498 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003499 case glslang::EOpSparseTexelsResident:
3500 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003501 default:
3502 assert(0);
3503 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003504 }
John Kessenich140f3df2015-06-26 16:58:36 -06003505 }
3506
LoopDawg4425f242018-02-18 11:40:01 -07003507 int components = node->getType().getVectorSize();
3508
3509 if (node->getOp() == glslang::EOpTextureFetch) {
3510 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3511 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3512 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3513 // here around e.g. which ones return scalars or other types.
3514 components = 4;
3515 }
3516
3517 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3518
3519 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3520
Rex Xufc618912015-09-09 16:42:49 +08003521 // Check for image functions other than queries
3522 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003523 std::vector<spv::Id> operands;
3524 auto opIt = arguments.begin();
3525 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003526
3527 // Handle subpass operations
3528 // TODO: GLSL should change to have the "MS" only on the type rather than the
3529 // built-in function.
3530 if (cracked.subpass) {
3531 // add on the (0,0) coordinate
3532 spv::Id zero = builder.makeIntConstant(0);
3533 std::vector<spv::Id> comps;
3534 comps.push_back(zero);
3535 comps.push_back(zero);
3536 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3537 if (sampler.ms) {
3538 operands.push_back(spv::ImageOperandsSampleMask);
3539 operands.push_back(*(opIt++));
3540 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003541 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3542 builder.setPrecision(result, precision);
3543 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003544 }
3545
John Kessenich56bab042015-09-16 10:54:31 -06003546 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003547#ifdef AMD_EXTENSIONS
3548 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3549#else
John Kessenich56bab042015-09-16 10:54:31 -06003550 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003551#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003552 if (sampler.ms) {
3553 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003554 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003555#ifdef AMD_EXTENSIONS
3556 } else if (cracked.lod) {
3557 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3558 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3559
3560 operands.push_back(spv::ImageOperandsLodMask);
3561 operands.push_back(*opIt);
3562#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003563 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003564 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3565 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003566
LoopDawg4425f242018-02-18 11:40:01 -07003567 std::vector<spv::Id> result = { builder.createOp(spv::OpImageRead, resultType(), operands) };
3568 builder.setPrecision(result[0], precision);
3569
3570 // If needed, add a conversion constructor to the proper size.
3571 if (components != node->getType().getVectorSize())
3572 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3573
3574 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08003575#ifdef AMD_EXTENSIONS
3576 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3577#else
John Kessenich56bab042015-09-16 10:54:31 -06003578 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003579#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003580 if (sampler.ms) {
3581 operands.push_back(*(opIt + 1));
3582 operands.push_back(spv::ImageOperandsSampleMask);
3583 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003584#ifdef AMD_EXTENSIONS
3585 } else if (cracked.lod) {
3586 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3587 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3588
3589 operands.push_back(*(opIt + 1));
3590 operands.push_back(spv::ImageOperandsLodMask);
3591 operands.push_back(*opIt);
3592#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003593 } else
3594 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003595 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003596 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3597 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003598 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003599#ifdef AMD_EXTENSIONS
3600 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3601#else
Rex Xu5eafa472016-02-19 22:24:03 +08003602 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003603#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003604 builder.addCapability(spv::CapabilitySparseResidency);
3605 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3606 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3607
3608 if (sampler.ms) {
3609 operands.push_back(spv::ImageOperandsSampleMask);
3610 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003611#ifdef AMD_EXTENSIONS
3612 } else if (cracked.lod) {
3613 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3614 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3615
3616 operands.push_back(spv::ImageOperandsLodMask);
3617 operands.push_back(*opIt++);
3618#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003619 }
3620
3621 // Create the return type that was a special structure
3622 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003623 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003624 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3625 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3626
3627 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3628
3629 // Decode the return type
3630 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3631 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003632 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003633 // Process image atomic operations
3634
3635 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3636 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003637 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003638
John Kessenich8c8505c2016-07-26 12:50:38 -06003639 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003640 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003641
3642 std::vector<spv::Id> operands;
3643 operands.push_back(pointer);
3644 for (; opIt != arguments.end(); ++opIt)
3645 operands.push_back(*opIt);
3646
John Kessenich8c8505c2016-07-26 12:50:38 -06003647 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003648 }
3649 }
3650
amhagan05506bb2017-06-13 16:53:02 -04003651#ifdef AMD_EXTENSIONS
3652 // Check for fragment mask functions other than queries
3653 if (cracked.fragMask) {
3654 assert(sampler.ms);
3655
3656 auto opIt = arguments.begin();
3657 std::vector<spv::Id> operands;
3658
3659 // Extract the image if necessary
3660 if (builder.isSampledImage(params.sampler))
3661 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3662
3663 operands.push_back(params.sampler);
3664 ++opIt;
3665
3666 if (sampler.isSubpass()) {
3667 // add on the (0,0) coordinate
3668 spv::Id zero = builder.makeIntConstant(0);
3669 std::vector<spv::Id> comps;
3670 comps.push_back(zero);
3671 comps.push_back(zero);
3672 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3673 }
3674
3675 for (; opIt != arguments.end(); ++opIt)
3676 operands.push_back(*opIt);
3677
3678 spv::Op fragMaskOp = spv::OpNop;
3679 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3680 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3681 else if (node->getOp() == glslang::EOpFragmentFetch)
3682 fragMaskOp = spv::OpFragmentFetchAMD;
3683
3684 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3685 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3686 return builder.createOp(fragMaskOp, resultType(), operands);
3687 }
3688#endif
3689
Rex Xufc618912015-09-09 16:42:49 +08003690 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003691 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003692 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3693
John Kessenichfc51d282015-08-19 13:34:18 -06003694 // check for bias argument
3695 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003696#ifdef AMD_EXTENSIONS
3697 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3698#else
Rex Xu71519fe2015-11-11 15:35:47 +08003699 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003700#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003701 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003702#ifdef AMD_EXTENSIONS
3703 if (cracked.gather)
3704 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08003705
3706 if (f16ShadowCompare)
3707 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003708#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003709 if (cracked.offset)
3710 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003711#ifdef AMD_EXTENSIONS
3712 else if (cracked.offsets)
3713 ++nonBiasArgCount;
3714#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003715 if (cracked.grad)
3716 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003717 if (cracked.lodClamp)
3718 ++nonBiasArgCount;
3719 if (sparse)
3720 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003721
3722 if ((int)arguments.size() > nonBiasArgCount)
3723 bias = true;
3724 }
3725
John Kessenicha5c33d62016-06-02 23:45:21 -06003726 // See if the sampler param should really be just the SPV image part
3727 if (cracked.fetch) {
3728 // a fetch needs to have the image extracted first
3729 if (builder.isSampledImage(params.sampler))
3730 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3731 }
3732
Rex Xu225e0fc2016-11-17 17:47:59 +08003733#ifdef AMD_EXTENSIONS
3734 if (cracked.gather) {
3735 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3736 if (bias || cracked.lod ||
3737 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3738 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003739 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003740 }
3741 }
3742#endif
3743
John Kessenichfc51d282015-08-19 13:34:18 -06003744 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003745
John Kessenichfc51d282015-08-19 13:34:18 -06003746 params.coords = arguments[1];
3747 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003748 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003749
3750 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08003751#ifdef AMD_EXTENSIONS
3752 if (cubeCompare || f16ShadowCompare) {
3753#else
Rex Xu48edadf2015-12-31 16:11:41 +08003754 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08003755#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003756 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003757 ++extraArgs;
3758 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003759 params.Dref = arguments[2];
3760 ++extraArgs;
3761 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003762 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003763 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003764 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003765 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003766 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003767 dRefComp = builder.getNumComponents(params.coords) - 1;
3768 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003769 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3770 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003771
3772 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003773 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003774 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003775 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003776 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3777 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3778 noImplicitLod = true;
3779 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003780
3781 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003782 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003783 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003784 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003785 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003786
3787 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003788 if (cracked.grad) {
3789 params.gradX = arguments[2 + extraArgs];
3790 params.gradY = arguments[3 + extraArgs];
3791 extraArgs += 2;
3792 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003793
3794 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003795 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003796 params.offset = arguments[2 + extraArgs];
3797 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003798 } else if (cracked.offsets) {
3799 params.offsets = arguments[2 + extraArgs];
3800 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003801 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003802
3803 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003804 if (cracked.lodClamp) {
3805 params.lodClamp = arguments[2 + extraArgs];
3806 ++extraArgs;
3807 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003808
3809 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003810 if (sparse) {
3811 params.texelOut = arguments[2 + extraArgs];
3812 ++extraArgs;
3813 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003814
John Kessenich76d4dfc2016-06-16 12:43:23 -06003815 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003816 if (cracked.gather && ! sampler.shadow) {
3817 // default component is 0, if missing, otherwise an argument
3818 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003819 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003820 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003821 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003822 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003823 }
3824
3825 // bias
3826 if (bias) {
3827 params.bias = arguments[2 + extraArgs];
3828 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003829 }
John Kessenichfc51d282015-08-19 13:34:18 -06003830
John Kessenich65336482016-06-16 14:06:26 -06003831 // projective component (might not to move)
3832 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3833 // are divided by the last component of P."
3834 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3835 // unused components will appear after all used components."
3836 if (cracked.proj) {
3837 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3838 int projTargetComp;
3839 switch (sampler.dim) {
3840 case glslang::Esd1D: projTargetComp = 1; break;
3841 case glslang::Esd2D: projTargetComp = 2; break;
3842 case glslang::EsdRect: projTargetComp = 2; break;
3843 default: projTargetComp = projSourceComp; break;
3844 }
3845 // copy the projective coordinate if we have to
3846 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003847 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003848 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3849 projSourceComp);
3850 params.coords = builder.createCompositeInsert(projComp, params.coords,
3851 builder.getTypeId(params.coords), projTargetComp);
3852 }
3853 }
3854
LoopDawg4425f242018-02-18 11:40:01 -07003855 std::vector<spv::Id> result = {
3856 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
3857 };
3858
3859 if (components != node->getType().getVectorSize())
3860 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3861
3862 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06003863}
3864
3865spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3866{
3867 // Grab the function's pointer from the previously created function
3868 spv::Function* function = functionMap[node->getName().c_str()];
3869 if (! function)
3870 return 0;
3871
3872 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3873 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3874
3875 // See comments in makeFunctions() for details about the semantics for parameter passing.
3876 //
3877 // These imply we need a four step process:
3878 // 1. Evaluate the arguments
3879 // 2. Allocate and make copies of in, out, and inout arguments
3880 // 3. Make the call
3881 // 4. Copy back the results
3882
3883 // 1. Evaluate the arguments
3884 std::vector<spv::Builder::AccessChain> lValues;
3885 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003886 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003887 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003888 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003889 // build l-value
3890 builder.clearAccessChain();
3891 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003892 argTypes.push_back(&paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003893 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenich6a14f782017-12-04 02:48:10 -07003894 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0) ||
3895 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003896 // save l-value
3897 lValues.push_back(builder.getAccessChain());
3898 } else {
3899 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003900 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003901 }
3902 }
3903
3904 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3905 // copy the original into that space.
3906 //
3907 // Also, build up the list of actual arguments to pass in for the call
3908 int lValueCount = 0;
3909 int rValueCount = 0;
3910 std::vector<spv::Id> spvArgs;
3911 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003912 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003913 spv::Id arg;
John Kessenichd41993d2017-09-10 15:21:05 -06003914 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003915 builder.setAccessChain(lValues[lValueCount]);
3916 arg = builder.accessChainGetLValue();
3917 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06003918 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003919 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003920 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3921 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3922 // need to copy the input into output space
3923 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003924 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003925 builder.clearAccessChain();
3926 builder.setAccessChainLValue(arg);
3927 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003928 }
3929 ++lValueCount;
3930 } else {
3931 arg = rValues[rValueCount];
3932 ++rValueCount;
3933 }
3934 spvArgs.push_back(arg);
3935 }
3936
3937 // 3. Make the call.
3938 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003939 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003940
3941 // 4. Copy back out an "out" arguments.
3942 lValueCount = 0;
3943 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003944 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenichd41993d2017-09-10 15:21:05 -06003945 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0))
3946 ++lValueCount;
3947 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003948 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3949 spv::Id copy = builder.createLoad(spvArgs[a]);
3950 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003951 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003952 }
3953 ++lValueCount;
3954 }
3955 }
3956
3957 return result;
3958}
3959
3960// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06003961spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06003962 spv::Id typeId, spv::Id left, spv::Id right,
3963 glslang::TBasicType typeProxy, bool reduceComparison)
3964{
John Kessenich66011cb2018-03-06 16:12:04 -07003965 bool isUnsigned = isTypeUnsignedInt(typeProxy);
3966 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08003967 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003968
3969 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003970 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003971 bool comparison = false;
3972
3973 switch (op) {
3974 case glslang::EOpAdd:
3975 case glslang::EOpAddAssign:
3976 if (isFloat)
3977 binOp = spv::OpFAdd;
3978 else
3979 binOp = spv::OpIAdd;
3980 break;
3981 case glslang::EOpSub:
3982 case glslang::EOpSubAssign:
3983 if (isFloat)
3984 binOp = spv::OpFSub;
3985 else
3986 binOp = spv::OpISub;
3987 break;
3988 case glslang::EOpMul:
3989 case glslang::EOpMulAssign:
3990 if (isFloat)
3991 binOp = spv::OpFMul;
3992 else
3993 binOp = spv::OpIMul;
3994 break;
3995 case glslang::EOpVectorTimesScalar:
3996 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003997 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003998 if (builder.isVector(right))
3999 std::swap(left, right);
4000 assert(builder.isScalar(right));
4001 needMatchingVectors = false;
4002 binOp = spv::OpVectorTimesScalar;
4003 } else
4004 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004005 break;
4006 case glslang::EOpVectorTimesMatrix:
4007 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004008 binOp = spv::OpVectorTimesMatrix;
4009 break;
4010 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004011 binOp = spv::OpMatrixTimesVector;
4012 break;
4013 case glslang::EOpMatrixTimesScalar:
4014 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004015 binOp = spv::OpMatrixTimesScalar;
4016 break;
4017 case glslang::EOpMatrixTimesMatrix:
4018 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004019 binOp = spv::OpMatrixTimesMatrix;
4020 break;
4021 case glslang::EOpOuterProduct:
4022 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004023 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004024 break;
4025
4026 case glslang::EOpDiv:
4027 case glslang::EOpDivAssign:
4028 if (isFloat)
4029 binOp = spv::OpFDiv;
4030 else if (isUnsigned)
4031 binOp = spv::OpUDiv;
4032 else
4033 binOp = spv::OpSDiv;
4034 break;
4035 case glslang::EOpMod:
4036 case glslang::EOpModAssign:
4037 if (isFloat)
4038 binOp = spv::OpFMod;
4039 else if (isUnsigned)
4040 binOp = spv::OpUMod;
4041 else
4042 binOp = spv::OpSMod;
4043 break;
4044 case glslang::EOpRightShift:
4045 case glslang::EOpRightShiftAssign:
4046 if (isUnsigned)
4047 binOp = spv::OpShiftRightLogical;
4048 else
4049 binOp = spv::OpShiftRightArithmetic;
4050 break;
4051 case glslang::EOpLeftShift:
4052 case glslang::EOpLeftShiftAssign:
4053 binOp = spv::OpShiftLeftLogical;
4054 break;
4055 case glslang::EOpAnd:
4056 case glslang::EOpAndAssign:
4057 binOp = spv::OpBitwiseAnd;
4058 break;
4059 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004060 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004061 binOp = spv::OpLogicalAnd;
4062 break;
4063 case glslang::EOpInclusiveOr:
4064 case glslang::EOpInclusiveOrAssign:
4065 binOp = spv::OpBitwiseOr;
4066 break;
4067 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004068 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004069 binOp = spv::OpLogicalOr;
4070 break;
4071 case glslang::EOpExclusiveOr:
4072 case glslang::EOpExclusiveOrAssign:
4073 binOp = spv::OpBitwiseXor;
4074 break;
4075 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004076 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004077 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004078 break;
4079
4080 case glslang::EOpLessThan:
4081 case glslang::EOpGreaterThan:
4082 case glslang::EOpLessThanEqual:
4083 case glslang::EOpGreaterThanEqual:
4084 case glslang::EOpEqual:
4085 case glslang::EOpNotEqual:
4086 case glslang::EOpVectorEqual:
4087 case glslang::EOpVectorNotEqual:
4088 comparison = true;
4089 break;
4090 default:
4091 break;
4092 }
4093
John Kessenich7c1aa102015-10-15 13:29:11 -06004094 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004095 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004096 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07004097 if (builder.isMatrix(left) || builder.isMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004098 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004099
4100 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004101 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004102 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004103
qining25262b32016-05-06 17:25:16 -04004104 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004105 builder.addDecoration(result, decorations.noContraction);
4106 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004107 }
4108
4109 if (! comparison)
4110 return 0;
4111
John Kessenich7c1aa102015-10-15 13:29:11 -06004112 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004113
John Kessenich4583b612016-08-07 19:14:22 -06004114 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004115 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4116 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
4117 return result;
4118 }
John Kessenich140f3df2015-06-26 16:58:36 -06004119
4120 switch (op) {
4121 case glslang::EOpLessThan:
4122 if (isFloat)
4123 binOp = spv::OpFOrdLessThan;
4124 else if (isUnsigned)
4125 binOp = spv::OpULessThan;
4126 else
4127 binOp = spv::OpSLessThan;
4128 break;
4129 case glslang::EOpGreaterThan:
4130 if (isFloat)
4131 binOp = spv::OpFOrdGreaterThan;
4132 else if (isUnsigned)
4133 binOp = spv::OpUGreaterThan;
4134 else
4135 binOp = spv::OpSGreaterThan;
4136 break;
4137 case glslang::EOpLessThanEqual:
4138 if (isFloat)
4139 binOp = spv::OpFOrdLessThanEqual;
4140 else if (isUnsigned)
4141 binOp = spv::OpULessThanEqual;
4142 else
4143 binOp = spv::OpSLessThanEqual;
4144 break;
4145 case glslang::EOpGreaterThanEqual:
4146 if (isFloat)
4147 binOp = spv::OpFOrdGreaterThanEqual;
4148 else if (isUnsigned)
4149 binOp = spv::OpUGreaterThanEqual;
4150 else
4151 binOp = spv::OpSGreaterThanEqual;
4152 break;
4153 case glslang::EOpEqual:
4154 case glslang::EOpVectorEqual:
4155 if (isFloat)
4156 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004157 else if (isBool)
4158 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004159 else
4160 binOp = spv::OpIEqual;
4161 break;
4162 case glslang::EOpNotEqual:
4163 case glslang::EOpVectorNotEqual:
4164 if (isFloat)
4165 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004166 else if (isBool)
4167 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004168 else
4169 binOp = spv::OpINotEqual;
4170 break;
4171 default:
4172 break;
4173 }
4174
qining25262b32016-05-06 17:25:16 -04004175 if (binOp != spv::OpNop) {
4176 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004177 builder.addDecoration(result, decorations.noContraction);
4178 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004179 }
John Kessenich140f3df2015-06-26 16:58:36 -06004180
4181 return 0;
4182}
4183
John Kessenich04bb8a02015-12-12 12:28:14 -07004184//
4185// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
4186// These can be any of:
4187//
4188// matrix * scalar
4189// scalar * matrix
4190// matrix * matrix linear algebraic
4191// matrix * vector
4192// vector * matrix
4193// matrix * matrix componentwise
4194// matrix op matrix op in {+, -, /}
4195// matrix op scalar op in {+, -, /}
4196// scalar op matrix op in {+, -, /}
4197//
John Kessenichead86222018-03-28 18:01:20 -06004198spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4199 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07004200{
4201 bool firstClass = true;
4202
4203 // First, handle first-class matrix operations (* and matrix/scalar)
4204 switch (op) {
4205 case spv::OpFDiv:
4206 if (builder.isMatrix(left) && builder.isScalar(right)) {
4207 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01004208 spv::Id resultType = builder.getTypeId(right);
4209 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07004210 op = spv::OpMatrixTimesScalar;
4211 } else
4212 firstClass = false;
4213 break;
4214 case spv::OpMatrixTimesScalar:
4215 if (builder.isMatrix(right))
4216 std::swap(left, right);
4217 assert(builder.isScalar(right));
4218 break;
4219 case spv::OpVectorTimesMatrix:
4220 assert(builder.isVector(left));
4221 assert(builder.isMatrix(right));
4222 break;
4223 case spv::OpMatrixTimesVector:
4224 assert(builder.isMatrix(left));
4225 assert(builder.isVector(right));
4226 break;
4227 case spv::OpMatrixTimesMatrix:
4228 assert(builder.isMatrix(left));
4229 assert(builder.isMatrix(right));
4230 break;
4231 default:
4232 firstClass = false;
4233 break;
4234 }
4235
qining25262b32016-05-06 17:25:16 -04004236 if (firstClass) {
4237 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004238 builder.addDecoration(result, decorations.noContraction);
4239 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004240 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004241
LoopDawg592860c2016-06-09 08:57:35 -06004242 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004243 // The result type of all of them is the same type as the (a) matrix operand.
4244 // The algorithm is to:
4245 // - break the matrix(es) into vectors
4246 // - smear any scalar to a vector
4247 // - do vector operations
4248 // - make a matrix out the vector results
4249 switch (op) {
4250 case spv::OpFAdd:
4251 case spv::OpFSub:
4252 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004253 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004254 case spv::OpFMul:
4255 {
4256 // one time set up...
4257 bool leftMat = builder.isMatrix(left);
4258 bool rightMat = builder.isMatrix(right);
4259 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4260 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4261 spv::Id scalarType = builder.getScalarTypeId(typeId);
4262 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4263 std::vector<spv::Id> results;
4264 spv::Id smearVec = spv::NoResult;
4265 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06004266 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004267 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06004268 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004269
4270 // do each vector op
4271 for (unsigned int c = 0; c < numCols; ++c) {
4272 std::vector<unsigned int> indexes;
4273 indexes.push_back(c);
4274 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4275 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004276 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06004277 builder.addDecoration(result, decorations.noContraction);
4278 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004279 }
4280
4281 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004282 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
4283 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07004284 }
4285 default:
4286 assert(0);
4287 return spv::NoResult;
4288 }
4289}
4290
John Kessenichead86222018-03-28 18:01:20 -06004291spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
4292 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004293{
4294 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004295 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004296 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07004297 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4298 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004299
4300 switch (op) {
4301 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004302 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004303 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004304 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06004305 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004306 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004307 unaryOp = spv::OpSNegate;
4308 break;
4309
4310 case glslang::EOpLogicalNot:
4311 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004312 unaryOp = spv::OpLogicalNot;
4313 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004314 case glslang::EOpBitwiseNot:
4315 unaryOp = spv::OpNot;
4316 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004317
John Kessenich140f3df2015-06-26 16:58:36 -06004318 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004319 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004320 break;
4321 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004322 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004323 break;
4324 case glslang::EOpTranspose:
4325 unaryOp = spv::OpTranspose;
4326 break;
4327
4328 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004329 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004330 break;
4331 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004332 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004333 break;
4334 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004335 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004336 break;
4337 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004338 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004339 break;
4340 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004341 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004342 break;
4343 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004344 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004345 break;
4346 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004347 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004348 break;
4349 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004350 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004351 break;
4352
4353 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004354 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004355 break;
4356 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004357 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004358 break;
4359 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004360 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004361 break;
4362 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004363 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004364 break;
4365 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004366 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004367 break;
4368 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004369 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004370 break;
4371
4372 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004373 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004374 break;
4375 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004376 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004377 break;
4378
4379 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004380 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004381 break;
4382 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004383 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004384 break;
4385 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004386 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004387 break;
4388 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004389 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004390 break;
4391 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004392 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004393 break;
4394 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004395 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004396 break;
4397
4398 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004399 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004400 break;
4401 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004402 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004403 break;
4404 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004405 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004406 break;
4407 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004408 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004409 break;
4410 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004411 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004412 break;
4413 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004414 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004415 break;
4416
4417 case glslang::EOpIsNan:
4418 unaryOp = spv::OpIsNan;
4419 break;
4420 case glslang::EOpIsInf:
4421 unaryOp = spv::OpIsInf;
4422 break;
LoopDawg592860c2016-06-09 08:57:35 -06004423 case glslang::EOpIsFinite:
4424 unaryOp = spv::OpIsFinite;
4425 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004426
Rex Xucbc426e2015-12-15 16:03:10 +08004427 case glslang::EOpFloatBitsToInt:
4428 case glslang::EOpFloatBitsToUint:
4429 case glslang::EOpIntBitsToFloat:
4430 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004431 case glslang::EOpDoubleBitsToInt64:
4432 case glslang::EOpDoubleBitsToUint64:
4433 case glslang::EOpInt64BitsToDouble:
4434 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004435 case glslang::EOpFloat16BitsToInt16:
4436 case glslang::EOpFloat16BitsToUint16:
4437 case glslang::EOpInt16BitsToFloat16:
4438 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08004439 unaryOp = spv::OpBitcast;
4440 break;
4441
John Kessenich140f3df2015-06-26 16:58:36 -06004442 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004443 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004444 break;
4445 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004446 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004447 break;
4448 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004449 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004450 break;
4451 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004452 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004453 break;
4454 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004455 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004456 break;
4457 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004458 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004459 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004460 case glslang::EOpPackSnorm4x8:
4461 libCall = spv::GLSLstd450PackSnorm4x8;
4462 break;
4463 case glslang::EOpUnpackSnorm4x8:
4464 libCall = spv::GLSLstd450UnpackSnorm4x8;
4465 break;
4466 case glslang::EOpPackUnorm4x8:
4467 libCall = spv::GLSLstd450PackUnorm4x8;
4468 break;
4469 case glslang::EOpUnpackUnorm4x8:
4470 libCall = spv::GLSLstd450UnpackUnorm4x8;
4471 break;
4472 case glslang::EOpPackDouble2x32:
4473 libCall = spv::GLSLstd450PackDouble2x32;
4474 break;
4475 case glslang::EOpUnpackDouble2x32:
4476 libCall = spv::GLSLstd450UnpackDouble2x32;
4477 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004478
Rex Xu8ff43de2016-04-22 16:51:45 +08004479 case glslang::EOpPackInt2x32:
4480 case glslang::EOpUnpackInt2x32:
4481 case glslang::EOpPackUint2x32:
4482 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07004483 case glslang::EOpPack16:
4484 case glslang::EOpPack32:
4485 case glslang::EOpPack64:
4486 case glslang::EOpUnpack32:
4487 case glslang::EOpUnpack16:
4488 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08004489 case glslang::EOpPackInt2x16:
4490 case glslang::EOpUnpackInt2x16:
4491 case glslang::EOpPackUint2x16:
4492 case glslang::EOpUnpackUint2x16:
4493 case glslang::EOpPackInt4x16:
4494 case glslang::EOpUnpackInt4x16:
4495 case glslang::EOpPackUint4x16:
4496 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004497 case glslang::EOpPackFloat2x16:
4498 case glslang::EOpUnpackFloat2x16:
4499 unaryOp = spv::OpBitcast;
4500 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004501
John Kessenich140f3df2015-06-26 16:58:36 -06004502 case glslang::EOpDPdx:
4503 unaryOp = spv::OpDPdx;
4504 break;
4505 case glslang::EOpDPdy:
4506 unaryOp = spv::OpDPdy;
4507 break;
4508 case glslang::EOpFwidth:
4509 unaryOp = spv::OpFwidth;
4510 break;
4511 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004512 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004513 unaryOp = spv::OpDPdxFine;
4514 break;
4515 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004516 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004517 unaryOp = spv::OpDPdyFine;
4518 break;
4519 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004520 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004521 unaryOp = spv::OpFwidthFine;
4522 break;
4523 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004524 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004525 unaryOp = spv::OpDPdxCoarse;
4526 break;
4527 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004528 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004529 unaryOp = spv::OpDPdyCoarse;
4530 break;
4531 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004532 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004533 unaryOp = spv::OpFwidthCoarse;
4534 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004535 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004536 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004537 libCall = spv::GLSLstd450InterpolateAtCentroid;
4538 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004539 case glslang::EOpAny:
4540 unaryOp = spv::OpAny;
4541 break;
4542 case glslang::EOpAll:
4543 unaryOp = spv::OpAll;
4544 break;
4545
4546 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004547 if (isFloat)
4548 libCall = spv::GLSLstd450FAbs;
4549 else
4550 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004551 break;
4552 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004553 if (isFloat)
4554 libCall = spv::GLSLstd450FSign;
4555 else
4556 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004557 break;
4558
John Kessenichfc51d282015-08-19 13:34:18 -06004559 case glslang::EOpAtomicCounterIncrement:
4560 case glslang::EOpAtomicCounterDecrement:
4561 case glslang::EOpAtomicCounter:
4562 {
4563 // Handle all of the atomics in one place, in createAtomicOperation()
4564 std::vector<spv::Id> operands;
4565 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06004566 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004567 }
4568
John Kessenichfc51d282015-08-19 13:34:18 -06004569 case glslang::EOpBitFieldReverse:
4570 unaryOp = spv::OpBitReverse;
4571 break;
4572 case glslang::EOpBitCount:
4573 unaryOp = spv::OpBitCount;
4574 break;
4575 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004576 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004577 break;
4578 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004579 if (isUnsigned)
4580 libCall = spv::GLSLstd450FindUMsb;
4581 else
4582 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004583 break;
4584
Rex Xu574ab042016-04-14 16:53:07 +08004585 case glslang::EOpBallot:
4586 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004587 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004588 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004589 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004590#ifdef AMD_EXTENSIONS
4591 case glslang::EOpMinInvocations:
4592 case glslang::EOpMaxInvocations:
4593 case glslang::EOpAddInvocations:
4594 case glslang::EOpMinInvocationsNonUniform:
4595 case glslang::EOpMaxInvocationsNonUniform:
4596 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004597 case glslang::EOpMinInvocationsInclusiveScan:
4598 case glslang::EOpMaxInvocationsInclusiveScan:
4599 case glslang::EOpAddInvocationsInclusiveScan:
4600 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4601 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4602 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4603 case glslang::EOpMinInvocationsExclusiveScan:
4604 case glslang::EOpMaxInvocationsExclusiveScan:
4605 case glslang::EOpAddInvocationsExclusiveScan:
4606 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4607 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4608 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004609#endif
Rex Xu51596642016-09-21 18:56:12 +08004610 {
4611 std::vector<spv::Id> operands;
4612 operands.push_back(operand);
4613 return createInvocationsOperation(op, typeId, operands, typeProxy);
4614 }
John Kessenich66011cb2018-03-06 16:12:04 -07004615 case glslang::EOpSubgroupAll:
4616 case glslang::EOpSubgroupAny:
4617 case glslang::EOpSubgroupAllEqual:
4618 case glslang::EOpSubgroupBroadcastFirst:
4619 case glslang::EOpSubgroupBallot:
4620 case glslang::EOpSubgroupInverseBallot:
4621 case glslang::EOpSubgroupBallotBitCount:
4622 case glslang::EOpSubgroupBallotInclusiveBitCount:
4623 case glslang::EOpSubgroupBallotExclusiveBitCount:
4624 case glslang::EOpSubgroupBallotFindLSB:
4625 case glslang::EOpSubgroupBallotFindMSB:
4626 case glslang::EOpSubgroupAdd:
4627 case glslang::EOpSubgroupMul:
4628 case glslang::EOpSubgroupMin:
4629 case glslang::EOpSubgroupMax:
4630 case glslang::EOpSubgroupAnd:
4631 case glslang::EOpSubgroupOr:
4632 case glslang::EOpSubgroupXor:
4633 case glslang::EOpSubgroupInclusiveAdd:
4634 case glslang::EOpSubgroupInclusiveMul:
4635 case glslang::EOpSubgroupInclusiveMin:
4636 case glslang::EOpSubgroupInclusiveMax:
4637 case glslang::EOpSubgroupInclusiveAnd:
4638 case glslang::EOpSubgroupInclusiveOr:
4639 case glslang::EOpSubgroupInclusiveXor:
4640 case glslang::EOpSubgroupExclusiveAdd:
4641 case glslang::EOpSubgroupExclusiveMul:
4642 case glslang::EOpSubgroupExclusiveMin:
4643 case glslang::EOpSubgroupExclusiveMax:
4644 case glslang::EOpSubgroupExclusiveAnd:
4645 case glslang::EOpSubgroupExclusiveOr:
4646 case glslang::EOpSubgroupExclusiveXor:
4647 case glslang::EOpSubgroupQuadSwapHorizontal:
4648 case glslang::EOpSubgroupQuadSwapVertical:
4649 case glslang::EOpSubgroupQuadSwapDiagonal: {
4650 std::vector<spv::Id> operands;
4651 operands.push_back(operand);
4652 return createSubgroupOperation(op, typeId, operands, typeProxy);
4653 }
Rex Xu9d93a232016-05-05 12:30:44 +08004654#ifdef AMD_EXTENSIONS
4655 case glslang::EOpMbcnt:
4656 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4657 libCall = spv::MbcntAMD;
4658 break;
4659
4660 case glslang::EOpCubeFaceIndex:
4661 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4662 libCall = spv::CubeFaceIndexAMD;
4663 break;
4664
4665 case glslang::EOpCubeFaceCoord:
4666 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4667 libCall = spv::CubeFaceCoordAMD;
4668 break;
4669#endif
Rex Xu338b1852016-05-05 20:38:33 +08004670
John Kessenich140f3df2015-06-26 16:58:36 -06004671 default:
4672 return 0;
4673 }
4674
4675 spv::Id id;
4676 if (libCall >= 0) {
4677 std::vector<spv::Id> args;
4678 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004679 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004680 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004681 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004682 }
John Kessenich140f3df2015-06-26 16:58:36 -06004683
John Kessenichead86222018-03-28 18:01:20 -06004684 builder.addDecoration(id, decorations.noContraction);
4685 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004686}
4687
John Kessenich7a53f762016-01-20 11:19:27 -07004688// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06004689spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4690 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07004691{
4692 // Handle unary operations vector by vector.
4693 // The result type is the same type as the original type.
4694 // The algorithm is to:
4695 // - break the matrix into vectors
4696 // - apply the operation to each vector
4697 // - make a matrix out the vector results
4698
4699 // get the types sorted out
4700 int numCols = builder.getNumColumns(operand);
4701 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004702 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4703 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004704 std::vector<spv::Id> results;
4705
4706 // do each vector op
4707 for (int c = 0; c < numCols; ++c) {
4708 std::vector<unsigned int> indexes;
4709 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004710 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4711 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06004712 builder.addDecoration(destVec, decorations.noContraction);
4713 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004714 }
4715
4716 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004717 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
4718 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07004719}
4720
John Kessenich66011cb2018-03-06 16:12:04 -07004721spv::Id TGlslangToSpvTraverser::createConversionOperation(glslang::TOperator op, spv::Id operand, int vectorSize)
4722{
4723 spv::Op convOp = spv::OpNop;
4724 spv::Id type = 0;
4725
4726 spv::Id result = 0;
4727
4728 switch(op) {
4729 case glslang::EOpConvInt8ToUint16:
4730 convOp = spv::OpSConvert;
4731 type = builder.makeIntType(16);
4732 break;
4733 case glslang::EOpConvInt8ToUint:
4734 convOp = spv::OpSConvert;
4735 type = builder.makeIntType(32);
4736 break;
4737 case glslang::EOpConvInt8ToUint64:
4738 convOp = spv::OpSConvert;
4739 type = builder.makeIntType(64);
4740 break;
4741 case glslang::EOpConvInt16ToUint8:
4742 convOp = spv::OpSConvert;
4743 type = builder.makeIntType(8);
4744 break;
4745 case glslang::EOpConvInt16ToUint:
4746 convOp = spv::OpSConvert;
4747 type = builder.makeIntType(32);
4748 break;
4749 case glslang::EOpConvInt16ToUint64:
4750 convOp = spv::OpSConvert;
4751 type = builder.makeIntType(64);
4752 break;
4753 case glslang::EOpConvIntToUint8:
4754 convOp = spv::OpSConvert;
4755 type = builder.makeIntType(8);
4756 break;
4757 case glslang::EOpConvIntToUint16:
4758 convOp = spv::OpSConvert;
4759 type = builder.makeIntType(16);
4760 break;
4761 case glslang::EOpConvIntToUint64:
4762 convOp = spv::OpSConvert;
4763 type = builder.makeIntType(64);
4764 break;
4765 case glslang::EOpConvInt64ToUint8:
4766 convOp = spv::OpSConvert;
4767 type = builder.makeIntType(8);
4768 break;
4769 case glslang::EOpConvInt64ToUint16:
4770 convOp = spv::OpSConvert;
4771 type = builder.makeIntType(16);
4772 break;
4773 case glslang::EOpConvInt64ToUint:
4774 convOp = spv::OpSConvert;
4775 type = builder.makeIntType(32);
4776 break;
4777 case glslang::EOpConvUint8ToInt16:
4778 convOp = spv::OpUConvert;
4779 type = builder.makeIntType(16);
4780 break;
4781 case glslang::EOpConvUint8ToInt:
4782 convOp = spv::OpUConvert;
4783 type = builder.makeIntType(32);
4784 break;
4785 case glslang::EOpConvUint8ToInt64:
4786 convOp = spv::OpUConvert;
4787 type = builder.makeIntType(64);
4788 break;
4789 case glslang::EOpConvUint16ToInt8:
4790 convOp = spv::OpUConvert;
4791 type = builder.makeIntType(8);
4792 break;
4793 case glslang::EOpConvUint16ToInt:
4794 convOp = spv::OpUConvert;
4795 type = builder.makeIntType(32);
4796 break;
4797 case glslang::EOpConvUint16ToInt64:
4798 convOp = spv::OpUConvert;
4799 type = builder.makeIntType(64);
4800 break;
4801 case glslang::EOpConvUintToInt8:
4802 convOp = spv::OpUConvert;
4803 type = builder.makeIntType(8);
4804 break;
4805 case glslang::EOpConvUintToInt16:
4806 convOp = spv::OpUConvert;
4807 type = builder.makeIntType(16);
4808 break;
4809 case glslang::EOpConvUintToInt64:
4810 convOp = spv::OpUConvert;
4811 type = builder.makeIntType(64);
4812 break;
4813 case glslang::EOpConvUint64ToInt8:
4814 convOp = spv::OpUConvert;
4815 type = builder.makeIntType(8);
4816 break;
4817 case glslang::EOpConvUint64ToInt16:
4818 convOp = spv::OpUConvert;
4819 type = builder.makeIntType(16);
4820 break;
4821 case glslang::EOpConvUint64ToInt:
4822 convOp = spv::OpUConvert;
4823 type = builder.makeIntType(32);
4824 break;
4825
4826 default:
4827 assert(false && "Default missing");
4828 break;
4829 }
4830
4831 if (vectorSize > 0)
4832 type = builder.makeVectorType(type, vectorSize);
4833
4834 result = builder.createUnaryOp(convOp, type, operand);
4835 return result;
4836}
4837
John Kessenichead86222018-03-28 18:01:20 -06004838spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
4839 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004840{
4841 spv::Op convOp = spv::OpNop;
4842 spv::Id zero = 0;
4843 spv::Id one = 0;
4844
4845 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4846
4847 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07004848 case glslang::EOpConvInt8ToBool:
4849 case glslang::EOpConvUint8ToBool:
4850 zero = builder.makeUint8Constant(0);
4851 zero = makeSmearedConstant(zero, vectorSize);
4852 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08004853 case glslang::EOpConvInt16ToBool:
4854 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07004855 zero = builder.makeUint16Constant(0);
4856 zero = makeSmearedConstant(zero, vectorSize);
4857 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4858 case glslang::EOpConvIntToBool:
4859 case glslang::EOpConvUintToBool:
4860 zero = builder.makeUintConstant(0);
4861 zero = makeSmearedConstant(zero, vectorSize);
4862 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4863 case glslang::EOpConvInt64ToBool:
4864 case glslang::EOpConvUint64ToBool:
4865 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004866 zero = makeSmearedConstant(zero, vectorSize);
4867 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4868
4869 case glslang::EOpConvFloatToBool:
4870 zero = builder.makeFloatConstant(0.0F);
4871 zero = makeSmearedConstant(zero, vectorSize);
4872 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4873
4874 case glslang::EOpConvDoubleToBool:
4875 zero = builder.makeDoubleConstant(0.0);
4876 zero = makeSmearedConstant(zero, vectorSize);
4877 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4878
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004879 case glslang::EOpConvFloat16ToBool:
4880 zero = builder.makeFloat16Constant(0.0F);
4881 zero = makeSmearedConstant(zero, vectorSize);
4882 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004883
John Kessenich140f3df2015-06-26 16:58:36 -06004884 case glslang::EOpConvBoolToFloat:
4885 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004886 zero = builder.makeFloatConstant(0.0F);
4887 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004888 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004889
John Kessenich140f3df2015-06-26 16:58:36 -06004890 case glslang::EOpConvBoolToDouble:
4891 convOp = spv::OpSelect;
4892 zero = builder.makeDoubleConstant(0.0);
4893 one = builder.makeDoubleConstant(1.0);
4894 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004895
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004896 case glslang::EOpConvBoolToFloat16:
4897 convOp = spv::OpSelect;
4898 zero = builder.makeFloat16Constant(0.0F);
4899 one = builder.makeFloat16Constant(1.0F);
4900 break;
John Kessenich66011cb2018-03-06 16:12:04 -07004901
4902 case glslang::EOpConvBoolToInt8:
4903 zero = builder.makeInt8Constant(0);
4904 one = builder.makeInt8Constant(1);
4905 convOp = spv::OpSelect;
4906 break;
4907
4908 case glslang::EOpConvBoolToUint8:
4909 zero = builder.makeUint8Constant(0);
4910 one = builder.makeUint8Constant(1);
4911 convOp = spv::OpSelect;
4912 break;
4913
4914 case glslang::EOpConvBoolToInt16:
4915 zero = builder.makeInt16Constant(0);
4916 one = builder.makeInt16Constant(1);
4917 convOp = spv::OpSelect;
4918 break;
4919
4920 case glslang::EOpConvBoolToUint16:
4921 zero = builder.makeUint16Constant(0);
4922 one = builder.makeUint16Constant(1);
4923 convOp = spv::OpSelect;
4924 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004925
John Kessenich140f3df2015-06-26 16:58:36 -06004926 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004927 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004928 if (op == glslang::EOpConvBoolToInt64)
4929 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08004930 else
4931 zero = builder.makeIntConstant(0);
4932
4933 if (op == glslang::EOpConvBoolToInt64)
4934 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08004935 else
4936 one = builder.makeIntConstant(1);
4937
John Kessenich140f3df2015-06-26 16:58:36 -06004938 convOp = spv::OpSelect;
4939 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004940
John Kessenich140f3df2015-06-26 16:58:36 -06004941 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004942 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004943 if (op == glslang::EOpConvBoolToUint64)
4944 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08004945 else
4946 zero = builder.makeUintConstant(0);
4947
4948 if (op == glslang::EOpConvBoolToUint64)
4949 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08004950 else
4951 one = builder.makeUintConstant(1);
4952
John Kessenich140f3df2015-06-26 16:58:36 -06004953 convOp = spv::OpSelect;
4954 break;
4955
John Kessenich66011cb2018-03-06 16:12:04 -07004956 case glslang::EOpConvInt8ToFloat16:
4957 case glslang::EOpConvInt8ToFloat:
4958 case glslang::EOpConvInt8ToDouble:
4959 case glslang::EOpConvInt16ToFloat16:
4960 case glslang::EOpConvInt16ToFloat:
4961 case glslang::EOpConvInt16ToDouble:
4962 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06004963 case glslang::EOpConvIntToFloat:
4964 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004965 case glslang::EOpConvInt64ToFloat:
4966 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004967 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06004968 convOp = spv::OpConvertSToF;
4969 break;
4970
John Kessenich66011cb2018-03-06 16:12:04 -07004971 case glslang::EOpConvUint8ToFloat16:
4972 case glslang::EOpConvUint8ToFloat:
4973 case glslang::EOpConvUint8ToDouble:
4974 case glslang::EOpConvUint16ToFloat16:
4975 case glslang::EOpConvUint16ToFloat:
4976 case glslang::EOpConvUint16ToDouble:
4977 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06004978 case glslang::EOpConvUintToFloat:
4979 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004980 case glslang::EOpConvUint64ToFloat:
4981 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004982 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06004983 convOp = spv::OpConvertUToF;
4984 break;
4985
4986 case glslang::EOpConvDoubleToFloat:
4987 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004988 case glslang::EOpConvDoubleToFloat16:
4989 case glslang::EOpConvFloat16ToDouble:
4990 case glslang::EOpConvFloatToFloat16:
4991 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06004992 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004993 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06004994 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004995 break;
4996
John Kessenich66011cb2018-03-06 16:12:04 -07004997 case glslang::EOpConvFloat16ToInt8:
4998 case glslang::EOpConvFloatToInt8:
4999 case glslang::EOpConvDoubleToInt8:
5000 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005001 case glslang::EOpConvFloatToInt16:
5002 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005003 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005004 case glslang::EOpConvFloatToInt:
5005 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005006 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005007 case glslang::EOpConvFloatToInt64:
5008 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005009 convOp = spv::OpConvertFToS;
5010 break;
5011
John Kessenich66011cb2018-03-06 16:12:04 -07005012 case glslang::EOpConvUint8ToInt8:
5013 case glslang::EOpConvInt8ToUint8:
5014 case glslang::EOpConvUint16ToInt16:
5015 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005016 case glslang::EOpConvUintToInt:
5017 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005018 case glslang::EOpConvUint64ToInt64:
5019 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005020 if (builder.isInSpecConstCodeGenMode()) {
5021 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005022 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5023 zero = builder.makeUint8Constant(0);
5024 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005025 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005026 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5027 zero = builder.makeUint64Constant(0);
5028 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005029 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005030 }
qining189b2032016-04-12 23:16:20 -04005031 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005032 // Use OpIAdd, instead of OpBitcast to do the conversion when
5033 // generating for OpSpecConstantOp instruction.
5034 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5035 }
5036 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005037 convOp = spv::OpBitcast;
5038 break;
5039
John Kessenich66011cb2018-03-06 16:12:04 -07005040 case glslang::EOpConvFloat16ToUint8:
5041 case glslang::EOpConvFloatToUint8:
5042 case glslang::EOpConvDoubleToUint8:
5043 case glslang::EOpConvFloat16ToUint16:
5044 case glslang::EOpConvFloatToUint16:
5045 case glslang::EOpConvDoubleToUint16:
5046 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005047 case glslang::EOpConvFloatToUint:
5048 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005049 case glslang::EOpConvFloatToUint64:
5050 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005051 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005052 convOp = spv::OpConvertFToU;
5053 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005054
John Kessenich66011cb2018-03-06 16:12:04 -07005055 case glslang::EOpConvInt8ToInt16:
5056 case glslang::EOpConvInt8ToInt:
5057 case glslang::EOpConvInt8ToInt64:
5058 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005059 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005060 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005061 case glslang::EOpConvIntToInt8:
5062 case glslang::EOpConvIntToInt16:
5063 case glslang::EOpConvIntToInt64:
5064 case glslang::EOpConvInt64ToInt8:
5065 case glslang::EOpConvInt64ToInt16:
5066 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005067 convOp = spv::OpSConvert;
5068 break;
5069
John Kessenich66011cb2018-03-06 16:12:04 -07005070 case glslang::EOpConvUint8ToUint16:
5071 case glslang::EOpConvUint8ToUint:
5072 case glslang::EOpConvUint8ToUint64:
5073 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005074 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005075 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005076 case glslang::EOpConvUintToUint8:
5077 case glslang::EOpConvUintToUint16:
5078 case glslang::EOpConvUintToUint64:
5079 case glslang::EOpConvUint64ToUint8:
5080 case glslang::EOpConvUint64ToUint16:
5081 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005082 convOp = spv::OpUConvert;
5083 break;
5084
John Kessenich66011cb2018-03-06 16:12:04 -07005085 case glslang::EOpConvInt8ToUint16:
5086 case glslang::EOpConvInt8ToUint:
5087 case glslang::EOpConvInt8ToUint64:
5088 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005089 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005090 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005091 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005092 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005093 case glslang::EOpConvIntToUint64:
5094 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005095 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005096 case glslang::EOpConvInt64ToUint:
5097 case glslang::EOpConvUint8ToInt16:
5098 case glslang::EOpConvUint8ToInt:
5099 case glslang::EOpConvUint8ToInt64:
5100 case glslang::EOpConvUint16ToInt8:
5101 case glslang::EOpConvUint16ToInt:
5102 case glslang::EOpConvUint16ToInt64:
5103 case glslang::EOpConvUintToInt8:
5104 case glslang::EOpConvUintToInt16:
5105 case glslang::EOpConvUintToInt64:
5106 case glslang::EOpConvUint64ToInt8:
5107 case glslang::EOpConvUint64ToInt16:
5108 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005109 // OpSConvert/OpUConvert + OpBitCast
John Kessenich66011cb2018-03-06 16:12:04 -07005110 operand = createConversionOperation(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005111
5112 if (builder.isInSpecConstCodeGenMode()) {
5113 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005114 switch(op) {
5115 case glslang::EOpConvInt16ToUint8:
5116 case glslang::EOpConvIntToUint8:
5117 case glslang::EOpConvInt64ToUint8:
5118 case glslang::EOpConvUint16ToInt8:
5119 case glslang::EOpConvUintToInt8:
5120 case glslang::EOpConvUint64ToInt8:
5121 zero = builder.makeUint8Constant(0);
5122 break;
5123 case glslang::EOpConvInt8ToUint16:
5124 case glslang::EOpConvIntToUint16:
5125 case glslang::EOpConvInt64ToUint16:
5126 case glslang::EOpConvUint8ToInt16:
5127 case glslang::EOpConvUintToInt16:
5128 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005129 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005130 break;
5131 case glslang::EOpConvInt8ToUint:
5132 case glslang::EOpConvInt16ToUint:
5133 case glslang::EOpConvInt64ToUint:
5134 case glslang::EOpConvUint8ToInt:
5135 case glslang::EOpConvUint16ToInt:
5136 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005137 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005138 break;
5139 case glslang::EOpConvInt8ToUint64:
5140 case glslang::EOpConvInt16ToUint64:
5141 case glslang::EOpConvIntToUint64:
5142 case glslang::EOpConvUint8ToInt64:
5143 case glslang::EOpConvUint16ToInt64:
5144 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005145 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005146 break;
5147 default:
5148 assert(false && "Default missing");
5149 break;
5150 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005151 zero = makeSmearedConstant(zero, vectorSize);
5152 // Use OpIAdd, instead of OpBitcast to do the conversion when
5153 // generating for OpSpecConstantOp instruction.
5154 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5155 }
5156 // For normal run-time conversion instruction, use OpBitcast.
5157 convOp = spv::OpBitcast;
5158 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005159 default:
5160 break;
5161 }
5162
5163 spv::Id result = 0;
5164 if (convOp == spv::OpNop)
5165 return result;
5166
5167 if (convOp == spv::OpSelect) {
5168 zero = makeSmearedConstant(zero, vectorSize);
5169 one = makeSmearedConstant(one, vectorSize);
5170 result = builder.createTriOp(convOp, destType, operand, one, zero);
5171 } else
5172 result = builder.createUnaryOp(convOp, destType, operand);
5173
John Kessenichead86222018-03-28 18:01:20 -06005174 result = builder.setPrecision(result, decorations.precision);
5175 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06005176}
5177
5178spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
5179{
5180 if (vectorSize == 0)
5181 return constant;
5182
5183 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
5184 std::vector<spv::Id> components;
5185 for (int c = 0; c < vectorSize; ++c)
5186 components.push_back(constant);
5187 return builder.makeCompositeConstant(vectorTypeId, components);
5188}
5189
John Kessenich426394d2015-07-23 10:22:48 -06005190// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07005191spv::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 -06005192{
5193 spv::Op opCode = spv::OpNop;
5194
5195 switch (op) {
5196 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08005197 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005198 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06005199 opCode = spv::OpAtomicIAdd;
5200 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06005201 case glslang::EOpAtomicCounterSubtract:
5202 opCode = spv::OpAtomicISub;
5203 break;
John Kessenich426394d2015-07-23 10:22:48 -06005204 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08005205 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005206 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08005207 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06005208 break;
5209 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08005210 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005211 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08005212 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06005213 break;
5214 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08005215 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005216 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06005217 opCode = spv::OpAtomicAnd;
5218 break;
5219 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08005220 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005221 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06005222 opCode = spv::OpAtomicOr;
5223 break;
5224 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08005225 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005226 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06005227 opCode = spv::OpAtomicXor;
5228 break;
5229 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08005230 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005231 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06005232 opCode = spv::OpAtomicExchange;
5233 break;
5234 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08005235 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005236 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06005237 opCode = spv::OpAtomicCompareExchange;
5238 break;
5239 case glslang::EOpAtomicCounterIncrement:
5240 opCode = spv::OpAtomicIIncrement;
5241 break;
5242 case glslang::EOpAtomicCounterDecrement:
5243 opCode = spv::OpAtomicIDecrement;
5244 break;
5245 case glslang::EOpAtomicCounter:
5246 opCode = spv::OpAtomicLoad;
5247 break;
5248 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005249 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06005250 break;
5251 }
5252
Rex Xue8fe8b02017-09-26 15:42:56 +08005253 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
5254 builder.addCapability(spv::CapabilityInt64Atomics);
5255
John Kessenich426394d2015-07-23 10:22:48 -06005256 // Sort out the operands
5257 // - mapping from glslang -> SPV
5258 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06005259 // - compare-exchange swaps the value and comparator
5260 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06005261 // - EOpAtomicCounterDecrement needs a post decrement
John Kessenich426394d2015-07-23 10:22:48 -06005262 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
5263 auto opIt = operands.begin(); // walk the glslang operands
5264 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08005265 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
5266 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
5267 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08005268 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
5269 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08005270 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06005271 spvAtomicOperands.push_back(*(opIt + 1));
5272 spvAtomicOperands.push_back(*opIt);
5273 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08005274 }
John Kessenich426394d2015-07-23 10:22:48 -06005275
John Kessenich3e60a6f2015-09-14 22:45:16 -06005276 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06005277 for (; opIt != operands.end(); ++opIt)
5278 spvAtomicOperands.push_back(*opIt);
5279
John Kessenich48d6e792017-10-06 21:21:48 -06005280 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
5281
5282 // GLSL and HLSL atomic-counter decrement return post-decrement value,
5283 // while SPIR-V returns pre-decrement value. Translate between these semantics.
5284 if (op == glslang::EOpAtomicCounterDecrement)
5285 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
5286
5287 return resultId;
John Kessenich426394d2015-07-23 10:22:48 -06005288}
5289
John Kessenich91cef522016-05-05 16:45:40 -06005290// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08005291spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06005292{
John Kessenich66011cb2018-03-06 16:12:04 -07005293 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5294 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08005295
Rex Xu51596642016-09-21 18:56:12 +08005296 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08005297 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08005298 spv::GroupOperation groupOperation = spv::GroupOperationMax;
5299
chaocf200da82016-12-20 12:44:35 -08005300 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
5301 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08005302 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
5303 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005304 } else if (op == glslang::EOpAnyInvocation ||
5305 op == glslang::EOpAllInvocations ||
5306 op == glslang::EOpAllInvocationsEqual) {
5307 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
5308 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08005309 } else {
5310 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04005311#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08005312 if (op == glslang::EOpMinInvocationsNonUniform ||
5313 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08005314 op == glslang::EOpAddInvocationsNonUniform ||
5315 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5316 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5317 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
5318 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
5319 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
5320 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08005321 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04005322#endif
Rex Xu51596642016-09-21 18:56:12 +08005323
5324 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08005325#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08005326 switch (op) {
5327 case glslang::EOpMinInvocations:
5328 case glslang::EOpMaxInvocations:
5329 case glslang::EOpAddInvocations:
5330 case glslang::EOpMinInvocationsNonUniform:
5331 case glslang::EOpMaxInvocationsNonUniform:
5332 case glslang::EOpAddInvocationsNonUniform:
5333 groupOperation = spv::GroupOperationReduce;
5334 spvGroupOperands.push_back(groupOperation);
5335 break;
5336 case glslang::EOpMinInvocationsInclusiveScan:
5337 case glslang::EOpMaxInvocationsInclusiveScan:
5338 case glslang::EOpAddInvocationsInclusiveScan:
5339 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5340 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5341 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5342 groupOperation = spv::GroupOperationInclusiveScan;
5343 spvGroupOperands.push_back(groupOperation);
5344 break;
5345 case glslang::EOpMinInvocationsExclusiveScan:
5346 case glslang::EOpMaxInvocationsExclusiveScan:
5347 case glslang::EOpAddInvocationsExclusiveScan:
5348 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5349 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5350 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5351 groupOperation = spv::GroupOperationExclusiveScan;
5352 spvGroupOperands.push_back(groupOperation);
5353 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07005354 default:
5355 break;
Rex Xu430ef402016-10-14 17:22:23 +08005356 }
Rex Xu9d93a232016-05-05 12:30:44 +08005357#endif
Rex Xu51596642016-09-21 18:56:12 +08005358 }
5359
5360 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
5361 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06005362
5363 switch (op) {
5364 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005365 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08005366 break;
John Kessenich91cef522016-05-05 16:45:40 -06005367 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005368 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08005369 break;
John Kessenich91cef522016-05-05 16:45:40 -06005370 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005371 opCode = spv::OpSubgroupAllEqualKHR;
5372 break;
Rex Xu51596642016-09-21 18:56:12 +08005373 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08005374 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08005375 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005376 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005377 break;
5378 case glslang::EOpReadFirstInvocation:
5379 opCode = spv::OpSubgroupFirstInvocationKHR;
5380 break;
5381 case glslang::EOpBallot:
5382 {
5383 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
5384 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
5385 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
5386 //
5387 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
5388 //
5389 spv::Id uintType = builder.makeUintType(32);
5390 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
5391 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
5392
5393 std::vector<spv::Id> components;
5394 components.push_back(builder.createCompositeExtract(result, uintType, 0));
5395 components.push_back(builder.createCompositeExtract(result, uintType, 1));
5396
5397 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
5398 return builder.createUnaryOp(spv::OpBitcast, typeId,
5399 builder.createCompositeConstruct(uvec2Type, components));
5400 }
5401
Rex Xu9d93a232016-05-05 12:30:44 +08005402#ifdef AMD_EXTENSIONS
5403 case glslang::EOpMinInvocations:
5404 case glslang::EOpMaxInvocations:
5405 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08005406 case glslang::EOpMinInvocationsInclusiveScan:
5407 case glslang::EOpMaxInvocationsInclusiveScan:
5408 case glslang::EOpAddInvocationsInclusiveScan:
5409 case glslang::EOpMinInvocationsExclusiveScan:
5410 case glslang::EOpMaxInvocationsExclusiveScan:
5411 case glslang::EOpAddInvocationsExclusiveScan:
5412 if (op == glslang::EOpMinInvocations ||
5413 op == glslang::EOpMinInvocationsInclusiveScan ||
5414 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005415 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005416 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005417 else {
5418 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005419 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005420 else
Rex Xu51596642016-09-21 18:56:12 +08005421 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005422 }
Rex Xu430ef402016-10-14 17:22:23 +08005423 } else if (op == glslang::EOpMaxInvocations ||
5424 op == glslang::EOpMaxInvocationsInclusiveScan ||
5425 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005426 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005427 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005428 else {
5429 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005430 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005431 else
Rex Xu51596642016-09-21 18:56:12 +08005432 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005433 }
5434 } else {
5435 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005436 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005437 else
Rex Xu51596642016-09-21 18:56:12 +08005438 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005439 }
5440
Rex Xu2bbbe062016-08-23 15:41:05 +08005441 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005442 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005443
5444 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005445 case glslang::EOpMinInvocationsNonUniform:
5446 case glslang::EOpMaxInvocationsNonUniform:
5447 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005448 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5449 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5450 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5451 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5452 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5453 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5454 if (op == glslang::EOpMinInvocationsNonUniform ||
5455 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5456 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005457 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005458 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005459 else {
5460 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005461 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005462 else
Rex Xu51596642016-09-21 18:56:12 +08005463 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005464 }
5465 }
Rex Xu430ef402016-10-14 17:22:23 +08005466 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5467 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5468 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005469 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005470 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005471 else {
5472 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005473 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005474 else
Rex Xu51596642016-09-21 18:56:12 +08005475 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005476 }
5477 }
5478 else {
5479 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005480 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005481 else
Rex Xu51596642016-09-21 18:56:12 +08005482 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005483 }
5484
Rex Xu2bbbe062016-08-23 15:41:05 +08005485 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005486 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005487
5488 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005489#endif
John Kessenich91cef522016-05-05 16:45:40 -06005490 default:
5491 logger->missingFunctionality("invocation operation");
5492 return spv::NoResult;
5493 }
Rex Xu51596642016-09-21 18:56:12 +08005494
5495 assert(opCode != spv::OpNop);
5496 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005497}
5498
Rex Xu2bbbe062016-08-23 15:41:05 +08005499// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005500spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005501{
Rex Xub7072052016-09-26 15:53:40 +08005502#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005503 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5504 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005505 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005506 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005507 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5508 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5509 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005510#else
5511 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5512 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005513 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5514 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005515#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005516
5517 // Handle group invocation operations scalar by scalar.
5518 // The result type is the same type as the original type.
5519 // The algorithm is to:
5520 // - break the vector into scalars
5521 // - apply the operation to each scalar
5522 // - make a vector out the scalar results
5523
5524 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005525 int numComponents = builder.getNumComponents(operands[0]);
5526 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005527 std::vector<spv::Id> results;
5528
5529 // do each scalar op
5530 for (int comp = 0; comp < numComponents; ++comp) {
5531 std::vector<unsigned int> indexes;
5532 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005533 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005534 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005535 if (op == spv::OpSubgroupReadInvocationKHR) {
5536 spvGroupOperands.push_back(scalar);
5537 spvGroupOperands.push_back(operands[1]);
5538 } else if (op == spv::OpGroupBroadcast) {
5539 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005540 spvGroupOperands.push_back(scalar);
5541 spvGroupOperands.push_back(operands[1]);
5542 } else {
chaocf200da82016-12-20 12:44:35 -08005543 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005544 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005545 spvGroupOperands.push_back(scalar);
5546 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005547
Rex Xub7072052016-09-26 15:53:40 +08005548 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005549 }
5550
5551 // put the pieces together
5552 return builder.createCompositeConstruct(typeId, results);
5553}
Rex Xu2bbbe062016-08-23 15:41:05 +08005554
John Kessenich66011cb2018-03-06 16:12:04 -07005555// Create subgroup invocation operations.
5556spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
5557{
5558 // Add the required capabilities.
5559 switch (op) {
5560 case glslang::EOpSubgroupElect:
5561 builder.addCapability(spv::CapabilityGroupNonUniform);
5562 break;
5563 case glslang::EOpSubgroupAll:
5564 case glslang::EOpSubgroupAny:
5565 case glslang::EOpSubgroupAllEqual:
5566 builder.addCapability(spv::CapabilityGroupNonUniform);
5567 builder.addCapability(spv::CapabilityGroupNonUniformVote);
5568 break;
5569 case glslang::EOpSubgroupBroadcast:
5570 case glslang::EOpSubgroupBroadcastFirst:
5571 case glslang::EOpSubgroupBallot:
5572 case glslang::EOpSubgroupInverseBallot:
5573 case glslang::EOpSubgroupBallotBitExtract:
5574 case glslang::EOpSubgroupBallotBitCount:
5575 case glslang::EOpSubgroupBallotInclusiveBitCount:
5576 case glslang::EOpSubgroupBallotExclusiveBitCount:
5577 case glslang::EOpSubgroupBallotFindLSB:
5578 case glslang::EOpSubgroupBallotFindMSB:
5579 builder.addCapability(spv::CapabilityGroupNonUniform);
5580 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
5581 break;
5582 case glslang::EOpSubgroupShuffle:
5583 case glslang::EOpSubgroupShuffleXor:
5584 builder.addCapability(spv::CapabilityGroupNonUniform);
5585 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
5586 break;
5587 case glslang::EOpSubgroupShuffleUp:
5588 case glslang::EOpSubgroupShuffleDown:
5589 builder.addCapability(spv::CapabilityGroupNonUniform);
5590 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
5591 break;
5592 case glslang::EOpSubgroupAdd:
5593 case glslang::EOpSubgroupMul:
5594 case glslang::EOpSubgroupMin:
5595 case glslang::EOpSubgroupMax:
5596 case glslang::EOpSubgroupAnd:
5597 case glslang::EOpSubgroupOr:
5598 case glslang::EOpSubgroupXor:
5599 case glslang::EOpSubgroupInclusiveAdd:
5600 case glslang::EOpSubgroupInclusiveMul:
5601 case glslang::EOpSubgroupInclusiveMin:
5602 case glslang::EOpSubgroupInclusiveMax:
5603 case glslang::EOpSubgroupInclusiveAnd:
5604 case glslang::EOpSubgroupInclusiveOr:
5605 case glslang::EOpSubgroupInclusiveXor:
5606 case glslang::EOpSubgroupExclusiveAdd:
5607 case glslang::EOpSubgroupExclusiveMul:
5608 case glslang::EOpSubgroupExclusiveMin:
5609 case glslang::EOpSubgroupExclusiveMax:
5610 case glslang::EOpSubgroupExclusiveAnd:
5611 case glslang::EOpSubgroupExclusiveOr:
5612 case glslang::EOpSubgroupExclusiveXor:
5613 builder.addCapability(spv::CapabilityGroupNonUniform);
5614 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
5615 break;
5616 case glslang::EOpSubgroupClusteredAdd:
5617 case glslang::EOpSubgroupClusteredMul:
5618 case glslang::EOpSubgroupClusteredMin:
5619 case glslang::EOpSubgroupClusteredMax:
5620 case glslang::EOpSubgroupClusteredAnd:
5621 case glslang::EOpSubgroupClusteredOr:
5622 case glslang::EOpSubgroupClusteredXor:
5623 builder.addCapability(spv::CapabilityGroupNonUniform);
5624 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
5625 break;
5626 case glslang::EOpSubgroupQuadBroadcast:
5627 case glslang::EOpSubgroupQuadSwapHorizontal:
5628 case glslang::EOpSubgroupQuadSwapVertical:
5629 case glslang::EOpSubgroupQuadSwapDiagonal:
5630 builder.addCapability(spv::CapabilityGroupNonUniform);
5631 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
5632 break;
5633 default: assert(0 && "Unhandled subgroup operation!");
5634 }
5635
5636 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
5637 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
5638 const bool isBool = typeProxy == glslang::EbtBool;
5639
5640 spv::Op opCode = spv::OpNop;
5641
5642 // Figure out which opcode to use.
5643 switch (op) {
5644 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
5645 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
5646 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
5647 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
5648 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
5649 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
5650 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
5651 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
5652 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
5653 case glslang::EOpSubgroupBallotBitCount:
5654 case glslang::EOpSubgroupBallotInclusiveBitCount:
5655 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
5656 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
5657 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
5658 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
5659 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
5660 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
5661 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
5662 case glslang::EOpSubgroupAdd:
5663 case glslang::EOpSubgroupInclusiveAdd:
5664 case glslang::EOpSubgroupExclusiveAdd:
5665 case glslang::EOpSubgroupClusteredAdd:
5666 if (isFloat) {
5667 opCode = spv::OpGroupNonUniformFAdd;
5668 } else {
5669 opCode = spv::OpGroupNonUniformIAdd;
5670 }
5671 break;
5672 case glslang::EOpSubgroupMul:
5673 case glslang::EOpSubgroupInclusiveMul:
5674 case glslang::EOpSubgroupExclusiveMul:
5675 case glslang::EOpSubgroupClusteredMul:
5676 if (isFloat) {
5677 opCode = spv::OpGroupNonUniformFMul;
5678 } else {
5679 opCode = spv::OpGroupNonUniformIMul;
5680 }
5681 break;
5682 case glslang::EOpSubgroupMin:
5683 case glslang::EOpSubgroupInclusiveMin:
5684 case glslang::EOpSubgroupExclusiveMin:
5685 case glslang::EOpSubgroupClusteredMin:
5686 if (isFloat) {
5687 opCode = spv::OpGroupNonUniformFMin;
5688 } else if (isUnsigned) {
5689 opCode = spv::OpGroupNonUniformUMin;
5690 } else {
5691 opCode = spv::OpGroupNonUniformSMin;
5692 }
5693 break;
5694 case glslang::EOpSubgroupMax:
5695 case glslang::EOpSubgroupInclusiveMax:
5696 case glslang::EOpSubgroupExclusiveMax:
5697 case glslang::EOpSubgroupClusteredMax:
5698 if (isFloat) {
5699 opCode = spv::OpGroupNonUniformFMax;
5700 } else if (isUnsigned) {
5701 opCode = spv::OpGroupNonUniformUMax;
5702 } else {
5703 opCode = spv::OpGroupNonUniformSMax;
5704 }
5705 break;
5706 case glslang::EOpSubgroupAnd:
5707 case glslang::EOpSubgroupInclusiveAnd:
5708 case glslang::EOpSubgroupExclusiveAnd:
5709 case glslang::EOpSubgroupClusteredAnd:
5710 if (isBool) {
5711 opCode = spv::OpGroupNonUniformLogicalAnd;
5712 } else {
5713 opCode = spv::OpGroupNonUniformBitwiseAnd;
5714 }
5715 break;
5716 case glslang::EOpSubgroupOr:
5717 case glslang::EOpSubgroupInclusiveOr:
5718 case glslang::EOpSubgroupExclusiveOr:
5719 case glslang::EOpSubgroupClusteredOr:
5720 if (isBool) {
5721 opCode = spv::OpGroupNonUniformLogicalOr;
5722 } else {
5723 opCode = spv::OpGroupNonUniformBitwiseOr;
5724 }
5725 break;
5726 case glslang::EOpSubgroupXor:
5727 case glslang::EOpSubgroupInclusiveXor:
5728 case glslang::EOpSubgroupExclusiveXor:
5729 case glslang::EOpSubgroupClusteredXor:
5730 if (isBool) {
5731 opCode = spv::OpGroupNonUniformLogicalXor;
5732 } else {
5733 opCode = spv::OpGroupNonUniformBitwiseXor;
5734 }
5735 break;
5736 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
5737 case glslang::EOpSubgroupQuadSwapHorizontal:
5738 case glslang::EOpSubgroupQuadSwapVertical:
5739 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
5740 default: assert(0 && "Unhandled subgroup operation!");
5741 }
5742
5743 std::vector<spv::Id> spvGroupOperands;
5744
5745 // Every operation begins with the Execution Scope operand.
5746 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
5747
5748 // Next, for all operations that use a Group Operation, push that as an operand.
5749 switch (op) {
5750 default: break;
5751 case glslang::EOpSubgroupBallotBitCount:
5752 case glslang::EOpSubgroupAdd:
5753 case glslang::EOpSubgroupMul:
5754 case glslang::EOpSubgroupMin:
5755 case glslang::EOpSubgroupMax:
5756 case glslang::EOpSubgroupAnd:
5757 case glslang::EOpSubgroupOr:
5758 case glslang::EOpSubgroupXor:
5759 spvGroupOperands.push_back(spv::GroupOperationReduce);
5760 break;
5761 case glslang::EOpSubgroupBallotInclusiveBitCount:
5762 case glslang::EOpSubgroupInclusiveAdd:
5763 case glslang::EOpSubgroupInclusiveMul:
5764 case glslang::EOpSubgroupInclusiveMin:
5765 case glslang::EOpSubgroupInclusiveMax:
5766 case glslang::EOpSubgroupInclusiveAnd:
5767 case glslang::EOpSubgroupInclusiveOr:
5768 case glslang::EOpSubgroupInclusiveXor:
5769 spvGroupOperands.push_back(spv::GroupOperationInclusiveScan);
5770 break;
5771 case glslang::EOpSubgroupBallotExclusiveBitCount:
5772 case glslang::EOpSubgroupExclusiveAdd:
5773 case glslang::EOpSubgroupExclusiveMul:
5774 case glslang::EOpSubgroupExclusiveMin:
5775 case glslang::EOpSubgroupExclusiveMax:
5776 case glslang::EOpSubgroupExclusiveAnd:
5777 case glslang::EOpSubgroupExclusiveOr:
5778 case glslang::EOpSubgroupExclusiveXor:
5779 spvGroupOperands.push_back(spv::GroupOperationExclusiveScan);
5780 break;
5781 case glslang::EOpSubgroupClusteredAdd:
5782 case glslang::EOpSubgroupClusteredMul:
5783 case glslang::EOpSubgroupClusteredMin:
5784 case glslang::EOpSubgroupClusteredMax:
5785 case glslang::EOpSubgroupClusteredAnd:
5786 case glslang::EOpSubgroupClusteredOr:
5787 case glslang::EOpSubgroupClusteredXor:
5788 spvGroupOperands.push_back(spv::GroupOperationClusteredReduce);
5789 break;
5790 }
5791
5792 // Push back the operands next.
5793 for (auto opIt : operands) {
5794 spvGroupOperands.push_back(opIt);
5795 }
5796
5797 // Some opcodes have additional operands.
5798 switch (op) {
5799 default: break;
5800 case glslang::EOpSubgroupQuadSwapHorizontal: spvGroupOperands.push_back(builder.makeUintConstant(0)); break;
5801 case glslang::EOpSubgroupQuadSwapVertical: spvGroupOperands.push_back(builder.makeUintConstant(1)); break;
5802 case glslang::EOpSubgroupQuadSwapDiagonal: spvGroupOperands.push_back(builder.makeUintConstant(2)); break;
5803 }
5804
5805 return builder.createOp(opCode, typeId, spvGroupOperands);
5806}
5807
John Kessenich5e4b1242015-08-06 22:53:06 -06005808spv::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 -06005809{
John Kessenich66011cb2018-03-06 16:12:04 -07005810 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5811 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06005812
John Kessenich140f3df2015-06-26 16:58:36 -06005813 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005814 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005815 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005816 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005817 spv::Id typeId0 = 0;
5818 if (consumedOperands > 0)
5819 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005820 spv::Id typeId1 = 0;
5821 if (consumedOperands > 1)
5822 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005823 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005824
5825 switch (op) {
5826 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005827 if (isFloat)
5828 libCall = spv::GLSLstd450FMin;
5829 else if (isUnsigned)
5830 libCall = spv::GLSLstd450UMin;
5831 else
5832 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005833 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005834 break;
5835 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06005836 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06005837 break;
5838 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06005839 if (isFloat)
5840 libCall = spv::GLSLstd450FMax;
5841 else if (isUnsigned)
5842 libCall = spv::GLSLstd450UMax;
5843 else
5844 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005845 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005846 break;
5847 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005848 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005849 break;
5850 case glslang::EOpDot:
5851 opCode = spv::OpDot;
5852 break;
5853 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005854 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005855 break;
5856
5857 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005858 if (isFloat)
5859 libCall = spv::GLSLstd450FClamp;
5860 else if (isUnsigned)
5861 libCall = spv::GLSLstd450UClamp;
5862 else
5863 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005864 builder.promoteScalar(precision, operands.front(), operands[1]);
5865 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005866 break;
5867 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005868 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5869 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005870 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005871 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005872 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005873 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005874 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005875 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005876 break;
5877 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005878 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005879 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005880 break;
5881 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005882 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005883 builder.promoteScalar(precision, operands[0], operands[2]);
5884 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005885 break;
5886
5887 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005888 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005889 break;
5890 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005891 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005892 break;
5893 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005894 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005895 break;
5896 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005897 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005898 break;
5899 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005900 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005901 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005902 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005903 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005904 libCall = spv::GLSLstd450InterpolateAtSample;
5905 break;
5906 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005907 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005908 libCall = spv::GLSLstd450InterpolateAtOffset;
5909 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005910 case glslang::EOpAddCarry:
5911 opCode = spv::OpIAddCarry;
5912 typeId = builder.makeStructResultType(typeId0, typeId0);
5913 consumedOperands = 2;
5914 break;
5915 case glslang::EOpSubBorrow:
5916 opCode = spv::OpISubBorrow;
5917 typeId = builder.makeStructResultType(typeId0, typeId0);
5918 consumedOperands = 2;
5919 break;
5920 case glslang::EOpUMulExtended:
5921 opCode = spv::OpUMulExtended;
5922 typeId = builder.makeStructResultType(typeId0, typeId0);
5923 consumedOperands = 2;
5924 break;
5925 case glslang::EOpIMulExtended:
5926 opCode = spv::OpSMulExtended;
5927 typeId = builder.makeStructResultType(typeId0, typeId0);
5928 consumedOperands = 2;
5929 break;
5930 case glslang::EOpBitfieldExtract:
5931 if (isUnsigned)
5932 opCode = spv::OpBitFieldUExtract;
5933 else
5934 opCode = spv::OpBitFieldSExtract;
5935 break;
5936 case glslang::EOpBitfieldInsert:
5937 opCode = spv::OpBitFieldInsert;
5938 break;
5939
5940 case glslang::EOpFma:
5941 libCall = spv::GLSLstd450Fma;
5942 break;
5943 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005944 {
5945 libCall = spv::GLSLstd450FrexpStruct;
5946 assert(builder.isPointerType(typeId1));
5947 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08005948 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08005949 if (builder.getNumComponents(operands[0]) == 1)
5950 frexpIntType = builder.makeIntegerType(width, true);
5951 else
5952 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5953 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5954 consumedOperands = 1;
5955 }
John Kessenich55e7d112015-11-15 21:33:39 -07005956 break;
5957 case glslang::EOpLdexp:
5958 libCall = spv::GLSLstd450Ldexp;
5959 break;
5960
Rex Xu574ab042016-04-14 16:53:07 +08005961 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005962 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005963
John Kessenich66011cb2018-03-06 16:12:04 -07005964 case glslang::EOpSubgroupBroadcast:
5965 case glslang::EOpSubgroupBallotBitExtract:
5966 case glslang::EOpSubgroupShuffle:
5967 case glslang::EOpSubgroupShuffleXor:
5968 case glslang::EOpSubgroupShuffleUp:
5969 case glslang::EOpSubgroupShuffleDown:
5970 case glslang::EOpSubgroupClusteredAdd:
5971 case glslang::EOpSubgroupClusteredMul:
5972 case glslang::EOpSubgroupClusteredMin:
5973 case glslang::EOpSubgroupClusteredMax:
5974 case glslang::EOpSubgroupClusteredAnd:
5975 case glslang::EOpSubgroupClusteredOr:
5976 case glslang::EOpSubgroupClusteredXor:
5977 case glslang::EOpSubgroupQuadBroadcast:
5978 return createSubgroupOperation(op, typeId, operands, typeProxy);
5979
Rex Xu9d93a232016-05-05 12:30:44 +08005980#ifdef AMD_EXTENSIONS
5981 case glslang::EOpSwizzleInvocations:
5982 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5983 libCall = spv::SwizzleInvocationsAMD;
5984 break;
5985 case glslang::EOpSwizzleInvocationsMasked:
5986 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5987 libCall = spv::SwizzleInvocationsMaskedAMD;
5988 break;
5989 case glslang::EOpWriteInvocation:
5990 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5991 libCall = spv::WriteInvocationAMD;
5992 break;
5993
5994 case glslang::EOpMin3:
5995 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5996 if (isFloat)
5997 libCall = spv::FMin3AMD;
5998 else {
5999 if (isUnsigned)
6000 libCall = spv::UMin3AMD;
6001 else
6002 libCall = spv::SMin3AMD;
6003 }
6004 break;
6005 case glslang::EOpMax3:
6006 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6007 if (isFloat)
6008 libCall = spv::FMax3AMD;
6009 else {
6010 if (isUnsigned)
6011 libCall = spv::UMax3AMD;
6012 else
6013 libCall = spv::SMax3AMD;
6014 }
6015 break;
6016 case glslang::EOpMid3:
6017 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6018 if (isFloat)
6019 libCall = spv::FMid3AMD;
6020 else {
6021 if (isUnsigned)
6022 libCall = spv::UMid3AMD;
6023 else
6024 libCall = spv::SMid3AMD;
6025 }
6026 break;
6027
6028 case glslang::EOpInterpolateAtVertex:
6029 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
6030 libCall = spv::InterpolateAtVertexAMD;
6031 break;
6032#endif
6033
John Kessenich140f3df2015-06-26 16:58:36 -06006034 default:
6035 return 0;
6036 }
6037
6038 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07006039 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05006040 // Use an extended instruction from the standard library.
6041 // Construct the call arguments, without modifying the original operands vector.
6042 // We might need the remaining arguments, e.g. in the EOpFrexp case.
6043 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08006044 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07006045 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07006046 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06006047 case 0:
6048 // should all be handled by visitAggregate and createNoArgOperation
6049 assert(0);
6050 return 0;
6051 case 1:
6052 // should all be handled by createUnaryOperation
6053 assert(0);
6054 return 0;
6055 case 2:
6056 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
6057 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006058 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006059 // anything 3 or over doesn't have l-value operands, so all should be consumed
6060 assert(consumedOperands == operands.size());
6061 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06006062 break;
6063 }
6064 }
6065
John Kessenich55e7d112015-11-15 21:33:39 -07006066 // Decode the return types that were structures
6067 switch (op) {
6068 case glslang::EOpAddCarry:
6069 case glslang::EOpSubBorrow:
6070 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6071 id = builder.createCompositeExtract(id, typeId0, 0);
6072 break;
6073 case glslang::EOpUMulExtended:
6074 case glslang::EOpIMulExtended:
6075 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
6076 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6077 break;
6078 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006079 {
6080 assert(operands.size() == 2);
6081 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
6082 // "exp" is floating-point type (from HLSL intrinsic)
6083 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
6084 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
6085 builder.createStore(member1, operands[1]);
6086 } else
6087 // "exp" is integer type (from GLSL built-in function)
6088 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
6089 id = builder.createCompositeExtract(id, typeId0, 0);
6090 }
John Kessenich55e7d112015-11-15 21:33:39 -07006091 break;
6092 default:
6093 break;
6094 }
6095
John Kessenich32cfd492016-02-02 12:37:46 -07006096 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006097}
6098
Rex Xu9d93a232016-05-05 12:30:44 +08006099// Intrinsics with no arguments (or no return value, and no precision).
6100spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06006101{
6102 // TODO: get the barrier operands correct
6103
6104 switch (op) {
6105 case glslang::EOpEmitVertex:
6106 builder.createNoResultOp(spv::OpEmitVertex);
6107 return 0;
6108 case glslang::EOpEndPrimitive:
6109 builder.createNoResultOp(spv::OpEndPrimitive);
6110 return 0;
6111 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006112 if (glslangIntermediate->getStage() == EShLangTessControl) {
6113 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
6114 // TODO: prefer the following, when available:
6115 // builder.createControlBarrier(spv::ScopePatch, spv::ScopePatch,
6116 // spv::MemorySemanticsPatchMask |
6117 // spv::MemorySemanticsAcquireReleaseMask);
6118 } else {
6119 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6120 spv::MemorySemanticsWorkgroupMemoryMask |
6121 spv::MemorySemanticsAcquireReleaseMask);
6122 }
John Kessenich140f3df2015-06-26 16:58:36 -06006123 return 0;
6124 case glslang::EOpMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006125 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory |
6126 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006127 return 0;
6128 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich82979362017-12-11 04:02:24 -07006129 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask |
6130 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006131 return 0;
6132 case glslang::EOpMemoryBarrierBuffer:
John Kessenich82979362017-12-11 04:02:24 -07006133 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6134 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006135 return 0;
6136 case glslang::EOpMemoryBarrierImage:
John Kessenich82979362017-12-11 04:02:24 -07006137 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask |
6138 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006139 return 0;
6140 case glslang::EOpMemoryBarrierShared:
John Kessenich82979362017-12-11 04:02:24 -07006141 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask |
6142 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006143 return 0;
6144 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006145 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
6146 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006147 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06006148 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006149 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07006150 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07006151 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006152 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07006153 case glslang::EOpDeviceMemoryBarrier:
6154 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6155 spv::MemorySemanticsImageMemoryMask |
6156 spv::MemorySemanticsAcquireReleaseMask);
6157 return 0;
6158 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
6159 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6160 spv::MemorySemanticsImageMemoryMask |
6161 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006162 return 0;
6163 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07006164 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6165 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006166 return 0;
6167 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006168 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6169 spv::MemorySemanticsWorkgroupMemoryMask |
6170 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006171 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07006172 case glslang::EOpSubgroupBarrier:
6173 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6174 spv::MemorySemanticsAcquireReleaseMask);
6175 return spv::NoResult;
6176 case glslang::EOpSubgroupMemoryBarrier:
6177 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6178 spv::MemorySemanticsAcquireReleaseMask);
6179 return spv::NoResult;
6180 case glslang::EOpSubgroupMemoryBarrierBuffer:
6181 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
6182 spv::MemorySemanticsAcquireReleaseMask);
6183 return spv::NoResult;
6184 case glslang::EOpSubgroupMemoryBarrierImage:
6185 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
6186 spv::MemorySemanticsAcquireReleaseMask);
6187 return spv::NoResult;
6188 case glslang::EOpSubgroupMemoryBarrierShared:
6189 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6190 spv::MemorySemanticsAcquireReleaseMask);
6191 return spv::NoResult;
6192 case glslang::EOpSubgroupElect: {
6193 std::vector<spv::Id> operands;
6194 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
6195 }
Rex Xu9d93a232016-05-05 12:30:44 +08006196#ifdef AMD_EXTENSIONS
6197 case glslang::EOpTime:
6198 {
6199 std::vector<spv::Id> args; // Dummy arguments
6200 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
6201 return builder.setPrecision(id, precision);
6202 }
6203#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006204 default:
Lei Zhang17535f72016-05-04 15:55:59 -04006205 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06006206 return 0;
6207 }
6208}
6209
6210spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
6211{
John Kessenich2f273362015-07-18 22:34:27 -06006212 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06006213 spv::Id id;
6214 if (symbolValues.end() != iter) {
6215 id = iter->second;
6216 return id;
6217 }
6218
6219 // it was not found, create it
6220 id = createSpvVariable(symbol);
6221 symbolValues[symbol->getId()] = id;
6222
Rex Xuc884b4a2016-06-29 15:03:44 +08006223 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006224 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
6225 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
6226 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07006227 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07006228 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06006229 if (symbol->getQualifier().hasIndex())
6230 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
6231 if (symbol->getQualifier().hasComponent())
6232 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06006233 // atomic counters use this:
6234 if (symbol->getQualifier().hasOffset())
6235 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006236 }
6237
scygan2c864272016-05-18 18:09:17 +02006238 if (symbol->getQualifier().hasLocation())
6239 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07006240 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07006241 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07006242 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06006243 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07006244 }
John Kessenich140f3df2015-06-26 16:58:36 -06006245 if (symbol->getQualifier().hasSet())
6246 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07006247 else if (IsDescriptorResource(symbol->getType())) {
6248 // default to 0
6249 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
6250 }
John Kessenich140f3df2015-06-26 16:58:36 -06006251 if (symbol->getQualifier().hasBinding())
6252 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07006253 if (symbol->getQualifier().hasAttachment())
6254 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06006255 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07006256 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06006257 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06006258 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07006259 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06006260 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07006261 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
6262 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
6263 builder.addDecoration(id, spv::DecorationXfbStride, stride);
6264 }
6265 if (symbol->getQualifier().hasXfbOffset())
6266 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006267 }
6268
Rex Xu1da878f2016-02-21 20:59:01 +08006269 if (symbol->getType().isImage()) {
6270 std::vector<spv::Decoration> memory;
6271 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
6272 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07006273 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08006274 }
6275
John Kessenich140f3df2015-06-26 16:58:36 -06006276 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06006277 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06006278 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07006279 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06006280
John Kessenichecba76f2017-01-06 00:34:48 -07006281#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08006282 if (builtIn == spv::BuiltInSampleMask) {
6283 spv::Decoration decoration;
6284 // GL_NV_sample_mask_override_coverage extension
6285 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08006286 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08006287 else
6288 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07006289 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08006290 if (decoration != spv::DecorationMax) {
6291 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
6292 }
6293 }
chaoc771d89f2017-01-13 01:10:53 -08006294 else if (builtIn == spv::BuiltInLayer) {
6295 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06006296 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006297 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08006298 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
6299 builder.addExtension(spv::E_SPV_NV_viewport_array2);
6300 }
John Kessenichb41bff62017-08-11 13:07:17 -06006301 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006302 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
6303 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08006304 builder.addCapability(spv::CapabilityShaderStereoViewNV);
6305 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
6306 }
6307 }
6308
chaoc6e5acae2016-12-20 13:28:52 -08006309 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006310 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08006311 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08006312 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
6313 }
chaoc0ad6a4e2016-12-19 16:29:34 -08006314#endif
6315
John Kessenich5d610ee2018-03-07 18:05:55 -07006316 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
6317 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
6318 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
6319 symbol->getType().getQualifier().semanticName);
6320 }
6321
John Kessenich140f3df2015-06-26 16:58:36 -06006322 return id;
6323}
6324
John Kessenich55e7d112015-11-15 21:33:39 -07006325// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07006326// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07006327//
6328// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
6329//
6330// Recursively walk the nodes. The nodes form a tree whose leaves are
6331// regular constants, which themselves are trees that createSpvConstant()
6332// recursively walks. So, this function walks the "top" of the tree:
6333// - emit specialization constant-building instructions for specConstant
6334// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04006335spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07006336{
John Kessenich7cc0e282016-03-20 00:46:02 -06006337 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07006338
qining4f4bb812016-04-03 23:55:17 -04006339 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07006340 if (! node.getQualifier().specConstant) {
6341 // hand off to the non-spec-constant path
6342 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
6343 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04006344 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07006345 nextConst, false);
6346 }
6347
6348 // We now know we have a specialization constant to build
6349
John Kessenichd94c0032016-05-30 19:29:40 -06006350 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04006351 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
6352 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
6353 std::vector<spv::Id> dimConstId;
6354 for (int dim = 0; dim < 3; ++dim) {
6355 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
6356 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07006357 if (specConst) {
6358 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
6359 glslangIntermediate->getLocalSizeSpecId(dim));
6360 }
qining4f4bb812016-04-03 23:55:17 -04006361 }
6362 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
6363 }
6364
6365 // An AST node labelled as specialization constant should be a symbol node.
6366 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
6367 if (auto* sn = node.getAsSymbolNode()) {
6368 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04006369 // Traverse the constant constructor sub tree like generating normal run-time instructions.
6370 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
6371 // will set the builder into spec constant op instruction generating mode.
6372 sub_tree->traverse(this);
6373 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04006374 } else if (auto* const_union_array = &sn->getConstArray()){
6375 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01006376 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
6377 builder.addName(id, sn->getName().c_str());
6378 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07006379 }
6380 }
qining4f4bb812016-04-03 23:55:17 -04006381
6382 // Neither a front-end constant node, nor a specialization constant node with constant union array or
6383 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04006384 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04006385 exit(1);
6386 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07006387}
6388
John Kessenich140f3df2015-06-26 16:58:36 -06006389// Use 'consts' as the flattened glslang source of scalar constants to recursively
6390// build the aggregate SPIR-V constant.
6391//
6392// If there are not enough elements present in 'consts', 0 will be substituted;
6393// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
6394//
qining08408382016-03-21 09:51:37 -04006395spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06006396{
6397 // vector of constants for SPIR-V
6398 std::vector<spv::Id> spvConsts;
6399
6400 // Type is used for struct and array constants
6401 spv::Id typeId = convertGlslangToSpvType(glslangType);
6402
6403 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006404 glslang::TType elementType(glslangType, 0);
6405 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04006406 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006407 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006408 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06006409 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04006410 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006411 } else if (glslangType.getStruct()) {
6412 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
6413 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04006414 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06006415 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06006416 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
6417 bool zero = nextConst >= consts.size();
6418 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006419 case glslang::EbtInt8:
6420 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
6421 break;
6422 case glslang::EbtUint8:
6423 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
6424 break;
6425 case glslang::EbtInt16:
6426 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
6427 break;
6428 case glslang::EbtUint16:
6429 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
6430 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006431 case glslang::EbtInt:
6432 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
6433 break;
6434 case glslang::EbtUint:
6435 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
6436 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006437 case glslang::EbtInt64:
6438 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
6439 break;
6440 case glslang::EbtUint64:
6441 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
6442 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006443 case glslang::EbtFloat:
6444 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
6445 break;
6446 case glslang::EbtDouble:
6447 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
6448 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006449 case glslang::EbtFloat16:
6450 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
6451 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006452 case glslang::EbtBool:
6453 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
6454 break;
6455 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006456 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06006457 break;
6458 }
6459 ++nextConst;
6460 }
6461 } else {
6462 // we have a non-aggregate (scalar) constant
6463 bool zero = nextConst >= consts.size();
6464 spv::Id scalar = 0;
6465 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006466 case glslang::EbtInt8:
6467 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
6468 break;
6469 case glslang::EbtUint8:
6470 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
6471 break;
6472 case glslang::EbtInt16:
6473 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
6474 break;
6475 case glslang::EbtUint16:
6476 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
6477 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006478 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07006479 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006480 break;
6481 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07006482 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006483 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006484 case glslang::EbtInt64:
6485 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
6486 break;
6487 case glslang::EbtUint64:
6488 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
6489 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006490 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07006491 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006492 break;
6493 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07006494 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006495 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006496 case glslang::EbtFloat16:
6497 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
6498 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006499 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07006500 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006501 break;
6502 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006503 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06006504 break;
6505 }
6506 ++nextConst;
6507 return scalar;
6508 }
6509
6510 return builder.makeCompositeConstant(typeId, spvConsts);
6511}
6512
John Kessenich7c1aa102015-10-15 13:29:11 -06006513// Return true if the node is a constant or symbol whose reading has no
6514// non-trivial observable cost or effect.
6515bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
6516{
6517 // don't know what this is
6518 if (node == nullptr)
6519 return false;
6520
6521 // a constant is safe
6522 if (node->getAsConstantUnion() != nullptr)
6523 return true;
6524
6525 // not a symbol means non-trivial
6526 if (node->getAsSymbolNode() == nullptr)
6527 return false;
6528
6529 // a symbol, depends on what's being read
6530 switch (node->getType().getQualifier().storage) {
6531 case glslang::EvqTemporary:
6532 case glslang::EvqGlobal:
6533 case glslang::EvqIn:
6534 case glslang::EvqInOut:
6535 case glslang::EvqConst:
6536 case glslang::EvqConstReadOnly:
6537 case glslang::EvqUniform:
6538 return true;
6539 default:
6540 return false;
6541 }
qining25262b32016-05-06 17:25:16 -04006542}
John Kessenich7c1aa102015-10-15 13:29:11 -06006543
6544// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06006545// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06006546// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06006547// Return true if trivial.
6548bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
6549{
6550 if (node == nullptr)
6551 return false;
6552
John Kessenich84cc15f2017-05-24 16:44:47 -06006553 // count non scalars as trivial, as well as anything coming from HLSL
6554 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06006555 return true;
6556
John Kessenich7c1aa102015-10-15 13:29:11 -06006557 // symbols and constants are trivial
6558 if (isTrivialLeaf(node))
6559 return true;
6560
6561 // otherwise, it needs to be a simple operation or one or two leaf nodes
6562
6563 // not a simple operation
6564 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
6565 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
6566 if (binaryNode == nullptr && unaryNode == nullptr)
6567 return false;
6568
6569 // not on leaf nodes
6570 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
6571 return false;
6572
6573 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
6574 return false;
6575 }
6576
6577 switch (node->getAsOperator()->getOp()) {
6578 case glslang::EOpLogicalNot:
6579 case glslang::EOpConvIntToBool:
6580 case glslang::EOpConvUintToBool:
6581 case glslang::EOpConvFloatToBool:
6582 case glslang::EOpConvDoubleToBool:
6583 case glslang::EOpEqual:
6584 case glslang::EOpNotEqual:
6585 case glslang::EOpLessThan:
6586 case glslang::EOpGreaterThan:
6587 case glslang::EOpLessThanEqual:
6588 case glslang::EOpGreaterThanEqual:
6589 case glslang::EOpIndexDirect:
6590 case glslang::EOpIndexDirectStruct:
6591 case glslang::EOpLogicalXor:
6592 case glslang::EOpAny:
6593 case glslang::EOpAll:
6594 return true;
6595 default:
6596 return false;
6597 }
6598}
6599
6600// Emit short-circuiting code, where 'right' is never evaluated unless
6601// the left side is true (for &&) or false (for ||).
6602spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
6603{
6604 spv::Id boolTypeId = builder.makeBoolType();
6605
6606 // emit left operand
6607 builder.clearAccessChain();
6608 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006609 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006610
6611 // Operands to accumulate OpPhi operands
6612 std::vector<spv::Id> phiOperands;
6613 // accumulate left operand's phi information
6614 phiOperands.push_back(leftId);
6615 phiOperands.push_back(builder.getBuildPoint()->getId());
6616
6617 // Make the two kinds of operation symmetric with a "!"
6618 // || => emit "if (! left) result = right"
6619 // && => emit "if ( left) result = right"
6620 //
6621 // TODO: this runtime "not" for || could be avoided by adding functionality
6622 // to 'builder' to have an "else" without an "then"
6623 if (op == glslang::EOpLogicalOr)
6624 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
6625
6626 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08006627 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06006628
6629 // emit right operand as the "then" part of the "if"
6630 builder.clearAccessChain();
6631 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006632 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006633
6634 // accumulate left operand's phi information
6635 phiOperands.push_back(rightId);
6636 phiOperands.push_back(builder.getBuildPoint()->getId());
6637
6638 // finish the "if"
6639 ifBuilder.makeEndIf();
6640
6641 // phi together the two results
6642 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
6643}
6644
Frank Henigman541f7bb2018-01-16 00:18:26 -05006645#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08006646// Return type Id of the imported set of extended instructions corresponds to the name.
6647// Import this set if it has not been imported yet.
6648spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
6649{
6650 if (extBuiltinMap.find(name) != extBuiltinMap.end())
6651 return extBuiltinMap[name];
6652 else {
Rex Xu51596642016-09-21 18:56:12 +08006653 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08006654 spv::Id extBuiltins = builder.import(name);
6655 extBuiltinMap[name] = extBuiltins;
6656 return extBuiltins;
6657 }
6658}
Frank Henigman541f7bb2018-01-16 00:18:26 -05006659#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006660
John Kessenich140f3df2015-06-26 16:58:36 -06006661}; // end anonymous namespace
6662
6663namespace glslang {
6664
John Kessenich68d78fd2015-07-12 19:28:10 -06006665void GetSpirvVersion(std::string& version)
6666{
John Kessenich9e55f632015-07-15 10:03:39 -06006667 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06006668 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07006669 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06006670 version = buf;
6671}
6672
John Kessenicha372a3e2017-11-02 22:32:14 -06006673// For low-order part of the generator's magic number. Bump up
6674// when there is a change in the style (e.g., if SSA form changes,
6675// or a different instruction sequence to do something gets used).
6676int GetSpirvGeneratorVersion()
6677{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07006678 // return 1; // start
6679 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07006680 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07006681 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07006682 // return 5; // make OpArrayLength result type be an int with signedness of 0
6683 return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
6684 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenicha372a3e2017-11-02 22:32:14 -06006685}
6686
John Kessenich140f3df2015-06-26 16:58:36 -06006687// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006688void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06006689{
6690 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06006691 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006692 if (out.fail())
6693 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06006694 for (int i = 0; i < (int)spirv.size(); ++i) {
6695 unsigned int word = spirv[i];
6696 out.write((const char*)&word, 4);
6697 }
6698 out.close();
6699}
6700
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006701// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08006702void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006703{
6704 std::ofstream out;
6705 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006706 if (out.fail())
6707 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07006708 out << "\t// " <<
6709 glslang::GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
6710 std::endl;
Flavio15017db2017-02-15 14:29:33 -08006711 if (varName != nullptr) {
6712 out << "\t #pragma once" << std::endl;
6713 out << "const uint32_t " << varName << "[] = {" << std::endl;
6714 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006715 const int WORDS_PER_LINE = 8;
6716 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
6717 out << "\t";
6718 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
6719 const unsigned int word = spirv[i + j];
6720 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
6721 if (i + j + 1 < (int)spirv.size()) {
6722 out << ",";
6723 }
6724 }
6725 out << std::endl;
6726 }
Flavio15017db2017-02-15 14:29:33 -08006727 if (varName != nullptr) {
6728 out << "};";
6729 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006730 out.close();
6731}
6732
GregFcd1f1692017-09-21 18:40:22 -06006733#ifdef ENABLE_OPT
6734void errHandler(const std::string& str) {
6735 std::cerr << str << std::endl;
6736}
6737#endif
6738
John Kessenich140f3df2015-06-26 16:58:36 -06006739//
6740// Set up the glslang traversal
6741//
John Kessenich121853f2017-05-31 17:11:16 -06006742void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06006743{
Lei Zhang17535f72016-05-04 15:55:59 -04006744 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06006745 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04006746}
6747
John Kessenich121853f2017-05-31 17:11:16 -06006748void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
6749 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04006750{
John Kessenich140f3df2015-06-26 16:58:36 -06006751 TIntermNode* root = intermediate.getTreeRoot();
6752
6753 if (root == 0)
6754 return;
6755
John Kessenich121853f2017-05-31 17:11:16 -06006756 glslang::SpvOptions defaultOptions;
6757 if (options == nullptr)
6758 options = &defaultOptions;
6759
John Kessenich140f3df2015-06-26 16:58:36 -06006760 glslang::GetThreadPoolAllocator().push();
6761
John Kessenich2b5ea9f2018-01-31 18:35:56 -07006762 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06006763 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07006764 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06006765 it.dumpSpv(spirv);
6766
GregFcd1f1692017-09-21 18:40:22 -06006767#ifdef ENABLE_OPT
6768 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
6769 // eg. forward and remove memory writes of opaque types.
6770 if ((intermediate.getSource() == EShSourceHlsl ||
6771 options->optimizeSize) &&
6772 !options->disableOptimizer) {
6773 spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
6774
6775 spvtools::Optimizer optimizer(target_env);
6776 optimizer.SetMessageConsumer([](spv_message_level_t level,
6777 const char* source,
6778 const spv_position_t& position,
6779 const char* message) {
6780 std::cerr << StringifyMessage(level, source, position, message)
6781 << std::endl;
6782 });
6783
GregFeecb8742018-03-26 12:11:55 -06006784 optimizer.RegisterPass(CreateMergeReturnPass());
GregFcd1f1692017-09-21 18:40:22 -06006785 optimizer.RegisterPass(CreateInlineExhaustivePass());
GregFe0639282017-12-21 10:55:57 -07006786 optimizer.RegisterPass(CreateEliminateDeadFunctionsPass());
6787 optimizer.RegisterPass(CreateScalarReplacementPass());
GregFcd1f1692017-09-21 18:40:22 -06006788 optimizer.RegisterPass(CreateLocalAccessChainConvertPass());
6789 optimizer.RegisterPass(CreateLocalSingleBlockLoadStoreElimPass());
6790 optimizer.RegisterPass(CreateLocalSingleStoreElimPass());
GregFeecb8742018-03-26 12:11:55 -06006791 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFcd1f1692017-09-21 18:40:22 -06006792 optimizer.RegisterPass(CreateInsertExtractElimPass());
GregF8a4848f2018-02-07 16:04:42 -07006793 optimizer.RegisterPass(CreateDeadInsertElimPass());
GregFcd1f1692017-09-21 18:40:22 -06006794 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFeecb8742018-03-26 12:11:55 -06006795 optimizer.RegisterPass(CreateCCPPass());
6796 optimizer.RegisterPass(CreateSimplificationPass());
GregFcd1f1692017-09-21 18:40:22 -06006797 optimizer.RegisterPass(CreateDeadBranchElimPass());
GregFcc80d802017-10-23 16:48:42 -06006798 optimizer.RegisterPass(CreateCFGCleanupPass());
GregFcd1f1692017-09-21 18:40:22 -06006799 optimizer.RegisterPass(CreateBlockMergePass());
6800 optimizer.RegisterPass(CreateLocalMultiStoreElimPass());
GregFeecb8742018-03-26 12:11:55 -06006801 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFcd1f1692017-09-21 18:40:22 -06006802 optimizer.RegisterPass(CreateInsertExtractElimPass());
GregF8a4848f2018-02-07 16:04:42 -07006803 optimizer.RegisterPass(CreateDeadInsertElimPass());
6804 if (options->optimizeSize) {
6805 optimizer.RegisterPass(CreateRedundancyEliminationPass());
6806 // TODO(greg-lunarg): Add this when AMD driver issues are resolved
6807 // optimizer.RegisterPass(CreateCommonUniformElimPass());
6808 }
GregFcd1f1692017-09-21 18:40:22 -06006809 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFcd1f1692017-09-21 18:40:22 -06006810
6811 if (!optimizer.Run(spirv.data(), spirv.size(), &spirv))
6812 return;
6813
6814 // Remove dead module-level objects: functions, types, vars
6815 // TODO(greg-lunarg): Switch to spirv-opt versions when available
6816 spv::spirvbin_t Remapper(0);
6817 Remapper.registerErrorHandler(errHandler);
6818 Remapper.remap(spirv, spv::spirvbin_t::DCE_ALL);
6819 }
6820#endif
6821
John Kessenich140f3df2015-06-26 16:58:36 -06006822 glslang::GetThreadPoolAllocator().pop();
6823}
6824
6825}; // end namespace glslang