blob: 88569f5f7512c91b0606fa31027cb63627f0fd4b [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
3// Copyright (C) 2015-2016 Google, Inc.
John Kessenich66011cb2018-03-06 16:12:04 -07004// Copyright (C) 2017 ARM Limited.
John Kessenich140f3df2015-06-26 16:58:36 -06005//
John Kessenich927608b2017-01-06 12:34:14 -07006// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06007//
John Kessenich927608b2017-01-06 12:34:14 -07008// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions
10// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060011//
12// Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//
15// Redistributions in binary form must reproduce the above
16// copyright notice, this list of conditions and the following
17// disclaimer in the documentation and/or other materials provided
18// with the distribution.
19//
20// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21// contributors may be used to endorse or promote products derived
22// from this software without specific prior written permission.
23//
John Kessenich927608b2017-01-06 12:34:14 -070024// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060036
37//
John Kessenich140f3df2015-06-26 16:58:36 -060038// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080046 #include "GLSL.std.450.h"
47 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070048 #include "GLSL.ext.EXT.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080050 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080051#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080052#ifdef NV_EXTENSIONS
53 #include "GLSL.ext.NV.h"
54#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060055}
John Kessenich140f3df2015-06-26 16:58:36 -060056
GregFfb03a552018-03-29 11:49:14 -060057#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -060058 #include "spirv-tools/optimizer.hpp"
GregFcd1f1692017-09-21 18:40:22 -060059#endif
60
GregFfb03a552018-03-29 11:49:14 -060061#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -060062using namespace spvtools;
63#endif
64
John Kessenich140f3df2015-06-26 16:58:36 -060065// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020066#include "../glslang/MachineIndependent/localintermediate.h"
67#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060068#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050069#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060070
John Kessenich140f3df2015-06-26 16:58:36 -060071#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050072#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040073#include <list>
74#include <map>
75#include <stack>
76#include <string>
77#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060078
79namespace {
80
qining4c912612016-04-01 10:35:16 -040081namespace {
82class SpecConstantOpModeGuard {
83public:
84 SpecConstantOpModeGuard(spv::Builder* builder)
85 : builder_(builder) {
86 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040087 }
88 ~SpecConstantOpModeGuard() {
89 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
90 : builder_->setToNormalCodeGenMode();
91 }
qining40887662016-04-03 22:20:42 -040092 void turnOnSpecConstantOpMode() {
93 builder_->setToSpecConstCodeGenMode();
94 }
qining4c912612016-04-01 10:35:16 -040095
96private:
97 spv::Builder* builder_;
98 bool previous_flag_;
99};
John Kessenichead86222018-03-28 18:01:20 -0600100
101struct OpDecorations {
102 spv::Decoration precision;
103 spv::Decoration noContraction;
John Kessenich5611c6d2018-04-05 11:25:02 -0600104 spv::Decoration nonUniform;
John Kessenichead86222018-03-28 18:01:20 -0600105};
106
107} // namespace
qining4c912612016-04-01 10:35:16 -0400108
John Kessenich140f3df2015-06-26 16:58:36 -0600109//
110// The main holder of information for translating glslang to SPIR-V.
111//
112// Derives from the AST walking base class.
113//
114class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
115public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700116 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
117 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700118 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600119
120 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
121 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
122 void visitConstantUnion(glslang::TIntermConstantUnion*);
123 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
124 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
125 void visitSymbol(glslang::TIntermSymbol* symbol);
126 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
127 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
128 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
129
John Kessenichfca82622016-11-26 13:23:20 -0700130 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700131 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600132
133protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700134 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
135 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
136
Rex Xu17ff3432016-10-14 17:41:45 +0800137 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800138 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600139 spv::Decoration TranslateNonUniformDecoration(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 Kessenich5611c6d2018-04-05 11:25:02 -0600146 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich140f3df2015-06-26 16:58:36 -0600147 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
148 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600149 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
150 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
151 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600152 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kessenichead86222018-03-28 18:01:20 -0600153 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
154 bool lastBufferBlockMember);
John Kessenich0e737842017-03-24 18:38:16 -0600155 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600156 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
157 glslang::TLayoutPacking, const glslang::TQualifier&);
158 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
159 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700160 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700161 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800162 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600163 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700164 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700165 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
166 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700167 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
168 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100169 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600170
John Kessenich6fccb3c2016-09-19 16:01:41 -0600171 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600172 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600173 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600174 void makeFunctions(const glslang::TIntermSequence&);
175 void makeGlobalInitializers(const glslang::TIntermSequence&);
176 void visitFunctions(const glslang::TIntermSequence&);
177 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800178 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600179 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
180 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600181 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
182
John Kessenichead86222018-03-28 18:01:20 -0600183 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
184 glslang::TBasicType typeProxy, bool reduceComparison = true);
185 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
186 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
187 glslang::TBasicType typeProxy);
188 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
189 glslang::TBasicType typeProxy);
190 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
191 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600192 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600193 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800194 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 +0800195 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800196 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700197 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600198 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 +0800199 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600200 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
qining08408382016-03-21 09:51:37 -0400201 spv::Id createSpvConstant(const glslang::TIntermTyped&);
202 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600203 bool isTrivialLeaf(const glslang::TIntermTyped* node);
204 bool isTrivial(const glslang::TIntermTyped* node);
205 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500206#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800207 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500208#endif
John Kessenich66011cb2018-03-06 16:12:04 -0700209 void addPre13Extension(const char* ext)
210 {
211 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
212 builder.addExtension(ext);
213 }
John Kessenich140f3df2015-06-26 16:58:36 -0600214
John Kessenich121853f2017-05-31 17:11:16 -0600215 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600216 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600217 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700218 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600219 int sequenceDepth;
220
Lei Zhang17535f72016-05-04 15:55:59 -0400221 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400222
John Kessenich140f3df2015-06-26 16:58:36 -0600223 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
224 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700225 bool inEntryPoint;
226 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700227 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 -0700228 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600229 const glslang::TIntermediate* glslangIntermediate;
230 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800231 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600232
John Kessenich2f273362015-07-18 22:34:27 -0600233 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600234 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600235 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700236 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700237 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
238 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600239 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700240 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
John Kessenich140f3df2015-06-26 16:58:36 -0600241};
242
243//
244// Helper functions for translating glslang representations to SPIR-V enumerants.
245//
246
247// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700248spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600249{
John Kessenich66e2faf2016-03-12 18:34:36 -0700250 switch (source) {
251 case glslang::EShSourceGlsl:
252 switch (profile) {
253 case ENoProfile:
254 case ECoreProfile:
255 case ECompatibilityProfile:
256 return spv::SourceLanguageGLSL;
257 case EEsProfile:
258 return spv::SourceLanguageESSL;
259 default:
260 return spv::SourceLanguageUnknown;
261 }
262 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600263 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600264 default:
265 return spv::SourceLanguageUnknown;
266 }
267}
268
269// Translate glslang language (stage) to SPIR-V execution model.
270spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
271{
272 switch (stage) {
273 case EShLangVertex: return spv::ExecutionModelVertex;
274 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
275 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
276 case EShLangGeometry: return spv::ExecutionModelGeometry;
277 case EShLangFragment: return spv::ExecutionModelFragment;
278 case EShLangCompute: return spv::ExecutionModelGLCompute;
279 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700280 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600281 return spv::ExecutionModelFragment;
282 }
283}
284
John Kessenich140f3df2015-06-26 16:58:36 -0600285// Translate glslang sampler type to SPIR-V dimensionality.
286spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
287{
288 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700289 case glslang::Esd1D: return spv::Dim1D;
290 case glslang::Esd2D: return spv::Dim2D;
291 case glslang::Esd3D: return spv::Dim3D;
292 case glslang::EsdCube: return spv::DimCube;
293 case glslang::EsdRect: return spv::DimRect;
294 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700295 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600296 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700297 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600298 return spv::Dim2D;
299 }
300}
301
John Kessenichf6640762016-08-01 19:44:00 -0600302// Translate glslang precision to SPIR-V precision decorations.
303spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600304{
John Kessenichf6640762016-08-01 19:44:00 -0600305 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700306 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600307 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600308 default:
309 return spv::NoPrecision;
310 }
311}
312
John Kessenichf6640762016-08-01 19:44:00 -0600313// Translate glslang type to SPIR-V precision decorations.
314spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
315{
316 return TranslatePrecisionDecoration(type.getQualifier().precision);
317}
318
John Kessenich140f3df2015-06-26 16:58:36 -0600319// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600320spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600321{
322 if (type.getBasicType() == glslang::EbtBlock) {
323 switch (type.getQualifier().storage) {
324 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600325 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600326 case glslang::EvqVaryingIn: return spv::DecorationBlock;
327 case glslang::EvqVaryingOut: return spv::DecorationBlock;
328 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700329 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600330 break;
331 }
332 }
333
John Kessenich4016e382016-07-15 11:53:56 -0600334 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600335}
336
Rex Xu1da878f2016-02-21 20:59:01 +0800337// Translate glslang type to SPIR-V memory decorations.
338void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
339{
340 if (qualifier.coherent)
341 memory.push_back(spv::DecorationCoherent);
John Kessenich14b85d32018-06-04 15:36:03 -0600342 if (qualifier.volatil) {
Rex Xu1da878f2016-02-21 20:59:01 +0800343 memory.push_back(spv::DecorationVolatile);
John Kessenich14b85d32018-06-04 15:36:03 -0600344 memory.push_back(spv::DecorationCoherent);
345 }
Rex Xu1da878f2016-02-21 20:59:01 +0800346 if (qualifier.restrict)
347 memory.push_back(spv::DecorationRestrict);
348 if (qualifier.readonly)
349 memory.push_back(spv::DecorationNonWritable);
350 if (qualifier.writeonly)
351 memory.push_back(spv::DecorationNonReadable);
352}
353
John Kessenich140f3df2015-06-26 16:58:36 -0600354// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700355spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600356{
357 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700358 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600359 case glslang::ElmRowMajor:
360 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700361 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600362 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700363 default:
364 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600365 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600366 }
367 } else {
368 switch (type.getBasicType()) {
369 default:
John Kessenich4016e382016-07-15 11:53:56 -0600370 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600371 break;
372 case glslang::EbtBlock:
373 switch (type.getQualifier().storage) {
374 case glslang::EvqUniform:
375 case glslang::EvqBuffer:
376 switch (type.getQualifier().layoutPacking) {
377 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600378 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
379 default:
John Kessenich4016e382016-07-15 11:53:56 -0600380 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600381 }
382 case glslang::EvqVaryingIn:
383 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700384 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600385 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600386 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700387 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600388 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600389 }
390 }
391 }
392}
393
394// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600395// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700396// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800397spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600398{
Rex Xubbceed72016-05-21 09:40:44 +0800399 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700400 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600401 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800402 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700403 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700404 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600405 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800406#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800407 else if (qualifier.explicitInterp) {
408 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800409 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800410 }
Rex Xu9d93a232016-05-05 12:30:44 +0800411#endif
Rex Xubbceed72016-05-21 09:40:44 +0800412 else
John Kessenich4016e382016-07-15 11:53:56 -0600413 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800414}
415
416// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600417// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800418// should be applied.
419spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
420{
421 if (qualifier.patch)
422 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700423 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600424 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700425 else if (qualifier.sample) {
426 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600427 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700428 } else
John Kessenich4016e382016-07-15 11:53:56 -0600429 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600430}
431
John Kessenich92187592016-02-01 13:45:25 -0700432// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700433spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600434{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700435 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600436 return spv::DecorationInvariant;
437 else
John Kessenich4016e382016-07-15 11:53:56 -0600438 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600439}
440
qining9220dbb2016-05-04 17:34:38 -0400441// If glslang type is noContraction, return SPIR-V NoContraction decoration.
442spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
443{
444 if (qualifier.noContraction)
445 return spv::DecorationNoContraction;
446 else
John Kessenich4016e382016-07-15 11:53:56 -0600447 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400448}
449
John Kessenich5611c6d2018-04-05 11:25:02 -0600450// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
451spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
452{
453 if (qualifier.isNonUniform()) {
454 builder.addExtension("SPV_EXT_descriptor_indexing");
455 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
456 return spv::DecorationNonUniformEXT;
457 } else
458 return spv::DecorationMax;
459}
460
David Netoa901ffe2016-06-08 14:11:40 +0100461// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
462// associated capabilities when required. For some built-in variables, a capability
463// is generated only when using the variable in an executable instruction, but not when
464// just declaring a struct member variable with it. This is true for PointSize,
465// ClipDistance, and CullDistance.
466spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600467{
468 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700469 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600470 // Defer adding the capability until the built-in is actually used.
471 if (! memberDeclaration) {
472 switch (glslangIntermediate->getStage()) {
473 case EShLangGeometry:
474 builder.addCapability(spv::CapabilityGeometryPointSize);
475 break;
476 case EShLangTessControl:
477 case EShLangTessEvaluation:
478 builder.addCapability(spv::CapabilityTessellationPointSize);
479 break;
480 default:
481 break;
482 }
John Kessenich92187592016-02-01 13:45:25 -0700483 }
484 return spv::BuiltInPointSize;
485
John Kessenichebb50532016-05-16 19:22:05 -0600486 // These *Distance capabilities logically belong here, but if the member is declared and
487 // then never used, consumers of SPIR-V prefer the capability not be declared.
488 // They are now generated when used, rather than here when declared.
489 // Potentially, the specification should be more clear what the minimum
490 // use needed is to trigger the capability.
491 //
John Kessenich92187592016-02-01 13:45:25 -0700492 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100493 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800494 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700495 return spv::BuiltInClipDistance;
496
497 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100498 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800499 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700500 return spv::BuiltInCullDistance;
501
502 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600503 builder.addCapability(spv::CapabilityMultiViewport);
504 if (glslangIntermediate->getStage() == EShLangVertex ||
505 glslangIntermediate->getStage() == EShLangTessControl ||
506 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800507
John Kessenichba6a3c22017-09-13 13:22:50 -0600508 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
509 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800510 }
John Kessenich92187592016-02-01 13:45:25 -0700511 return spv::BuiltInViewportIndex;
512
John Kessenich5e801132016-02-15 11:09:46 -0700513 case glslang::EbvSampleId:
514 builder.addCapability(spv::CapabilitySampleRateShading);
515 return spv::BuiltInSampleId;
516
517 case glslang::EbvSamplePosition:
518 builder.addCapability(spv::CapabilitySampleRateShading);
519 return spv::BuiltInSamplePosition;
520
521 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700522 return spv::BuiltInSampleMask;
523
John Kessenich78a45572016-07-08 14:05:15 -0600524 case glslang::EbvLayer:
John Kessenichba6a3c22017-09-13 13:22:50 -0600525 builder.addCapability(spv::CapabilityGeometry);
526 if (glslangIntermediate->getStage() == EShLangVertex ||
527 glslangIntermediate->getStage() == EShLangTessControl ||
528 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800529
John Kessenichba6a3c22017-09-13 13:22:50 -0600530 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
531 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800532 }
John Kessenich78a45572016-07-08 14:05:15 -0600533 return spv::BuiltInLayer;
534
John Kessenich140f3df2015-06-26 16:58:36 -0600535 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600536 case glslang::EbvVertexId: return spv::BuiltInVertexId;
537 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700538 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
539 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800540
John Kessenichda581a22015-10-14 14:10:30 -0600541 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700542 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800543 builder.addCapability(spv::CapabilityDrawParameters);
544 return spv::BuiltInBaseVertex;
545
John Kessenichda581a22015-10-14 14:10:30 -0600546 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700547 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800548 builder.addCapability(spv::CapabilityDrawParameters);
549 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200550
John Kessenichda581a22015-10-14 14:10:30 -0600551 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700552 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800553 builder.addCapability(spv::CapabilityDrawParameters);
554 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200555
556 case glslang::EbvPrimitiveId:
557 if (glslangIntermediate->getStage() == EShLangFragment)
558 builder.addCapability(spv::CapabilityGeometry);
559 return spv::BuiltInPrimitiveId;
560
Rex Xu37cdcee2017-06-29 17:46:34 +0800561 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800562 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
563 builder.addCapability(spv::CapabilityStencilExportEXT);
564 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800565
John Kessenich140f3df2015-06-26 16:58:36 -0600566 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600567 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
568 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
569 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
570 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
571 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
572 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
573 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600574 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
575 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
576 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
577 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
578 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
579 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
580 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
581 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800582
Rex Xu574ab042016-04-14 16:53:07 +0800583 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800584 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800585 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
586 return spv::BuiltInSubgroupSize;
587
Rex Xu574ab042016-04-14 16:53:07 +0800588 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800589 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800590 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
591 return spv::BuiltInSubgroupLocalInvocationId;
592
Rex Xu574ab042016-04-14 16:53:07 +0800593 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800594 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
595 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
596 return spv::BuiltInSubgroupEqMaskKHR;
597
Rex Xu574ab042016-04-14 16:53:07 +0800598 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800599 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
600 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
601 return spv::BuiltInSubgroupGeMaskKHR;
602
Rex Xu574ab042016-04-14 16:53:07 +0800603 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800604 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
605 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
606 return spv::BuiltInSubgroupGtMaskKHR;
607
Rex Xu574ab042016-04-14 16:53:07 +0800608 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800609 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
610 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
611 return spv::BuiltInSubgroupLeMaskKHR;
612
Rex Xu574ab042016-04-14 16:53:07 +0800613 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800614 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
615 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
616 return spv::BuiltInSubgroupLtMaskKHR;
617
John Kessenich66011cb2018-03-06 16:12:04 -0700618 case glslang::EbvNumSubgroups:
619 builder.addCapability(spv::CapabilityGroupNonUniform);
620 return spv::BuiltInNumSubgroups;
621
622 case glslang::EbvSubgroupID:
623 builder.addCapability(spv::CapabilityGroupNonUniform);
624 return spv::BuiltInSubgroupId;
625
626 case glslang::EbvSubgroupSize2:
627 builder.addCapability(spv::CapabilityGroupNonUniform);
628 return spv::BuiltInSubgroupSize;
629
630 case glslang::EbvSubgroupInvocation2:
631 builder.addCapability(spv::CapabilityGroupNonUniform);
632 return spv::BuiltInSubgroupLocalInvocationId;
633
634 case glslang::EbvSubgroupEqMask2:
635 builder.addCapability(spv::CapabilityGroupNonUniform);
636 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
637 return spv::BuiltInSubgroupEqMask;
638
639 case glslang::EbvSubgroupGeMask2:
640 builder.addCapability(spv::CapabilityGroupNonUniform);
641 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
642 return spv::BuiltInSubgroupGeMask;
643
644 case glslang::EbvSubgroupGtMask2:
645 builder.addCapability(spv::CapabilityGroupNonUniform);
646 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
647 return spv::BuiltInSubgroupGtMask;
648
649 case glslang::EbvSubgroupLeMask2:
650 builder.addCapability(spv::CapabilityGroupNonUniform);
651 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
652 return spv::BuiltInSubgroupLeMask;
653
654 case glslang::EbvSubgroupLtMask2:
655 builder.addCapability(spv::CapabilityGroupNonUniform);
656 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
657 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800658#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800659 case glslang::EbvBaryCoordNoPersp:
660 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
661 return spv::BuiltInBaryCoordNoPerspAMD;
662
663 case glslang::EbvBaryCoordNoPerspCentroid:
664 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
665 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
666
667 case glslang::EbvBaryCoordNoPerspSample:
668 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
669 return spv::BuiltInBaryCoordNoPerspSampleAMD;
670
671 case glslang::EbvBaryCoordSmooth:
672 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
673 return spv::BuiltInBaryCoordSmoothAMD;
674
675 case glslang::EbvBaryCoordSmoothCentroid:
676 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
677 return spv::BuiltInBaryCoordSmoothCentroidAMD;
678
679 case glslang::EbvBaryCoordSmoothSample:
680 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
681 return spv::BuiltInBaryCoordSmoothSampleAMD;
682
683 case glslang::EbvBaryCoordPullModel:
684 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
685 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800686#endif
chaoc771d89f2017-01-13 01:10:53 -0800687
John Kessenich6c8aaac2017-02-27 01:20:51 -0700688 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700689 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700690 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700691 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700692
693 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700694 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700695 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700696 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700697
chaoc771d89f2017-01-13 01:10:53 -0800698#ifdef NV_EXTENSIONS
699 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800700 if (!memberDeclaration) {
701 builder.addExtension(spv::E_SPV_NV_viewport_array2);
702 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
703 }
chaoc771d89f2017-01-13 01:10:53 -0800704 return spv::BuiltInViewportMaskNV;
705 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800706 if (!memberDeclaration) {
707 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
708 builder.addCapability(spv::CapabilityShaderStereoViewNV);
709 }
chaoc771d89f2017-01-13 01:10:53 -0800710 return spv::BuiltInSecondaryPositionNV;
711 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800712 if (!memberDeclaration) {
713 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
714 builder.addCapability(spv::CapabilityShaderStereoViewNV);
715 }
chaoc771d89f2017-01-13 01:10:53 -0800716 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800717 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800718 if (!memberDeclaration) {
719 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
720 builder.addCapability(spv::CapabilityPerViewAttributesNV);
721 }
chaocdf3956c2017-02-14 14:52:34 -0800722 return spv::BuiltInPositionPerViewNV;
723 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800724 if (!memberDeclaration) {
725 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
726 builder.addCapability(spv::CapabilityPerViewAttributesNV);
727 }
chaocdf3956c2017-02-14 14:52:34 -0800728 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700729 case glslang::EbvFragFullyCoveredNV:
730 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
731 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
732 return spv::BuiltInFullyCoveredEXT;
chaoc771d89f2017-01-13 01:10:53 -0800733#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800734 default:
735 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600736 }
737}
738
Rex Xufc618912015-09-09 16:42:49 +0800739// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700740spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800741{
742 assert(type.getBasicType() == glslang::EbtSampler);
743
John Kessenich5d0fa972016-02-15 11:57:00 -0700744 // Check for capabilities
745 switch (type.getQualifier().layoutFormat) {
746 case glslang::ElfRg32f:
747 case glslang::ElfRg16f:
748 case glslang::ElfR11fG11fB10f:
749 case glslang::ElfR16f:
750 case glslang::ElfRgba16:
751 case glslang::ElfRgb10A2:
752 case glslang::ElfRg16:
753 case glslang::ElfRg8:
754 case glslang::ElfR16:
755 case glslang::ElfR8:
756 case glslang::ElfRgba16Snorm:
757 case glslang::ElfRg16Snorm:
758 case glslang::ElfRg8Snorm:
759 case glslang::ElfR16Snorm:
760 case glslang::ElfR8Snorm:
761
762 case glslang::ElfRg32i:
763 case glslang::ElfRg16i:
764 case glslang::ElfRg8i:
765 case glslang::ElfR16i:
766 case glslang::ElfR8i:
767
768 case glslang::ElfRgb10a2ui:
769 case glslang::ElfRg32ui:
770 case glslang::ElfRg16ui:
771 case glslang::ElfRg8ui:
772 case glslang::ElfR16ui:
773 case glslang::ElfR8ui:
774 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
775 break;
776
777 default:
778 break;
779 }
780
781 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800782 switch (type.getQualifier().layoutFormat) {
783 case glslang::ElfNone: return spv::ImageFormatUnknown;
784 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
785 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
786 case glslang::ElfR32f: return spv::ImageFormatR32f;
787 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
788 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
789 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
790 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
791 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
792 case glslang::ElfR16f: return spv::ImageFormatR16f;
793 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
794 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
795 case glslang::ElfRg16: return spv::ImageFormatRg16;
796 case glslang::ElfRg8: return spv::ImageFormatRg8;
797 case glslang::ElfR16: return spv::ImageFormatR16;
798 case glslang::ElfR8: return spv::ImageFormatR8;
799 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
800 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
801 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
802 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
803 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
804 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
805 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
806 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
807 case glslang::ElfR32i: return spv::ImageFormatR32i;
808 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
809 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
810 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
811 case glslang::ElfR16i: return spv::ImageFormatR16i;
812 case glslang::ElfR8i: return spv::ImageFormatR8i;
813 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
814 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
815 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
816 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
817 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
818 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
819 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
820 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
821 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
822 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600823 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800824 }
825}
826
John Kesseniche18fd202018-01-30 11:01:39 -0700827spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +0800828{
John Kesseniche18fd202018-01-30 11:01:39 -0700829 if (selectionNode.getFlatten())
830 return spv::SelectionControlFlattenMask;
831 if (selectionNode.getDontFlatten())
832 return spv::SelectionControlDontFlattenMask;
833 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +0800834}
835
John Kesseniche18fd202018-01-30 11:01:39 -0700836spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -0600837{
John Kesseniche18fd202018-01-30 11:01:39 -0700838 if (switchNode.getFlatten())
839 return spv::SelectionControlFlattenMask;
840 if (switchNode.getDontFlatten())
841 return spv::SelectionControlDontFlattenMask;
842 return spv::SelectionControlMaskNone;
843}
844
John Kessenicha2858d92018-01-31 08:11:18 -0700845// return a non-0 dependency if the dependency argument must be set
846spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
847 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -0700848{
849 spv::LoopControlMask control = spv::LoopControlMaskNone;
850
851 if (loopNode.getDontUnroll())
852 control = control | spv::LoopControlDontUnrollMask;
853 if (loopNode.getUnroll())
854 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -0700855 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -0700856 control = control | spv::LoopControlDependencyInfiniteMask;
857 else if (loopNode.getLoopDependency() > 0) {
858 control = control | spv::LoopControlDependencyLengthMask;
859 dependencyLength = loopNode.getLoopDependency();
860 }
John Kesseniche18fd202018-01-30 11:01:39 -0700861
862 return control;
steve-lunargf1709e72017-05-02 20:14:50 -0600863}
864
John Kessenicha5c5fb62017-05-05 05:09:58 -0600865// Translate glslang type to SPIR-V storage class.
866spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
867{
868 if (type.getQualifier().isPipeInput())
869 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600870 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -0600871 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600872
873 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
874 type.getQualifier().storage == glslang::EvqUniform) {
875 if (type.getBasicType() == glslang::EbtAtomicUint)
876 return spv::StorageClassAtomicCounter;
877 if (type.containsOpaque())
878 return spv::StorageClassUniformConstant;
879 }
880
881 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -0700882 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -0600883 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600884 }
885
886 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600887 if (type.getQualifier().layoutPushConstant)
888 return spv::StorageClassPushConstant;
889 if (type.getBasicType() == glslang::EbtBlock)
890 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600891 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600892 }
John Kessenichbed4e4f2017-09-08 02:38:07 -0600893
894 switch (type.getQualifier().storage) {
895 case glslang::EvqShared: return spv::StorageClassWorkgroup;
896 case glslang::EvqGlobal: return spv::StorageClassPrivate;
897 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
898 case glslang::EvqTemporary: return spv::StorageClassFunction;
899 default:
900 assert(0);
901 break;
902 }
903
904 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600905}
906
John Kessenich5611c6d2018-04-05 11:25:02 -0600907// Add capabilities pertaining to how an array is indexed.
908void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
909 const glslang::TType& indexType)
910{
911 if (indexType.getQualifier().isNonUniform()) {
912 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -0500913 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -0600914 if (baseType.getBasicType() == glslang::EbtSampler) {
915 if (baseType.getQualifier().hasAttachment())
916 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
917 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
918 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
919 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
920 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
921 else if (baseType.isImage())
922 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
923 else if (baseType.isTexture())
924 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
925 } else if (baseType.getBasicType() == glslang::EbtBlock) {
926 if (baseType.getQualifier().storage == glslang::EvqBuffer)
927 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
928 else if (baseType.getQualifier().storage == glslang::EvqUniform)
929 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
930 }
931 } else {
932 // assume a dynamically uniform index
933 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -0500934 if (baseType.getQualifier().hasAttachment()) {
935 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -0600936 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -0500937 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
938 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -0600939 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -0500940 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
941 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -0600942 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -0500943 }
John Kessenich5611c6d2018-04-05 11:25:02 -0600944 }
945 }
946}
947
qining25262b32016-05-06 17:25:16 -0400948// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700949// descriptor set.
950bool IsDescriptorResource(const glslang::TType& type)
951{
John Kessenichf7497e22016-03-08 21:36:22 -0700952 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700953 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700954 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700955
956 // non block...
957 // basically samplerXXX/subpass/sampler/texture are all included
958 // if they are the global-scope-class, not the function parameter
959 // (or local, if they ever exist) class.
960 if (type.getBasicType() == glslang::EbtSampler)
961 return type.getQualifier().isUniformOrBuffer();
962
963 // None of the above.
964 return false;
965}
966
John Kesseniche0b6cad2015-12-24 10:30:13 -0700967void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
968{
969 if (child.layoutMatrix == glslang::ElmNone)
970 child.layoutMatrix = parent.layoutMatrix;
971
972 if (parent.invariant)
973 child.invariant = true;
974 if (parent.nopersp)
975 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800976#ifdef AMD_EXTENSIONS
977 if (parent.explicitInterp)
978 child.explicitInterp = true;
979#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700980 if (parent.flat)
981 child.flat = true;
982 if (parent.centroid)
983 child.centroid = true;
984 if (parent.patch)
985 child.patch = true;
986 if (parent.sample)
987 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800988 if (parent.coherent)
989 child.coherent = true;
990 if (parent.volatil)
991 child.volatil = true;
992 if (parent.restrict)
993 child.restrict = true;
994 if (parent.readonly)
995 child.readonly = true;
996 if (parent.writeonly)
997 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700998}
999
John Kessenichf2b7f332016-09-01 17:05:23 -06001000bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001001{
John Kessenich7b9fa252016-01-21 18:56:57 -07001002 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001003 // - struct members might inherit from a struct declaration
1004 // (note that non-block structs don't explicitly inherit,
1005 // only implicitly, meaning no decoration involved)
1006 // - affect decorations on the struct members
1007 // (note smooth does not, and expecting something like volatile
1008 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001009 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001010 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001011}
1012
John Kessenich140f3df2015-06-26 16:58:36 -06001013//
1014// Implement the TGlslangToSpvTraverser class.
1015//
1016
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001017TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001018 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1019 : TIntermTraverser(true, false, true),
1020 options(options),
1021 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001022 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001023 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001024 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001025 glslangIntermediate(glslangIntermediate)
1026{
1027 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1028
1029 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001030 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1031 glslangIntermediate->getVersion());
1032
John Kessenich121853f2017-05-31 17:11:16 -06001033 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001034 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001035 builder.setSourceFile(glslangIntermediate->getSourceFile());
1036
1037 // Set the source shader's text. If for SPV version 1.0, include
1038 // a preamble in comments stating the OpModuleProcessed instructions.
1039 // Otherwise, emit those as actual instructions.
1040 std::string text;
1041 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1042 for (int p = 0; p < (int)processes.size(); ++p) {
1043 if (glslangIntermediate->getSpv().spv < 0x00010100) {
1044 text.append("// OpModuleProcessed ");
1045 text.append(processes[p]);
1046 text.append("\n");
1047 } else
1048 builder.addModuleProcessed(processes[p]);
1049 }
1050 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
1051 text.append("#line 1\n");
1052 text.append(glslangIntermediate->getSourceText());
1053 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -06001054 }
John Kessenich140f3df2015-06-26 16:58:36 -06001055 stdBuiltins = builder.import("GLSL.std.450");
1056 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -06001057 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1058 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001059
1060 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001061 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1062 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001063 builder.addSourceExtension(it->c_str());
1064
1065 // Add the top-level modes for this shader.
1066
John Kessenich92187592016-02-01 13:45:25 -07001067 if (glslangIntermediate->getXfbMode()) {
1068 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001069 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001070 }
John Kessenich140f3df2015-06-26 16:58:36 -06001071
1072 unsigned int mode;
1073 switch (glslangIntermediate->getStage()) {
1074 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001075 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001076 break;
1077
steve-lunarge7412492017-03-23 11:56:07 -06001078 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001079 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001080 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001081
steve-lunarge7412492017-03-23 11:56:07 -06001082 glslang::TLayoutGeometry primitive;
1083
1084 if (glslangIntermediate->getStage() == EShLangTessControl) {
1085 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1086 primitive = glslangIntermediate->getOutputPrimitive();
1087 } else {
1088 primitive = glslangIntermediate->getInputPrimitive();
1089 }
1090
1091 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001092 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1093 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1094 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001095 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001096 }
John Kessenich4016e382016-07-15 11:53:56 -06001097 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001098 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1099
John Kesseniche6903322015-10-13 16:29:02 -06001100 switch (glslangIntermediate->getVertexSpacing()) {
1101 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1102 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1103 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001104 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001105 }
John Kessenich4016e382016-07-15 11:53:56 -06001106 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001107 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1108
1109 switch (glslangIntermediate->getVertexOrder()) {
1110 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1111 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001112 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001113 }
John Kessenich4016e382016-07-15 11:53:56 -06001114 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001115 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1116
1117 if (glslangIntermediate->getPointMode())
1118 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001119 break;
1120
1121 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001122 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001123 switch (glslangIntermediate->getInputPrimitive()) {
1124 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1125 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1126 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001127 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001128 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001129 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001130 }
John Kessenich4016e382016-07-15 11:53:56 -06001131 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001132 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001133
John Kessenich140f3df2015-06-26 16:58:36 -06001134 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1135
1136 switch (glslangIntermediate->getOutputPrimitive()) {
1137 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1138 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1139 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001140 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001141 }
John Kessenich4016e382016-07-15 11:53:56 -06001142 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001143 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1144 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1145 break;
1146
1147 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001148 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001149 if (glslangIntermediate->getPixelCenterInteger())
1150 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001151
John Kessenich140f3df2015-06-26 16:58:36 -06001152 if (glslangIntermediate->getOriginUpperLeft())
1153 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001154 else
1155 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001156
1157 if (glslangIntermediate->getEarlyFragmentTests())
1158 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1159
chaocc1204522017-06-30 17:14:30 -07001160 if (glslangIntermediate->getPostDepthCoverage()) {
1161 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1162 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1163 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1164 }
1165
John Kesseniche6903322015-10-13 16:29:02 -06001166 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001167 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1168 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001169 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001170 }
John Kessenich4016e382016-07-15 11:53:56 -06001171 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001172 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1173
1174 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1175 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001176 break;
1177
1178 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001179 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001180 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1181 glslangIntermediate->getLocalSize(1),
1182 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001183 break;
1184
1185 default:
1186 break;
1187 }
John Kessenich140f3df2015-06-26 16:58:36 -06001188}
1189
John Kessenichfca82622016-11-26 13:23:20 -07001190// Finish creating SPV, after the traversal is complete.
1191void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001192{
John Kessenichf04c51b2018-08-03 15:56:12 -06001193 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001194 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001195 builder.setBuildPoint(shaderEntry->getLastBlock());
1196 builder.leaveFunction();
1197 }
1198
John Kessenich7ba63412015-12-20 17:37:07 -07001199 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001200 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1201 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001202
John Kessenichf04c51b2018-08-03 15:56:12 -06001203 // Add capabilities, extensions, remove unneeded decorations, etc.,
1204 // based on the resulting SPIR-V.
1205 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001206}
1207
John Kessenichfca82622016-11-26 13:23:20 -07001208// Write the SPV into 'out'.
1209void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001210{
John Kessenichfca82622016-11-26 13:23:20 -07001211 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001212}
1213
1214//
1215// Implement the traversal functions.
1216//
1217// Return true from interior nodes to have the external traversal
1218// continue on to children. Return false if children were
1219// already processed.
1220//
1221
1222//
qining25262b32016-05-06 17:25:16 -04001223// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001224// - uniform/input reads
1225// - output writes
1226// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1227// - something simple that degenerates into the last bullet
1228//
1229void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1230{
qining75d1d802016-04-06 14:42:01 -04001231 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1232 if (symbol->getType().getQualifier().isSpecConstant())
1233 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1234
John Kessenich140f3df2015-06-26 16:58:36 -06001235 // getSymbolId() will set up all the IO decorations on the first call.
1236 // Formal function parameters were mapped during makeFunctions().
1237 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001238
1239 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1240 if (builder.isPointer(id)) {
1241 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001242 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1243 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1244 iOSet.insert(id);
1245 }
John Kessenich7ba63412015-12-20 17:37:07 -07001246 }
1247
1248 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001249 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001250 // Prepare to generate code for the access
1251
1252 // L-value chains will be computed left to right. We're on the symbol now,
1253 // which is the left-most part of the access chain, so now is "clear" time,
1254 // followed by setting the base.
1255 builder.clearAccessChain();
1256
1257 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001258 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001259 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001260 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001261 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001262 // These are also pure R-values.
1263 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001264 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001265 builder.setAccessChainRValue(id);
1266 else
1267 builder.setAccessChainLValue(id);
1268 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001269
1270 // Process linkage-only nodes for any special additional interface work.
1271 if (linkageOnly) {
1272 if (glslangIntermediate->getHlslFunctionality1()) {
1273 // Map implicit counter buffers to their originating buffers, which should have been
1274 // seen by now, given earlier pruning of unused counters, and preservation of order
1275 // of declaration.
1276 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1277 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1278 // Save possible originating buffers for counter buffers, keyed by
1279 // making the potential counter-buffer name.
1280 std::string keyName = symbol->getName().c_str();
1281 keyName = glslangIntermediate->addCounterBufferName(keyName);
1282 counterOriginator[keyName] = symbol;
1283 } else {
1284 // Handle a counter buffer, by finding the saved originating buffer.
1285 std::string keyName = symbol->getName().c_str();
1286 auto it = counterOriginator.find(keyName);
1287 if (it != counterOriginator.end()) {
1288 id = getSymbolId(it->second);
1289 if (id != spv::NoResult) {
1290 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001291 if (counterId != spv::NoResult) {
1292 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001293 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001294 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001295 }
1296 }
1297 }
1298 }
1299 }
1300 }
John Kessenich140f3df2015-06-26 16:58:36 -06001301}
1302
1303bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1304{
John Kesseniche485c7a2017-05-31 18:50:53 -06001305 builder.setLine(node->getLoc().line);
1306
qining40887662016-04-03 22:20:42 -04001307 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1308 if (node->getType().getQualifier().isSpecConstant())
1309 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1310
John Kessenich140f3df2015-06-26 16:58:36 -06001311 // First, handle special cases
1312 switch (node->getOp()) {
1313 case glslang::EOpAssign:
1314 case glslang::EOpAddAssign:
1315 case glslang::EOpSubAssign:
1316 case glslang::EOpMulAssign:
1317 case glslang::EOpVectorTimesMatrixAssign:
1318 case glslang::EOpVectorTimesScalarAssign:
1319 case glslang::EOpMatrixTimesScalarAssign:
1320 case glslang::EOpMatrixTimesMatrixAssign:
1321 case glslang::EOpDivAssign:
1322 case glslang::EOpModAssign:
1323 case glslang::EOpAndAssign:
1324 case glslang::EOpInclusiveOrAssign:
1325 case glslang::EOpExclusiveOrAssign:
1326 case glslang::EOpLeftShiftAssign:
1327 case glslang::EOpRightShiftAssign:
1328 // A bin-op assign "a += b" means the same thing as "a = a + b"
1329 // where a is evaluated before b. For a simple assignment, GLSL
1330 // says to evaluate the left before the right. So, always, left
1331 // node then right node.
1332 {
1333 // get the left l-value, save it away
1334 builder.clearAccessChain();
1335 node->getLeft()->traverse(this);
1336 spv::Builder::AccessChain lValue = builder.getAccessChain();
1337
1338 // evaluate the right
1339 builder.clearAccessChain();
1340 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001341 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001342
1343 if (node->getOp() != glslang::EOpAssign) {
1344 // the left is also an r-value
1345 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001346 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001347
1348 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001349 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001350 TranslateNoContractionDecoration(node->getType().getQualifier()),
1351 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001352 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001353 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1354 node->getType().getBasicType());
1355
1356 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001357 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001358 }
1359
1360 // store the result
1361 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001362 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001363
1364 // assignments are expressions having an rValue after they are evaluated...
1365 builder.clearAccessChain();
1366 builder.setAccessChainRValue(rValue);
1367 }
1368 return false;
1369 case glslang::EOpIndexDirect:
1370 case glslang::EOpIndexDirectStruct:
1371 {
1372 // Get the left part of the access chain.
1373 node->getLeft()->traverse(this);
1374
1375 // Add the next element in the chain
1376
David Netoa901ffe2016-06-08 14:11:40 +01001377 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001378 if (! node->getLeft()->getType().isArray() &&
1379 node->getLeft()->getType().isVector() &&
1380 node->getOp() == glslang::EOpIndexDirect) {
1381 // This is essentially a hard-coded vector swizzle of size 1,
1382 // so short circuit the access-chain stuff with a swizzle.
1383 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001384 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001385 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001386 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001387 int spvIndex = glslangIndex;
1388 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1389 node->getOp() == glslang::EOpIndexDirectStruct)
1390 {
1391 // This may be, e.g., an anonymous block-member selection, which generally need
1392 // index remapping due to hidden members in anonymous blocks.
1393 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1394 assert(remapper.size() > 0);
1395 spvIndex = remapper[glslangIndex];
1396 }
John Kessenichebb50532016-05-16 19:22:05 -06001397
David Netoa901ffe2016-06-08 14:11:40 +01001398 // normal case for indexing array or structure or block
1399 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1400
1401 // Add capabilities here for accessing PointSize and clip/cull distance.
1402 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001403 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001404 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001405 }
1406 }
1407 return false;
1408 case glslang::EOpIndexIndirect:
1409 {
1410 // Structure or array or vector indirection.
1411 // Will use native SPIR-V access-chain for struct and array indirection;
1412 // matrices are arrays of vectors, so will also work for a matrix.
1413 // Will use the access chain's 'component' for variable index into a vector.
1414
1415 // This adapter is building access chains left to right.
1416 // Set up the access chain to the left.
1417 node->getLeft()->traverse(this);
1418
1419 // save it so that computing the right side doesn't trash it
1420 spv::Builder::AccessChain partial = builder.getAccessChain();
1421
1422 // compute the next index in the chain
1423 builder.clearAccessChain();
1424 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001425 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001426
John Kessenich5611c6d2018-04-05 11:25:02 -06001427 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1428
John Kessenich140f3df2015-06-26 16:58:36 -06001429 // restore the saved access chain
1430 builder.setAccessChain(partial);
1431
1432 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001433 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001434 else
John Kessenichfa668da2015-09-13 14:46:30 -06001435 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001436 }
1437 return false;
1438 case glslang::EOpVectorSwizzle:
1439 {
1440 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001441 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001442 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001443 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001444 }
1445 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001446 case glslang::EOpMatrixSwizzle:
1447 logger->missingFunctionality("matrix swizzle");
1448 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001449 case glslang::EOpLogicalOr:
1450 case glslang::EOpLogicalAnd:
1451 {
1452
1453 // These may require short circuiting, but can sometimes be done as straight
1454 // binary operations. The right operand must be short circuited if it has
1455 // side effects, and should probably be if it is complex.
1456 if (isTrivial(node->getRight()->getAsTyped()))
1457 break; // handle below as a normal binary operation
1458 // otherwise, we need to do dynamic short circuiting on the right operand
1459 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1460 builder.clearAccessChain();
1461 builder.setAccessChainRValue(result);
1462 }
1463 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001464 default:
1465 break;
1466 }
1467
1468 // Assume generic binary op...
1469
John Kessenich32cfd492016-02-02 12:37:46 -07001470 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001471 builder.clearAccessChain();
1472 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001473 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001474
John Kessenich32cfd492016-02-02 12:37:46 -07001475 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001476 builder.clearAccessChain();
1477 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001478 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001479
John Kessenich32cfd492016-02-02 12:37:46 -07001480 // get result
John Kessenichead86222018-03-28 18:01:20 -06001481 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001482 TranslateNoContractionDecoration(node->getType().getQualifier()),
1483 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001484 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001485 convertGlslangToSpvType(node->getType()), left, right,
1486 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001487
John Kessenich50e57562015-12-21 21:21:11 -07001488 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001489 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001490 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001491 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001492 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001493 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001494 return false;
1495 }
John Kessenich140f3df2015-06-26 16:58:36 -06001496}
1497
1498bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1499{
John Kesseniche485c7a2017-05-31 18:50:53 -06001500 builder.setLine(node->getLoc().line);
1501
qining40887662016-04-03 22:20:42 -04001502 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1503 if (node->getType().getQualifier().isSpecConstant())
1504 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1505
John Kessenichfc51d282015-08-19 13:34:18 -06001506 spv::Id result = spv::NoResult;
1507
1508 // try texturing first
1509 result = createImageTextureFunctionCall(node);
1510 if (result != spv::NoResult) {
1511 builder.clearAccessChain();
1512 builder.setAccessChainRValue(result);
1513
1514 return false; // done with this node
1515 }
1516
1517 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001518
1519 if (node->getOp() == glslang::EOpArrayLength) {
1520 // Quite special; won't want to evaluate the operand.
1521
John Kessenich5611c6d2018-04-05 11:25:02 -06001522 // Currently, the front-end does not allow .length() on an array until it is sized,
1523 // except for the last block membeor of an SSBO.
1524 // TODO: If this changes, link-time sized arrays might show up here, and need their
1525 // size extracted.
1526
John Kessenichc9a80832015-09-12 12:17:44 -06001527 // Normal .length() would have been constant folded by the front-end.
1528 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001529 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001530
John Kessenichc9a80832015-09-12 12:17:44 -06001531 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1532 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001533 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1534 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001535
1536 builder.clearAccessChain();
1537 builder.setAccessChainRValue(length);
1538
1539 return false;
1540 }
1541
John Kessenichfc51d282015-08-19 13:34:18 -06001542 // Start by evaluating the operand
1543
John Kessenich8c8505c2016-07-26 12:50:38 -06001544 // Does it need a swizzle inversion? If so, evaluation is inverted;
1545 // operate first on the swizzle base, then apply the swizzle.
1546 spv::Id invertedType = spv::NoType;
1547 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1548 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1549 invertedType = getInvertedSwizzleType(*node->getOperand());
1550
John Kessenich140f3df2015-06-26 16:58:36 -06001551 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001552 if (invertedType != spv::NoType)
1553 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1554 else
1555 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001556
Rex Xufc618912015-09-09 16:42:49 +08001557 spv::Id operand = spv::NoResult;
1558
1559 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1560 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001561 node->getOp() == glslang::EOpAtomicCounter ||
1562 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001563 operand = builder.accessChainGetLValue(); // Special case l-value operands
1564 else
John Kessenich32cfd492016-02-02 12:37:46 -07001565 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001566
John Kessenichead86222018-03-28 18:01:20 -06001567 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001568 TranslateNoContractionDecoration(node->getType().getQualifier()),
1569 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001570
1571 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001572 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001573 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001574
1575 // if not, then possibly an operation
1576 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001577 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001578
1579 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001580 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001581 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001582 builder.addDecoration(result, decorations.nonUniform);
1583 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001584
John Kessenich140f3df2015-06-26 16:58:36 -06001585 builder.clearAccessChain();
1586 builder.setAccessChainRValue(result);
1587
1588 return false; // done with this node
1589 }
1590
1591 // it must be a special case, check...
1592 switch (node->getOp()) {
1593 case glslang::EOpPostIncrement:
1594 case glslang::EOpPostDecrement:
1595 case glslang::EOpPreIncrement:
1596 case glslang::EOpPreDecrement:
1597 {
1598 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001599 spv::Id one = 0;
1600 if (node->getBasicType() == glslang::EbtFloat)
1601 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001602 else if (node->getBasicType() == glslang::EbtDouble)
1603 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001604 else if (node->getBasicType() == glslang::EbtFloat16)
1605 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001606 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1607 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001608 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1609 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001610 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1611 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001612 else
1613 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001614 glslang::TOperator op;
1615 if (node->getOp() == glslang::EOpPreIncrement ||
1616 node->getOp() == glslang::EOpPostIncrement)
1617 op = glslang::EOpAdd;
1618 else
1619 op = glslang::EOpSub;
1620
John Kessenichead86222018-03-28 18:01:20 -06001621 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001622 convertGlslangToSpvType(node->getType()), operand, one,
1623 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001624 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001625
1626 // The result of operation is always stored, but conditionally the
1627 // consumed result. The consumed result is always an r-value.
1628 builder.accessChainStore(result);
1629 builder.clearAccessChain();
1630 if (node->getOp() == glslang::EOpPreIncrement ||
1631 node->getOp() == glslang::EOpPreDecrement)
1632 builder.setAccessChainRValue(result);
1633 else
1634 builder.setAccessChainRValue(operand);
1635 }
1636
1637 return false;
1638
1639 case glslang::EOpEmitStreamVertex:
1640 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1641 return false;
1642 case glslang::EOpEndStreamPrimitive:
1643 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1644 return false;
1645
1646 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001647 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001648 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001649 }
John Kessenich140f3df2015-06-26 16:58:36 -06001650}
1651
1652bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1653{
qining27e04a02016-04-14 16:40:20 -04001654 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1655 if (node->getType().getQualifier().isSpecConstant())
1656 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1657
John Kessenichfc51d282015-08-19 13:34:18 -06001658 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001659 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1660 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001661
1662 // try texturing
1663 result = createImageTextureFunctionCall(node);
1664 if (result != spv::NoResult) {
1665 builder.clearAccessChain();
1666 builder.setAccessChainRValue(result);
1667
1668 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001669#ifdef AMD_EXTENSIONS
1670 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1671#else
John Kessenich56bab042015-09-16 10:54:31 -06001672 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001673#endif
Rex Xufc618912015-09-09 16:42:49 +08001674 // "imageStore" is a special case, which has no result
1675 return false;
1676 }
John Kessenichfc51d282015-08-19 13:34:18 -06001677
John Kessenich140f3df2015-06-26 16:58:36 -06001678 glslang::TOperator binOp = glslang::EOpNull;
1679 bool reduceComparison = true;
1680 bool isMatrix = false;
1681 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001682 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001683
1684 assert(node->getOp());
1685
John Kessenichf6640762016-08-01 19:44:00 -06001686 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001687
1688 switch (node->getOp()) {
1689 case glslang::EOpSequence:
1690 {
1691 if (preVisit)
1692 ++sequenceDepth;
1693 else
1694 --sequenceDepth;
1695
1696 if (sequenceDepth == 1) {
1697 // If this is the parent node of all the functions, we want to see them
1698 // early, so all call points have actual SPIR-V functions to reference.
1699 // In all cases, still let the traverser visit the children for us.
1700 makeFunctions(node->getAsAggregate()->getSequence());
1701
John Kessenich6fccb3c2016-09-19 16:01:41 -06001702 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001703 // anything else gets there, so visit out of order, doing them all now.
1704 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1705
John Kessenich6a60c2f2016-12-08 21:01:59 -07001706 // 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 -06001707 // so do them manually.
1708 visitFunctions(node->getAsAggregate()->getSequence());
1709
1710 return false;
1711 }
1712
1713 return true;
1714 }
1715 case glslang::EOpLinkerObjects:
1716 {
1717 if (visit == glslang::EvPreVisit)
1718 linkageOnly = true;
1719 else
1720 linkageOnly = false;
1721
1722 return true;
1723 }
1724 case glslang::EOpComma:
1725 {
1726 // processing from left to right naturally leaves the right-most
1727 // lying around in the access chain
1728 glslang::TIntermSequence& glslangOperands = node->getSequence();
1729 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1730 glslangOperands[i]->traverse(this);
1731
1732 return false;
1733 }
1734 case glslang::EOpFunction:
1735 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001736 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001737 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001738 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001739 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001740 } else {
1741 handleFunctionEntry(node);
1742 }
1743 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001744 if (inEntryPoint)
1745 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001746 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001747 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001748 }
1749
1750 return true;
1751 case glslang::EOpParameters:
1752 // Parameters will have been consumed by EOpFunction processing, but not
1753 // the body, so we still visited the function node's children, making this
1754 // child redundant.
1755 return false;
1756 case glslang::EOpFunctionCall:
1757 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001758 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001759 if (node->isUserDefined())
1760 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001761 // 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 -07001762 if (result) {
1763 builder.clearAccessChain();
1764 builder.setAccessChainRValue(result);
1765 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001766 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001767
1768 return false;
1769 }
1770 case glslang::EOpConstructMat2x2:
1771 case glslang::EOpConstructMat2x3:
1772 case glslang::EOpConstructMat2x4:
1773 case glslang::EOpConstructMat3x2:
1774 case glslang::EOpConstructMat3x3:
1775 case glslang::EOpConstructMat3x4:
1776 case glslang::EOpConstructMat4x2:
1777 case glslang::EOpConstructMat4x3:
1778 case glslang::EOpConstructMat4x4:
1779 case glslang::EOpConstructDMat2x2:
1780 case glslang::EOpConstructDMat2x3:
1781 case glslang::EOpConstructDMat2x4:
1782 case glslang::EOpConstructDMat3x2:
1783 case glslang::EOpConstructDMat3x3:
1784 case glslang::EOpConstructDMat3x4:
1785 case glslang::EOpConstructDMat4x2:
1786 case glslang::EOpConstructDMat4x3:
1787 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001788 case glslang::EOpConstructIMat2x2:
1789 case glslang::EOpConstructIMat2x3:
1790 case glslang::EOpConstructIMat2x4:
1791 case glslang::EOpConstructIMat3x2:
1792 case glslang::EOpConstructIMat3x3:
1793 case glslang::EOpConstructIMat3x4:
1794 case glslang::EOpConstructIMat4x2:
1795 case glslang::EOpConstructIMat4x3:
1796 case glslang::EOpConstructIMat4x4:
1797 case glslang::EOpConstructUMat2x2:
1798 case glslang::EOpConstructUMat2x3:
1799 case glslang::EOpConstructUMat2x4:
1800 case glslang::EOpConstructUMat3x2:
1801 case glslang::EOpConstructUMat3x3:
1802 case glslang::EOpConstructUMat3x4:
1803 case glslang::EOpConstructUMat4x2:
1804 case glslang::EOpConstructUMat4x3:
1805 case glslang::EOpConstructUMat4x4:
1806 case glslang::EOpConstructBMat2x2:
1807 case glslang::EOpConstructBMat2x3:
1808 case glslang::EOpConstructBMat2x4:
1809 case glslang::EOpConstructBMat3x2:
1810 case glslang::EOpConstructBMat3x3:
1811 case glslang::EOpConstructBMat3x4:
1812 case glslang::EOpConstructBMat4x2:
1813 case glslang::EOpConstructBMat4x3:
1814 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001815 case glslang::EOpConstructF16Mat2x2:
1816 case glslang::EOpConstructF16Mat2x3:
1817 case glslang::EOpConstructF16Mat2x4:
1818 case glslang::EOpConstructF16Mat3x2:
1819 case glslang::EOpConstructF16Mat3x3:
1820 case glslang::EOpConstructF16Mat3x4:
1821 case glslang::EOpConstructF16Mat4x2:
1822 case glslang::EOpConstructF16Mat4x3:
1823 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06001824 isMatrix = true;
1825 // fall through
1826 case glslang::EOpConstructFloat:
1827 case glslang::EOpConstructVec2:
1828 case glslang::EOpConstructVec3:
1829 case glslang::EOpConstructVec4:
1830 case glslang::EOpConstructDouble:
1831 case glslang::EOpConstructDVec2:
1832 case glslang::EOpConstructDVec3:
1833 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001834 case glslang::EOpConstructFloat16:
1835 case glslang::EOpConstructF16Vec2:
1836 case glslang::EOpConstructF16Vec3:
1837 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001838 case glslang::EOpConstructBool:
1839 case glslang::EOpConstructBVec2:
1840 case glslang::EOpConstructBVec3:
1841 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07001842 case glslang::EOpConstructInt8:
1843 case glslang::EOpConstructI8Vec2:
1844 case glslang::EOpConstructI8Vec3:
1845 case glslang::EOpConstructI8Vec4:
1846 case glslang::EOpConstructUint8:
1847 case glslang::EOpConstructU8Vec2:
1848 case glslang::EOpConstructU8Vec3:
1849 case glslang::EOpConstructU8Vec4:
1850 case glslang::EOpConstructInt16:
1851 case glslang::EOpConstructI16Vec2:
1852 case glslang::EOpConstructI16Vec3:
1853 case glslang::EOpConstructI16Vec4:
1854 case glslang::EOpConstructUint16:
1855 case glslang::EOpConstructU16Vec2:
1856 case glslang::EOpConstructU16Vec3:
1857 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001858 case glslang::EOpConstructInt:
1859 case glslang::EOpConstructIVec2:
1860 case glslang::EOpConstructIVec3:
1861 case glslang::EOpConstructIVec4:
1862 case glslang::EOpConstructUint:
1863 case glslang::EOpConstructUVec2:
1864 case glslang::EOpConstructUVec3:
1865 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001866 case glslang::EOpConstructInt64:
1867 case glslang::EOpConstructI64Vec2:
1868 case glslang::EOpConstructI64Vec3:
1869 case glslang::EOpConstructI64Vec4:
1870 case glslang::EOpConstructUint64:
1871 case glslang::EOpConstructU64Vec2:
1872 case glslang::EOpConstructU64Vec3:
1873 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001874 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001875 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001876 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001877 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001878 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001879 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001880 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001881 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001882 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001883 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001884 std::vector<spv::Id> constituents;
1885 for (int c = 0; c < (int)arguments.size(); ++c)
1886 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001887 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001888 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001889 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001890 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001891 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001892
1893 builder.clearAccessChain();
1894 builder.setAccessChainRValue(constructed);
1895
1896 return false;
1897 }
1898
1899 // These six are component-wise compares with component-wise results.
1900 // Forward on to createBinaryOperation(), requesting a vector result.
1901 case glslang::EOpLessThan:
1902 case glslang::EOpGreaterThan:
1903 case glslang::EOpLessThanEqual:
1904 case glslang::EOpGreaterThanEqual:
1905 case glslang::EOpVectorEqual:
1906 case glslang::EOpVectorNotEqual:
1907 {
1908 // Map the operation to a binary
1909 binOp = node->getOp();
1910 reduceComparison = false;
1911 switch (node->getOp()) {
1912 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1913 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1914 default: binOp = node->getOp(); break;
1915 }
1916
1917 break;
1918 }
1919 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001920 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001921 binOp = glslang::EOpMul;
1922 break;
1923 case glslang::EOpOuterProduct:
1924 // two vectors multiplied to make a matrix
1925 binOp = glslang::EOpOuterProduct;
1926 break;
1927 case glslang::EOpDot:
1928 {
qining25262b32016-05-06 17:25:16 -04001929 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001930 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001931 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001932 binOp = glslang::EOpMul;
1933 break;
1934 }
1935 case glslang::EOpMod:
1936 // when an aggregate, this is the floating-point mod built-in function,
1937 // which can be emitted by the one in createBinaryOperation()
1938 binOp = glslang::EOpMod;
1939 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001940 case glslang::EOpEmitVertex:
1941 case glslang::EOpEndPrimitive:
1942 case glslang::EOpBarrier:
1943 case glslang::EOpMemoryBarrier:
1944 case glslang::EOpMemoryBarrierAtomicCounter:
1945 case glslang::EOpMemoryBarrierBuffer:
1946 case glslang::EOpMemoryBarrierImage:
1947 case glslang::EOpMemoryBarrierShared:
1948 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07001949 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001950 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07001951 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001952 case glslang::EOpWorkgroupMemoryBarrier:
1953 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07001954 case glslang::EOpSubgroupBarrier:
1955 case glslang::EOpSubgroupMemoryBarrier:
1956 case glslang::EOpSubgroupMemoryBarrierBuffer:
1957 case glslang::EOpSubgroupMemoryBarrierImage:
1958 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06001959 noReturnValue = true;
1960 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1961 break;
1962
John Kessenich426394d2015-07-23 10:22:48 -06001963 case glslang::EOpAtomicAdd:
1964 case glslang::EOpAtomicMin:
1965 case glslang::EOpAtomicMax:
1966 case glslang::EOpAtomicAnd:
1967 case glslang::EOpAtomicOr:
1968 case glslang::EOpAtomicXor:
1969 case glslang::EOpAtomicExchange:
1970 case glslang::EOpAtomicCompSwap:
1971 atomic = true;
1972 break;
1973
John Kessenich0d0c6d32017-07-23 16:08:26 -06001974 case glslang::EOpAtomicCounterAdd:
1975 case glslang::EOpAtomicCounterSubtract:
1976 case glslang::EOpAtomicCounterMin:
1977 case glslang::EOpAtomicCounterMax:
1978 case glslang::EOpAtomicCounterAnd:
1979 case glslang::EOpAtomicCounterOr:
1980 case glslang::EOpAtomicCounterXor:
1981 case glslang::EOpAtomicCounterExchange:
1982 case glslang::EOpAtomicCounterCompSwap:
1983 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1984 builder.addCapability(spv::CapabilityAtomicStorageOps);
1985 atomic = true;
1986 break;
1987
John Kessenich140f3df2015-06-26 16:58:36 -06001988 default:
1989 break;
1990 }
1991
1992 //
1993 // See if it maps to a regular operation.
1994 //
John Kessenich140f3df2015-06-26 16:58:36 -06001995 if (binOp != glslang::EOpNull) {
1996 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1997 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1998 assert(left && right);
1999
2000 builder.clearAccessChain();
2001 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002002 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002003
2004 builder.clearAccessChain();
2005 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002006 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002007
John Kesseniche485c7a2017-05-31 18:50:53 -06002008 builder.setLine(node->getLoc().line);
John Kessenichead86222018-03-28 18:01:20 -06002009 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002010 TranslateNoContractionDecoration(node->getType().getQualifier()),
2011 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002012 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002013 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002014 left->getType().getBasicType(), reduceComparison);
2015
2016 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002017 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002018 builder.clearAccessChain();
2019 builder.setAccessChainRValue(result);
2020
2021 return false;
2022 }
2023
John Kessenich426394d2015-07-23 10:22:48 -06002024 //
2025 // Create the list of operands.
2026 //
John Kessenich140f3df2015-06-26 16:58:36 -06002027 glslang::TIntermSequence& glslangOperands = node->getSequence();
2028 std::vector<spv::Id> operands;
2029 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002030 // special case l-value operands; there are just a few
2031 bool lvalue = false;
2032 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002033 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002034 case glslang::EOpModf:
2035 if (arg == 1)
2036 lvalue = true;
2037 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002038 case glslang::EOpInterpolateAtSample:
2039 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002040#ifdef AMD_EXTENSIONS
2041 case glslang::EOpInterpolateAtVertex:
2042#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002043 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002044 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002045
2046 // Does it need a swizzle inversion? If so, evaluation is inverted;
2047 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002048 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002049 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2050 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2051 }
Rex Xu7a26c172015-12-08 17:12:09 +08002052 break;
Rex Xud4782c12015-09-06 16:30:11 +08002053 case glslang::EOpAtomicAdd:
2054 case glslang::EOpAtomicMin:
2055 case glslang::EOpAtomicMax:
2056 case glslang::EOpAtomicAnd:
2057 case glslang::EOpAtomicOr:
2058 case glslang::EOpAtomicXor:
2059 case glslang::EOpAtomicExchange:
2060 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002061 case glslang::EOpAtomicCounterAdd:
2062 case glslang::EOpAtomicCounterSubtract:
2063 case glslang::EOpAtomicCounterMin:
2064 case glslang::EOpAtomicCounterMax:
2065 case glslang::EOpAtomicCounterAnd:
2066 case glslang::EOpAtomicCounterOr:
2067 case glslang::EOpAtomicCounterXor:
2068 case glslang::EOpAtomicCounterExchange:
2069 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002070 if (arg == 0)
2071 lvalue = true;
2072 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002073 case glslang::EOpAddCarry:
2074 case glslang::EOpSubBorrow:
2075 if (arg == 2)
2076 lvalue = true;
2077 break;
2078 case glslang::EOpUMulExtended:
2079 case glslang::EOpIMulExtended:
2080 if (arg >= 2)
2081 lvalue = true;
2082 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002083 default:
2084 break;
2085 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002086 builder.clearAccessChain();
2087 if (invertedType != spv::NoType && arg == 0)
2088 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2089 else
2090 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002091 if (lvalue)
2092 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002093 else {
2094 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07002095 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002096 }
John Kessenich140f3df2015-06-26 16:58:36 -06002097 }
John Kessenich426394d2015-07-23 10:22:48 -06002098
John Kesseniche485c7a2017-05-31 18:50:53 -06002099 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06002100 if (atomic) {
2101 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002102 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002103 } else {
2104 // Pass through to generic operations.
2105 switch (glslangOperands.size()) {
2106 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002107 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002108 break;
2109 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002110 {
2111 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002112 TranslateNoContractionDecoration(node->getType().getQualifier()),
2113 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002114 result = createUnaryOperation(
2115 node->getOp(), decorations,
2116 resultType(), operands.front(),
2117 glslangOperands[0]->getAsTyped()->getBasicType());
2118 }
John Kessenich426394d2015-07-23 10:22:48 -06002119 break;
2120 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002121 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002122 break;
2123 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002124 if (invertedType)
2125 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002126 }
2127
2128 if (noReturnValue)
2129 return false;
2130
2131 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002132 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002133 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002134 } else {
2135 builder.clearAccessChain();
2136 builder.setAccessChainRValue(result);
2137 return false;
2138 }
2139}
2140
John Kessenich433e9ff2017-01-26 20:31:11 -07002141// This path handles both if-then-else and ?:
2142// The if-then-else has a node type of void, while
2143// ?: has either a void or a non-void node type
2144//
2145// Leaving the result, when not void:
2146// GLSL only has r-values as the result of a :?, but
2147// if we have an l-value, that can be more efficient if it will
2148// become the base of a complex r-value expression, because the
2149// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002150bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2151{
John Kessenich4bee5312018-02-20 21:29:05 -07002152 // See if it simple and safe, or required, to execute both sides.
2153 // Crucially, side effects must be either semantically required or avoided,
2154 // and there are performance trade-offs.
2155 // Return true if required or a good idea (and safe) to execute both sides,
2156 // false otherwise.
2157 const auto bothSidesPolicy = [&]() -> bool {
2158 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002159 if (node->getTrueBlock() == nullptr ||
2160 node->getFalseBlock() == nullptr)
2161 return false;
2162
John Kessenich4bee5312018-02-20 21:29:05 -07002163 // required? (unless we write additional code to look for side effects
2164 // and make performance trade-offs if none are present)
2165 if (!node->getShortCircuit())
2166 return true;
2167
2168 // if not required to execute both, decide based on performance/practicality...
2169
2170 // see if OpSelect can handle it
2171 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2172 node->getBasicType() == glslang::EbtVoid)
2173 return false;
2174
John Kessenich433e9ff2017-01-26 20:31:11 -07002175 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2176 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2177
2178 // return true if a single operand to ? : is okay for OpSelect
2179 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002180 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002181 };
2182
2183 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2184 operandOkay(node->getFalseBlock()->getAsTyped());
2185 };
2186
John Kessenich4bee5312018-02-20 21:29:05 -07002187 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2188 // emit the condition before doing anything with selection
2189 node->getCondition()->traverse(this);
2190 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2191
2192 // Find a way of executing both sides and selecting the right result.
2193 const auto executeBothSides = [&]() -> void {
2194 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002195 node->getTrueBlock()->traverse(this);
2196 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2197 node->getFalseBlock()->traverse(this);
2198 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2199
John Kesseniche485c7a2017-05-31 18:50:53 -06002200 builder.setLine(node->getLoc().line);
2201
John Kessenich4bee5312018-02-20 21:29:05 -07002202 // done if void
2203 if (node->getBasicType() == glslang::EbtVoid)
2204 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002205
John Kessenich4bee5312018-02-20 21:29:05 -07002206 // emit code to select between trueValue and falseValue
2207
2208 // see if OpSelect can handle it
2209 if (node->getType().isScalar() || node->getType().isVector()) {
2210 // Emit OpSelect for this selection.
2211
2212 // smear condition to vector, if necessary (AST is always scalar)
2213 if (builder.isVector(trueValue))
2214 condition = builder.smearScalar(spv::NoPrecision, condition,
2215 builder.makeVectorType(builder.makeBoolType(),
2216 builder.getNumComponents(trueValue)));
2217
2218 // OpSelect
2219 result = builder.createTriOp(spv::OpSelect,
2220 convertGlslangToSpvType(node->getType()), condition,
2221 trueValue, falseValue);
2222
2223 builder.clearAccessChain();
2224 builder.setAccessChainRValue(result);
2225 } else {
2226 // We need control flow to select the result.
2227 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2228 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2229
2230 // Selection control:
2231 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2232
2233 // make an "if" based on the value created by the condition
2234 spv::Builder::If ifBuilder(condition, control, builder);
2235
2236 // emit the "then" statement
2237 builder.createStore(trueValue, result);
2238 ifBuilder.makeBeginElse();
2239 // emit the "else" statement
2240 builder.createStore(falseValue, result);
2241
2242 // finish off the control flow
2243 ifBuilder.makeEndIf();
2244
2245 builder.clearAccessChain();
2246 builder.setAccessChainLValue(result);
2247 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002248 };
2249
John Kessenich4bee5312018-02-20 21:29:05 -07002250 // Execute the one side needed, as per the condition
2251 const auto executeOneSide = [&]() {
2252 // Always emit control flow.
2253 if (node->getBasicType() != glslang::EbtVoid)
2254 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002255
John Kessenich4bee5312018-02-20 21:29:05 -07002256 // Selection control:
2257 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2258
2259 // make an "if" based on the value created by the condition
2260 spv::Builder::If ifBuilder(condition, control, builder);
2261
2262 // emit the "then" statement
2263 if (node->getTrueBlock() != nullptr) {
2264 node->getTrueBlock()->traverse(this);
2265 if (result != spv::NoResult)
2266 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2267 }
2268
2269 if (node->getFalseBlock() != nullptr) {
2270 ifBuilder.makeBeginElse();
2271 // emit the "else" statement
2272 node->getFalseBlock()->traverse(this);
2273 if (result != spv::NoResult)
2274 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2275 }
2276
2277 // finish off the control flow
2278 ifBuilder.makeEndIf();
2279
2280 if (result != spv::NoResult) {
2281 builder.clearAccessChain();
2282 builder.setAccessChainLValue(result);
2283 }
2284 };
2285
2286 // Try for OpSelect (or a requirement to execute both sides)
2287 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002288 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2289 if (node->getType().getQualifier().isSpecConstant())
2290 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002291 executeBothSides();
2292 } else
2293 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002294
2295 return false;
2296}
2297
2298bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2299{
2300 // emit and get the condition before doing anything with switch
2301 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002302 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002303
Rex Xu57e65922017-07-04 23:23:40 +08002304 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002305 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002306
John Kessenich140f3df2015-06-26 16:58:36 -06002307 // browse the children to sort out code segments
2308 int defaultSegment = -1;
2309 std::vector<TIntermNode*> codeSegments;
2310 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2311 std::vector<int> caseValues;
2312 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2313 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2314 TIntermNode* child = *c;
2315 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002316 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002317 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002318 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002319 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2320 } else
2321 codeSegments.push_back(child);
2322 }
2323
qining25262b32016-05-06 17:25:16 -04002324 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002325 // statements between the last case and the end of the switch statement
2326 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2327 (int)codeSegments.size() == defaultSegment)
2328 codeSegments.push_back(nullptr);
2329
2330 // make the switch statement
2331 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002332 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002333
2334 // emit all the code in the segments
2335 breakForLoop.push(false);
2336 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2337 builder.nextSwitchSegment(segmentBlocks, s);
2338 if (codeSegments[s])
2339 codeSegments[s]->traverse(this);
2340 else
2341 builder.addSwitchBreak();
2342 }
2343 breakForLoop.pop();
2344
2345 builder.endSwitch(segmentBlocks);
2346
2347 return false;
2348}
2349
2350void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2351{
2352 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002353 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002354
2355 builder.clearAccessChain();
2356 builder.setAccessChainRValue(constant);
2357}
2358
2359bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2360{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002361 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002362 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002363
2364 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002365 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2366 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002367
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002368 // Spec requires back edges to target header blocks, and every header block
2369 // must dominate its merge block. Make a header block first to ensure these
2370 // conditions are met. By definition, it will contain OpLoopMerge, followed
2371 // by a block-ending branch. But we don't want to put any other body/test
2372 // instructions in it, since the body/test may have arbitrary instructions,
2373 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002374 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002375 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002376 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002377 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002378 spv::Block& test = builder.makeNewBlock();
2379 builder.createBranch(&test);
2380
2381 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002382 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002383 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002384 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2385
2386 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002387 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002388 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002389 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002390 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002391 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002392
2393 builder.setBuildPoint(&blocks.continue_target);
2394 if (node->getTerminal())
2395 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002396 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002397 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002398 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002399 builder.createBranch(&blocks.body);
2400
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002401 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002402 builder.setBuildPoint(&blocks.body);
2403 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002404 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002405 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002406 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002407
2408 builder.setBuildPoint(&blocks.continue_target);
2409 if (node->getTerminal())
2410 node->getTerminal()->traverse(this);
2411 if (node->getTest()) {
2412 node->getTest()->traverse(this);
2413 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002414 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002415 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002416 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002417 // TODO: unless there was a break/return/discard instruction
2418 // somewhere in the body, this is an infinite loop, so we should
2419 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002420 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002421 }
John Kessenich140f3df2015-06-26 16:58:36 -06002422 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002423 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002424 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002425 return false;
2426}
2427
2428bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2429{
2430 if (node->getExpression())
2431 node->getExpression()->traverse(this);
2432
John Kesseniche485c7a2017-05-31 18:50:53 -06002433 builder.setLine(node->getLoc().line);
2434
John Kessenich140f3df2015-06-26 16:58:36 -06002435 switch (node->getFlowOp()) {
2436 case glslang::EOpKill:
2437 builder.makeDiscard();
2438 break;
2439 case glslang::EOpBreak:
2440 if (breakForLoop.top())
2441 builder.createLoopExit();
2442 else
2443 builder.addSwitchBreak();
2444 break;
2445 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002446 builder.createLoopContinue();
2447 break;
2448 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002449 if (node->getExpression()) {
2450 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2451 spv::Id returnId = accessChainLoad(glslangReturnType);
2452 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2453 builder.clearAccessChain();
2454 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2455 builder.setAccessChainLValue(copyId);
2456 multiTypeStore(glslangReturnType, returnId);
2457 returnId = builder.createLoad(copyId);
2458 }
2459 builder.makeReturn(false, returnId);
2460 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002461 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002462
2463 builder.clearAccessChain();
2464 break;
2465
2466 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002467 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002468 break;
2469 }
2470
2471 return false;
2472}
2473
2474spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2475{
qining25262b32016-05-06 17:25:16 -04002476 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002477 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002478 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002479 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002480 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002481 }
2482
2483 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002484 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002485 spv::Id spvType = convertGlslangToSpvType(node->getType());
2486
Rex Xucabbb782017-03-24 13:41:14 +08002487 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2488 node->getType().containsBasicType(glslang::EbtInt16) ||
2489 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002490 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002491 switch (storageClass) {
2492 case spv::StorageClassInput:
2493 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002494 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002495 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002496 break;
2497 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07002498 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002499 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06002500 break;
2501 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07002502 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002503 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2504 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06002505 else
2506 builder.addCapability(spv::CapabilityStorageUniform16);
2507 break;
2508 case spv::StorageClassStorageBuffer:
2509 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
2510 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2511 break;
2512 default:
2513 break;
Rex Xuf89ad982017-04-07 23:22:33 +08002514 }
2515 }
Rex Xuf89ad982017-04-07 23:22:33 +08002516
John Kessenich312dcfb2018-07-03 13:19:51 -06002517 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
2518 node->getType().containsBasicType(glslang::EbtUint8);
2519 if (contains8BitType) {
2520 if (storageClass == spv::StorageClassPushConstant) {
2521 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2522 builder.addCapability(spv::CapabilityStoragePushConstant8);
2523 } else if (storageClass == spv::StorageClassUniform) {
2524 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2525 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
2526 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2527 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
2528 }
2529 }
2530
John Kessenich140f3df2015-06-26 16:58:36 -06002531 const char* name = node->getName().c_str();
2532 if (glslang::IsAnonymous(name))
2533 name = "";
2534
2535 return builder.createVariable(storageClass, spvType, name);
2536}
2537
2538// Return type Id of the sampled type.
2539spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2540{
2541 switch (sampler.type) {
2542 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08002543#ifdef AMD_EXTENSIONS
2544 case glslang::EbtFloat16:
2545 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
2546 builder.addCapability(spv::CapabilityFloat16ImageAMD);
2547 return builder.makeFloatType(16);
2548#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002549 case glslang::EbtInt: return builder.makeIntType(32);
2550 case glslang::EbtUint: return builder.makeUintType(32);
2551 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002552 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002553 return builder.makeFloatType(32);
2554 }
2555}
2556
John Kessenich8c8505c2016-07-26 12:50:38 -06002557// If node is a swizzle operation, return the type that should be used if
2558// the swizzle base is first consumed by another operation, before the swizzle
2559// is applied.
2560spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2561{
John Kessenichecba76f2017-01-06 00:34:48 -07002562 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002563 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2564 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2565 else
2566 return spv::NoType;
2567}
2568
2569// When inverting a swizzle with a parent op, this function
2570// will apply the swizzle operation to a completed parent operation.
2571spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2572{
2573 std::vector<unsigned> swizzle;
2574 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2575 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2576}
2577
John Kessenich8c8505c2016-07-26 12:50:38 -06002578// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2579void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2580{
2581 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2582 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2583 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2584}
2585
John Kessenich3ac051e2015-12-20 11:29:16 -07002586// Convert from a glslang type to an SPV type, by calling into a
2587// recursive version of this function. This establishes the inherited
2588// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002589spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2590{
John Kessenichead86222018-03-28 18:01:20 -06002591 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false);
John Kessenich31ed4832015-09-09 17:51:38 -06002592}
2593
2594// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002595// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002596// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06002597spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
2598 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier, bool lastBufferBlockMember)
John Kessenich31ed4832015-09-09 17:51:38 -06002599{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002600 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002601
2602 switch (type.getBasicType()) {
2603 case glslang::EbtVoid:
2604 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002605 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002606 break;
2607 case glslang::EbtFloat:
2608 spvType = builder.makeFloatType(32);
2609 break;
2610 case glslang::EbtDouble:
2611 spvType = builder.makeFloatType(64);
2612 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002613 case glslang::EbtFloat16:
John Kessenich66011cb2018-03-06 16:12:04 -07002614#if AMD_EXTENSIONS
2615 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2616 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
2617#endif
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002618 spvType = builder.makeFloatType(16);
2619 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002620 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002621 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2622 // a 32-bit int where non-0 means true.
2623 if (explicitLayout != glslang::ElpNone)
2624 spvType = builder.makeUintType(32);
2625 else
2626 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002627 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002628 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07002629 spvType = builder.makeIntType(8);
2630 break;
2631 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07002632 spvType = builder.makeUintType(8);
2633 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002634 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07002635#ifdef AMD_EXTENSIONS
2636 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2637 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2638#endif
2639 spvType = builder.makeIntType(16);
2640 break;
2641 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07002642#ifdef AMD_EXTENSIONS
2643 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2644 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2645#endif
2646 spvType = builder.makeUintType(16);
2647 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002648 case glslang::EbtInt:
2649 spvType = builder.makeIntType(32);
2650 break;
2651 case glslang::EbtUint:
2652 spvType = builder.makeUintType(32);
2653 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002654 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002655 spvType = builder.makeIntType(64);
2656 break;
2657 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002658 spvType = builder.makeUintType(64);
2659 break;
John Kessenich426394d2015-07-23 10:22:48 -06002660 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002661 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002662 spvType = builder.makeUintType(32);
2663 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002664 case glslang::EbtSampler:
2665 {
2666 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002667 if (sampler.sampler) {
2668 // pure sampler
2669 spvType = builder.makeSamplerType();
2670 } else {
2671 // an image is present, make its type
2672 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2673 sampler.image ? 2 : 1, TranslateImageFormat(type));
2674 if (sampler.combined) {
2675 // already has both image and sampler, make the combined type
2676 spvType = builder.makeSampledImageType(spvType);
2677 }
John Kessenich55e7d112015-11-15 21:33:39 -07002678 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002679 }
John Kessenich140f3df2015-06-26 16:58:36 -06002680 break;
2681 case glslang::EbtStruct:
2682 case glslang::EbtBlock:
2683 {
2684 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002685 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002686
2687 // Try to share structs for different layouts, but not yet for other
2688 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002689 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002690 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002691 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002692 break;
2693
2694 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002695 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002696 memberRemapper[glslangMembers].resize(glslangMembers->size());
2697 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002698 }
2699 break;
2700 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002701 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002702 break;
2703 }
2704
2705 if (type.isMatrix())
2706 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2707 else {
2708 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2709 if (type.getVectorSize() > 1)
2710 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2711 }
2712
2713 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002714 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2715
John Kessenichc9a80832015-09-12 12:17:44 -06002716 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002717 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002718 // We need to decorate array strides for types needing explicit layout, except blocks.
2719 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002720 // Use a dummy glslang type for querying internal strides of
2721 // arrays of arrays, but using just a one-dimensional array.
2722 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06002723 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
2724 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07002725
2726 // Will compute the higher-order strides here, rather than making a whole
2727 // pile of types and doing repetitive recursion on their contents.
2728 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2729 }
John Kessenichf8842e52016-01-04 19:22:56 -07002730
2731 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002732 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002733 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002734 if (stride > 0)
2735 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002736 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002737 }
2738 } else {
2739 // single-dimensional array, and don't yet have stride
2740
John Kessenichf8842e52016-01-04 19:22:56 -07002741 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002742 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2743 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002744 }
John Kessenich31ed4832015-09-09 17:51:38 -06002745
John Kessenichead86222018-03-28 18:01:20 -06002746 // Do the outer dimension, which might not be known for a runtime-sized array.
2747 // (Unsized arrays that survive through linking will be runtime-sized arrays)
2748 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07002749 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06002750 else {
2751 if (!lastBufferBlockMember) {
2752 builder.addExtension("SPV_EXT_descriptor_indexing");
2753 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
2754 }
John Kessenichead86222018-03-28 18:01:20 -06002755 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06002756 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002757 if (stride > 0)
2758 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002759 }
2760
2761 return spvType;
2762}
2763
John Kessenich0e737842017-03-24 18:38:16 -06002764// TODO: this functionality should exist at a higher level, in creating the AST
2765//
2766// Identify interface members that don't have their required extension turned on.
2767//
2768bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2769{
2770 auto& extensions = glslangIntermediate->getRequestedExtensions();
2771
Rex Xubcf291a2017-03-29 23:01:36 +08002772 if (member.getFieldName() == "gl_ViewportMask" &&
2773 extensions.find("GL_NV_viewport_array2") == extensions.end())
2774 return true;
2775 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2776 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2777 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002778 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2779 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2780 return true;
2781 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2782 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2783 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002784 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2785 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2786 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002787
2788 return false;
2789};
2790
John Kessenich6090df02016-06-30 21:18:02 -06002791// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2792// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2793// Mutually recursive with convertGlslangToSpvType().
2794spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2795 const glslang::TTypeList* glslangMembers,
2796 glslang::TLayoutPacking explicitLayout,
2797 const glslang::TQualifier& qualifier)
2798{
2799 // Create a vector of struct types for SPIR-V to consume
2800 std::vector<spv::Id> spvMembers;
2801 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 -06002802 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2803 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2804 if (glslangMember.hiddenMember()) {
2805 ++memberDelta;
2806 if (type.getBasicType() == glslang::EbtBlock)
2807 memberRemapper[glslangMembers][i] = -1;
2808 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002809 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002810 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002811 if (filterMember(glslangMember))
2812 continue;
2813 }
John Kessenich6090df02016-06-30 21:18:02 -06002814 // modify just this child's view of the qualifier
2815 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2816 InheritQualifiers(memberQualifier, qualifier);
2817
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002818 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002819 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002820 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002821
2822 // recurse
John Kessenichead86222018-03-28 18:01:20 -06002823 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
2824 i == (int)glslangMembers->size() - 1;
2825 spvMembers.push_back(
2826 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember));
John Kessenich6090df02016-06-30 21:18:02 -06002827 }
2828 }
2829
2830 // Make the SPIR-V type
2831 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002832 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002833 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2834
2835 // Decorate it
2836 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2837
2838 return spvType;
2839}
2840
2841void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2842 const glslang::TTypeList* glslangMembers,
2843 glslang::TLayoutPacking explicitLayout,
2844 const glslang::TQualifier& qualifier,
2845 spv::Id spvType)
2846{
2847 // Name and decorate the non-hidden members
2848 int offset = -1;
2849 int locationOffset = 0; // for use within the members of this struct
2850 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2851 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2852 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002853 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002854 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002855 if (filterMember(glslangMember))
2856 continue;
2857 }
John Kessenich6090df02016-06-30 21:18:02 -06002858
2859 // modify just this child's view of the qualifier
2860 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2861 InheritQualifiers(memberQualifier, qualifier);
2862
2863 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07002864 if (member < 0)
2865 continue;
2866
2867 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2868 builder.addMemberDecoration(spvType, member,
2869 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2870 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2871 // Add interpolation and auxiliary storage decorations only to
2872 // top-level members of Input and Output storage classes
2873 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2874 type.getQualifier().storage == glslang::EvqVaryingOut) {
2875 if (type.getBasicType() == glslang::EbtBlock ||
2876 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
2877 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2878 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002879 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002880 }
2881 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002882
John Kessenich5d610ee2018-03-07 18:05:55 -07002883 if (type.getBasicType() == glslang::EbtBlock &&
2884 qualifier.storage == glslang::EvqBuffer) {
2885 // Add memory decorations only to top-level members of shader storage block
2886 std::vector<spv::Decoration> memory;
2887 TranslateMemoryDecoration(memberQualifier, memory);
2888 for (unsigned int i = 0; i < memory.size(); ++i)
2889 builder.addMemberDecoration(spvType, member, memory[i]);
2890 }
John Kessenich6090df02016-06-30 21:18:02 -06002891
John Kessenich5d610ee2018-03-07 18:05:55 -07002892 // Location assignment was already completed correctly by the front end,
2893 // just track whether a member needs to be decorated.
2894 // Ignore member locations if the container is an array, as that's
2895 // ill-specified and decisions have been made to not allow this.
2896 if (! type.isArray() && memberQualifier.hasLocation())
2897 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002898
John Kessenich5d610ee2018-03-07 18:05:55 -07002899 if (qualifier.hasLocation()) // track for upcoming inheritance
2900 locationOffset += glslangIntermediate->computeTypeLocationSize(
2901 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06002902
John Kessenich5d610ee2018-03-07 18:05:55 -07002903 // component, XFB, others
2904 if (glslangMember.getQualifier().hasComponent())
2905 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
2906 glslangMember.getQualifier().layoutComponent);
2907 if (glslangMember.getQualifier().hasXfbOffset())
2908 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
2909 glslangMember.getQualifier().layoutXfbOffset);
2910 else if (explicitLayout != glslang::ElpNone) {
2911 // figure out what to do with offset, which is accumulating
2912 int nextOffset;
2913 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2914 if (offset >= 0)
2915 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2916 offset = nextOffset;
2917 }
John Kessenich6090df02016-06-30 21:18:02 -06002918
John Kessenich5d610ee2018-03-07 18:05:55 -07002919 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2920 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
2921 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06002922
John Kessenich5d610ee2018-03-07 18:05:55 -07002923 // built-in variable decorations
2924 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
2925 if (builtIn != spv::BuiltInMax)
2926 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002927
John Kessenich5611c6d2018-04-05 11:25:02 -06002928 // nonuniform
2929 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
2930
John Kessenichead86222018-03-28 18:01:20 -06002931 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
2932 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
2933 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
2934 memberQualifier.semanticName);
2935 }
2936
chaoc771d89f2017-01-13 01:10:53 -08002937#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07002938 if (builtIn == spv::BuiltInLayer) {
2939 // SPV_NV_viewport_array2 extension
2940 if (glslangMember.getQualifier().layoutViewportRelative){
2941 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2942 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2943 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08002944 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002945 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2946 builder.addMemberDecoration(spvType, member,
2947 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
2948 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2949 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2950 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08002951 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002952 }
2953 if (glslangMember.getQualifier().layoutPassthrough) {
2954 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2955 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2956 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2957 }
chaoc771d89f2017-01-13 01:10:53 -08002958#endif
John Kessenich6090df02016-06-30 21:18:02 -06002959 }
2960
2961 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07002962 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2963 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002964 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2965 builder.addCapability(spv::CapabilityGeometryStreams);
2966 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2967 }
John Kessenich6090df02016-06-30 21:18:02 -06002968}
2969
John Kessenich6c292d32016-02-15 20:58:50 -07002970// Turn the expression forming the array size into an id.
2971// This is not quite trivial, because of specialization constants.
2972// Sometimes, a raw constant is turned into an Id, and sometimes
2973// a specialization constant expression is.
2974spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2975{
2976 // First, see if this is sized with a node, meaning a specialization constant:
2977 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2978 if (specNode != nullptr) {
2979 builder.clearAccessChain();
2980 specNode->traverse(this);
2981 return accessChainLoad(specNode->getAsTyped()->getType());
2982 }
qining25262b32016-05-06 17:25:16 -04002983
John Kessenich6c292d32016-02-15 20:58:50 -07002984 // Otherwise, need a compile-time (front end) size, get it:
2985 int size = arraySizes.getDimSize(dim);
2986 assert(size > 0);
2987 return builder.makeUintConstant(size);
2988}
2989
John Kessenich103bef92016-02-08 21:38:15 -07002990// Wrap the builder's accessChainLoad to:
2991// - localize handling of RelaxedPrecision
2992// - use the SPIR-V inferred type instead of another conversion of the glslang type
2993// (avoids unnecessary work and possible type punning for structures)
2994// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002995spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2996{
John Kessenich103bef92016-02-08 21:38:15 -07002997 spv::Id nominalTypeId = builder.accessChainGetInferredType();
John Kessenich5611c6d2018-04-05 11:25:02 -06002998 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
2999 TranslateNonUniformDecoration(type.getQualifier()), nominalTypeId);
John Kessenich103bef92016-02-08 21:38:15 -07003000
3001 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003002 if (type.getBasicType() == glslang::EbtBool) {
3003 if (builder.isScalarType(nominalTypeId)) {
3004 // Conversion for bool
3005 spv::Id boolType = builder.makeBoolType();
3006 if (nominalTypeId != boolType)
3007 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3008 } else if (builder.isVectorType(nominalTypeId)) {
3009 // Conversion for bvec
3010 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3011 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3012 if (nominalTypeId != bvecType)
3013 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3014 }
3015 }
John Kessenich103bef92016-02-08 21:38:15 -07003016
3017 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003018}
3019
Rex Xu27253232016-02-23 17:51:09 +08003020// Wrap the builder's accessChainStore to:
3021// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003022//
3023// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003024void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3025{
3026 // Need to convert to abstract types when necessary
3027 if (type.getBasicType() == glslang::EbtBool) {
3028 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3029
3030 if (builder.isScalarType(nominalTypeId)) {
3031 // Conversion for bool
3032 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003033 if (nominalTypeId != boolType) {
3034 // keep these outside arguments, for determinant order-of-evaluation
3035 spv::Id one = builder.makeUintConstant(1);
3036 spv::Id zero = builder.makeUintConstant(0);
3037 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3038 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003039 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003040 } else if (builder.isVectorType(nominalTypeId)) {
3041 // Conversion for bvec
3042 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3043 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003044 if (nominalTypeId != bvecType) {
3045 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003046 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3047 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3048 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003049 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003050 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3051 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003052 }
3053 }
3054
3055 builder.accessChainStore(rvalue);
3056}
3057
John Kessenich4bf71552016-09-02 11:20:21 -06003058// For storing when types match at the glslang level, but not might match at the
3059// SPIR-V level.
3060//
3061// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003062// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003063// as in a member-decorated way.
3064//
3065// NOTE: This function can handle any store request; if it's not special it
3066// simplifies to a simple OpStore.
3067//
3068// Implicitly uses the existing builder.accessChain as the storage target.
3069void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3070{
John Kessenichb3e24e42016-09-11 12:33:43 -06003071 // we only do the complex path here if it's an aggregate
3072 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003073 accessChainStore(type, rValue);
3074 return;
3075 }
3076
John Kessenichb3e24e42016-09-11 12:33:43 -06003077 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003078 spv::Id rType = builder.getTypeId(rValue);
3079 spv::Id lValue = builder.accessChainGetLValue();
3080 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3081 if (lType == rType) {
3082 accessChainStore(type, rValue);
3083 return;
3084 }
3085
John Kessenichb3e24e42016-09-11 12:33:43 -06003086 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003087 // where the two types were the same type in GLSL. This requires member
3088 // by member copy, recursively.
3089
John Kessenichb3e24e42016-09-11 12:33:43 -06003090 // If an array, copy element by element.
3091 if (type.isArray()) {
3092 glslang::TType glslangElementType(type, 0);
3093 spv::Id elementRType = builder.getContainedTypeId(rType);
3094 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3095 // get the source member
3096 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003097
John Kessenichb3e24e42016-09-11 12:33:43 -06003098 // set up the target storage
3099 builder.clearAccessChain();
3100 builder.setAccessChainLValue(lValue);
3101 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06003102
John Kessenichb3e24e42016-09-11 12:33:43 -06003103 // store the member
3104 multiTypeStore(glslangElementType, elementRValue);
3105 }
3106 } else {
3107 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003108
John Kessenichb3e24e42016-09-11 12:33:43 -06003109 // loop over structure members
3110 const glslang::TTypeList& members = *type.getStruct();
3111 for (int m = 0; m < (int)members.size(); ++m) {
3112 const glslang::TType& glslangMemberType = *members[m].type;
3113
3114 // get the source member
3115 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3116 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3117
3118 // set up the target storage
3119 builder.clearAccessChain();
3120 builder.setAccessChainLValue(lValue);
3121 builder.accessChainPush(builder.makeIntConstant(m));
3122
3123 // store the member
3124 multiTypeStore(glslangMemberType, memberRValue);
3125 }
John Kessenich4bf71552016-09-02 11:20:21 -06003126 }
3127}
3128
John Kessenichf85e8062015-12-19 13:57:10 -07003129// Decide whether or not this type should be
3130// decorated with offsets and strides, and if so
3131// whether std140 or std430 rules should be applied.
3132glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003133{
John Kessenichf85e8062015-12-19 13:57:10 -07003134 // has to be a block
3135 if (type.getBasicType() != glslang::EbtBlock)
3136 return glslang::ElpNone;
3137
3138 // has to be a uniform or buffer block
3139 if (type.getQualifier().storage != glslang::EvqUniform &&
3140 type.getQualifier().storage != glslang::EvqBuffer)
3141 return glslang::ElpNone;
3142
3143 // return the layout to use
3144 switch (type.getQualifier().layoutPacking) {
3145 case glslang::ElpStd140:
3146 case glslang::ElpStd430:
3147 return type.getQualifier().layoutPacking;
3148 default:
3149 return glslang::ElpNone;
3150 }
John Kessenich31ed4832015-09-09 17:51:38 -06003151}
3152
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003153// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003154int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003155{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003156 int size;
John Kessenich49987892015-12-29 17:11:44 -07003157 int stride;
3158 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003159
3160 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003161}
3162
John Kessenich49987892015-12-29 17:11:44 -07003163// 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 -07003164// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003165int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003166{
John Kessenich49987892015-12-29 17:11:44 -07003167 glslang::TType elementType;
3168 elementType.shallowCopy(matrixType);
3169 elementType.clearArraySizes();
3170
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003171 int size;
John Kessenich49987892015-12-29 17:11:44 -07003172 int stride;
3173 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
3174
3175 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003176}
3177
John Kessenich5e4b1242015-08-06 22:53:06 -06003178// Given a member type of a struct, realign the current offset for it, and compute
3179// the next (not yet aligned) offset for the next member, which will get aligned
3180// on the next call.
3181// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3182// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3183// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003184void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003185 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003186{
3187 // this will get a positive value when deemed necessary
3188 nextOffset = -1;
3189
John Kessenich5e4b1242015-08-06 22:53:06 -06003190 // override anything in currentOffset with user-set offset
3191 if (memberType.getQualifier().hasOffset())
3192 currentOffset = memberType.getQualifier().layoutOffset;
3193
3194 // It could be that current linker usage in glslang updated all the layoutOffset,
3195 // in which case the following code does not matter. But, that's not quite right
3196 // once cross-compilation unit GLSL validation is done, as the original user
3197 // settings are needed in layoutOffset, and then the following will come into play.
3198
John Kessenichf85e8062015-12-19 13:57:10 -07003199 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003200 if (! memberType.getQualifier().hasOffset())
3201 currentOffset = -1;
3202
3203 return;
3204 }
3205
John Kessenichf85e8062015-12-19 13:57:10 -07003206 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003207 if (currentOffset < 0)
3208 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003209
John Kessenich5e4b1242015-08-06 22:53:06 -06003210 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3211 // but possibly not yet correctly aligned.
3212
3213 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003214 int dummyStride;
3215 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003216
3217 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003218 // TODO: make this consistent in early phases of code:
3219 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3220 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3221 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003222 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003223 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003224 int dummySize;
3225 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3226 if (componentAlignment <= 4)
3227 memberAlignment = componentAlignment;
3228 }
3229
3230 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003231 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003232
3233 // Bump up to vec4 if there is a bad straddle
3234 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
3235 glslang::RoundToPow2(currentOffset, 16);
3236
John Kessenich5e4b1242015-08-06 22:53:06 -06003237 nextOffset = currentOffset + memberSize;
3238}
3239
David Netoa901ffe2016-06-08 14:11:40 +01003240void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003241{
David Netoa901ffe2016-06-08 14:11:40 +01003242 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3243 switch (glslangBuiltIn)
3244 {
3245 case glslang::EbvClipDistance:
3246 case glslang::EbvCullDistance:
3247 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003248#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003249 case glslang::EbvViewportMaskNV:
3250 case glslang::EbvSecondaryPositionNV:
3251 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003252 case glslang::EbvPositionPerViewNV:
3253 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08003254#endif
David Netoa901ffe2016-06-08 14:11:40 +01003255 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3256 // Alternately, we could just call this for any glslang built-in, since the
3257 // capability already guards against duplicates.
3258 TranslateBuiltInDecoration(glslangBuiltIn, false);
3259 break;
3260 default:
3261 // Capabilities were already generated when the struct was declared.
3262 break;
3263 }
John Kessenichebb50532016-05-16 19:22:05 -06003264}
3265
John Kessenich6fccb3c2016-09-19 16:01:41 -06003266bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003267{
John Kessenicheee9d532016-09-19 18:09:30 -06003268 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003269}
3270
John Kessenichd41993d2017-09-10 15:21:05 -06003271// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003272// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3273// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003274bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003275{
John Kessenich6a14f782017-12-04 02:48:10 -07003276 assert(qualifier == glslang::EvqIn ||
3277 qualifier == glslang::EvqOut ||
3278 qualifier == glslang::EvqInOut ||
3279 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003280 return qualifier != glslang::EvqConstReadOnly;
3281}
3282
3283// Is parameter pass-by-original?
3284bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3285 bool implicitThisParam)
3286{
3287 if (implicitThisParam) // implicit this
3288 return true;
3289 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003290 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003291 return paramType.containsOpaque() || // sampler, etc.
3292 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3293}
3294
John Kessenich140f3df2015-06-26 16:58:36 -06003295// Make all the functions, skeletally, without actually visiting their bodies.
3296void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3297{
John Kessenichfad62972017-07-18 02:35:46 -06003298 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
3299 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3300 if (paramPrecision != spv::NoPrecision)
3301 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06003302 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06003303 };
3304
John Kessenich140f3df2015-06-26 16:58:36 -06003305 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3306 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003307 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003308 continue;
3309
3310 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003311 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003312 //
qining25262b32016-05-06 17:25:16 -04003313 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003314 // function. What it is an address of varies:
3315 //
John Kessenich4bf71552016-09-02 11:20:21 -06003316 // - "in" parameters not marked as "const" can be written to without modifying the calling
3317 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003318 //
3319 // - "const in" parameters can just be the r-value, as no writes need occur.
3320 //
John Kessenich4bf71552016-09-02 11:20:21 -06003321 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3322 // 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 -06003323
3324 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003325 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003326 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3327
John Kessenichfad62972017-07-18 02:35:46 -06003328 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3329 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003330
John Kessenichfad62972017-07-18 02:35:46 -06003331 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003332 for (int p = 0; p < (int)parameters.size(); ++p) {
3333 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3334 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003335 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003336 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003337 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003338 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3339 else
John Kessenich4bf71552016-09-02 11:20:21 -06003340 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003341 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003342 paramTypes.push_back(typeId);
3343 }
3344
3345 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003346 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3347 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003348 glslFunction->getName().c_str(), paramTypes,
3349 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003350 if (implicitThis)
3351 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003352
3353 // Track function to emit/call later
3354 functionMap[glslFunction->getName().c_str()] = function;
3355
3356 // Set the parameter id's
3357 for (int p = 0; p < (int)parameters.size(); ++p) {
3358 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3359 // give a name too
3360 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3361 }
3362 }
3363}
3364
3365// Process all the initializers, while skipping the functions and link objects
3366void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3367{
3368 builder.setBuildPoint(shaderEntry->getLastBlock());
3369 for (int i = 0; i < (int)initializers.size(); ++i) {
3370 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3371 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3372
3373 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003374 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003375 initializer->traverse(this);
3376 }
3377 }
3378}
3379
3380// Process all the functions, while skipping initializers.
3381void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3382{
3383 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3384 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003385 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003386 node->traverse(this);
3387 }
3388}
3389
3390void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3391{
qining25262b32016-05-06 17:25:16 -04003392 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003393 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003394 currentFunction = functionMap[node->getName().c_str()];
3395 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003396 builder.setBuildPoint(functionBlock);
3397}
3398
Rex Xu04db3f52015-09-16 11:44:02 +08003399void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003400{
Rex Xufc618912015-09-09 16:42:49 +08003401 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003402
3403 glslang::TSampler sampler = {};
3404 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003405#ifdef AMD_EXTENSIONS
3406 bool f16ShadowCompare = false;
3407#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003408 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003409 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3410 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003411#ifdef AMD_EXTENSIONS
3412 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3413#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003414 }
3415
John Kessenich140f3df2015-06-26 16:58:36 -06003416 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3417 builder.clearAccessChain();
3418 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003419
3420 // Special case l-value operands
3421 bool lvalue = false;
3422 switch (node.getOp()) {
3423 case glslang::EOpImageAtomicAdd:
3424 case glslang::EOpImageAtomicMin:
3425 case glslang::EOpImageAtomicMax:
3426 case glslang::EOpImageAtomicAnd:
3427 case glslang::EOpImageAtomicOr:
3428 case glslang::EOpImageAtomicXor:
3429 case glslang::EOpImageAtomicExchange:
3430 case glslang::EOpImageAtomicCompSwap:
3431 if (i == 0)
3432 lvalue = true;
3433 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003434 case glslang::EOpSparseImageLoad:
3435 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3436 lvalue = true;
3437 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003438#ifdef AMD_EXTENSIONS
3439 case glslang::EOpSparseTexture:
3440 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3441 lvalue = true;
3442 break;
3443 case glslang::EOpSparseTextureClamp:
3444 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3445 lvalue = true;
3446 break;
3447 case glslang::EOpSparseTextureLod:
3448 case glslang::EOpSparseTextureOffset:
3449 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
3450 lvalue = true;
3451 break;
3452#else
Rex Xu48edadf2015-12-31 16:11:41 +08003453 case glslang::EOpSparseTexture:
3454 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3455 lvalue = true;
3456 break;
3457 case glslang::EOpSparseTextureClamp:
3458 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3459 lvalue = true;
3460 break;
3461 case glslang::EOpSparseTextureLod:
3462 case glslang::EOpSparseTextureOffset:
3463 if (i == 3)
3464 lvalue = true;
3465 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003466#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003467 case glslang::EOpSparseTextureFetch:
3468 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3469 lvalue = true;
3470 break;
3471 case glslang::EOpSparseTextureFetchOffset:
3472 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3473 lvalue = true;
3474 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003475#ifdef AMD_EXTENSIONS
3476 case glslang::EOpSparseTextureLodOffset:
3477 case glslang::EOpSparseTextureGrad:
3478 case glslang::EOpSparseTextureOffsetClamp:
3479 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
3480 lvalue = true;
3481 break;
3482 case glslang::EOpSparseTextureGradOffset:
3483 case glslang::EOpSparseTextureGradClamp:
3484 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
3485 lvalue = true;
3486 break;
3487 case glslang::EOpSparseTextureGradOffsetClamp:
3488 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
3489 lvalue = true;
3490 break;
3491#else
Rex Xu48edadf2015-12-31 16:11:41 +08003492 case glslang::EOpSparseTextureLodOffset:
3493 case glslang::EOpSparseTextureGrad:
3494 case glslang::EOpSparseTextureOffsetClamp:
3495 if (i == 4)
3496 lvalue = true;
3497 break;
3498 case glslang::EOpSparseTextureGradOffset:
3499 case glslang::EOpSparseTextureGradClamp:
3500 if (i == 5)
3501 lvalue = true;
3502 break;
3503 case glslang::EOpSparseTextureGradOffsetClamp:
3504 if (i == 6)
3505 lvalue = true;
3506 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003507#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08003508 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003509 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3510 lvalue = true;
3511 break;
3512 case glslang::EOpSparseTextureGatherOffset:
3513 case glslang::EOpSparseTextureGatherOffsets:
3514 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3515 lvalue = true;
3516 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003517#ifdef AMD_EXTENSIONS
3518 case glslang::EOpSparseTextureGatherLod:
3519 if (i == 3)
3520 lvalue = true;
3521 break;
3522 case glslang::EOpSparseTextureGatherLodOffset:
3523 case glslang::EOpSparseTextureGatherLodOffsets:
3524 if (i == 4)
3525 lvalue = true;
3526 break;
Rex Xu129799a2017-07-05 17:23:28 +08003527 case glslang::EOpSparseImageLoadLod:
3528 if (i == 3)
3529 lvalue = true;
3530 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003531#endif
Rex Xufc618912015-09-09 16:42:49 +08003532 default:
3533 break;
3534 }
3535
Rex Xu6b86d492015-09-16 17:48:22 +08003536 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003537 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003538 else
John Kessenich32cfd492016-02-02 12:37:46 -07003539 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003540 }
3541}
3542
John Kessenichfc51d282015-08-19 13:34:18 -06003543void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003544{
John Kessenichfc51d282015-08-19 13:34:18 -06003545 builder.clearAccessChain();
3546 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003547 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003548}
John Kessenich140f3df2015-06-26 16:58:36 -06003549
John Kessenichfc51d282015-08-19 13:34:18 -06003550spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3551{
John Kesseniche485c7a2017-05-31 18:50:53 -06003552 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003553 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003554
3555 builder.setLine(node->getLoc().line);
3556
John Kessenichfc51d282015-08-19 13:34:18 -06003557 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003558 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3559 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08003560#ifdef AMD_EXTENSIONS
3561 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
3562 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
3563 : false;
3564#endif
3565
John Kessenichfc51d282015-08-19 13:34:18 -06003566 std::vector<spv::Id> arguments;
3567 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003568 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003569 else
3570 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003571 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003572
3573 spv::Builder::TextureParameters params = { };
3574 params.sampler = arguments[0];
3575
Rex Xu04db3f52015-09-16 11:44:02 +08003576 glslang::TCrackedTextureOp cracked;
3577 node->crackTexture(sampler, cracked);
3578
amhagan05506bb2017-06-13 16:53:02 -04003579 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003580
John Kessenichfc51d282015-08-19 13:34:18 -06003581 // Check for queries
3582 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003583 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3584 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003585 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003586
John Kessenichfc51d282015-08-19 13:34:18 -06003587 switch (node->getOp()) {
3588 case glslang::EOpImageQuerySize:
3589 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003590 if (arguments.size() > 1) {
3591 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003592 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003593 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003594 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003595 case glslang::EOpImageQuerySamples:
3596 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003597 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003598 case glslang::EOpTextureQueryLod:
3599 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003600 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003601 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003602 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003603 case glslang::EOpSparseTexelsResident:
3604 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003605 default:
3606 assert(0);
3607 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003608 }
John Kessenich140f3df2015-06-26 16:58:36 -06003609 }
3610
LoopDawg4425f242018-02-18 11:40:01 -07003611 int components = node->getType().getVectorSize();
3612
3613 if (node->getOp() == glslang::EOpTextureFetch) {
3614 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3615 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3616 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3617 // here around e.g. which ones return scalars or other types.
3618 components = 4;
3619 }
3620
3621 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3622
3623 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3624
Rex Xufc618912015-09-09 16:42:49 +08003625 // Check for image functions other than queries
3626 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06003627 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06003628 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06003629 spv::IdImmediate image = { true, *(opIt++) };
3630 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07003631
3632 // Handle subpass operations
3633 // TODO: GLSL should change to have the "MS" only on the type rather than the
3634 // built-in function.
3635 if (cracked.subpass) {
3636 // add on the (0,0) coordinate
3637 spv::Id zero = builder.makeIntConstant(0);
3638 std::vector<spv::Id> comps;
3639 comps.push_back(zero);
3640 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06003641 spv::IdImmediate coord = { true,
3642 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
3643 operands.push_back(coord);
John Kessenich6c292d32016-02-15 20:58:50 -07003644 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06003645 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
3646 operands.push_back(imageOperands);
3647 spv::IdImmediate imageOperand = { true, *(opIt++) };
3648 operands.push_back(imageOperand);
John Kessenich6c292d32016-02-15 20:58:50 -07003649 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003650 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3651 builder.setPrecision(result, precision);
3652 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003653 }
3654
John Kessenich149afc32018-08-14 13:31:43 -06003655 spv::IdImmediate coord = { true, *(opIt++) };
3656 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08003657#ifdef AMD_EXTENSIONS
3658 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3659#else
John Kessenich56bab042015-09-16 10:54:31 -06003660 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003661#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003662 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06003663 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
3664 operands.push_back(imageOperands);
3665 spv::IdImmediate imageOperand = { true, *opIt };
3666 operands.push_back(imageOperand);
Rex Xu129799a2017-07-05 17:23:28 +08003667#ifdef AMD_EXTENSIONS
3668 } else if (cracked.lod) {
3669 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3670 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3671
John Kessenich149afc32018-08-14 13:31:43 -06003672 spv::IdImmediate imageOperands = { false, spv::ImageOperandsLodMask };
3673 operands.push_back(imageOperands);
3674 spv::IdImmediate imageOperand = { true, *opIt };
3675 operands.push_back(imageOperand);
Rex Xu129799a2017-07-05 17:23:28 +08003676#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003677 }
John Kessenich149afc32018-08-14 13:31:43 -06003678 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07003679 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003680
John Kessenich149afc32018-08-14 13:31:43 -06003681 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07003682 builder.setPrecision(result[0], precision);
3683
3684 // If needed, add a conversion constructor to the proper size.
3685 if (components != node->getType().getVectorSize())
3686 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3687
3688 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08003689#ifdef AMD_EXTENSIONS
3690 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3691#else
John Kessenich56bab042015-09-16 10:54:31 -06003692 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003693#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003694 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06003695 spv::IdImmediate texel = { true, *(opIt + 1) };
3696 operands.push_back(texel);
3697 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
3698 operands.push_back(imageOperands);
3699 spv::IdImmediate imageOperand = { true, *opIt };
3700 operands.push_back(imageOperand);
Rex Xu129799a2017-07-05 17:23:28 +08003701#ifdef AMD_EXTENSIONS
3702 } else if (cracked.lod) {
3703 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3704 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3705
John Kessenich149afc32018-08-14 13:31:43 -06003706 spv::IdImmediate texel = { true, *(opIt + 1) };
3707 operands.push_back(texel);
3708 spv::IdImmediate imageOperands = { false, spv::ImageOperandsLodMask };
3709 operands.push_back(imageOperands);
3710 spv::IdImmediate imageOperand = { true, *opIt };
3711 operands.push_back(imageOperand);
Rex Xu129799a2017-07-05 17:23:28 +08003712#endif
John Kessenich149afc32018-08-14 13:31:43 -06003713 } else {
3714 spv::IdImmediate texel = { true, *opIt };
3715 operands.push_back(texel);
3716 }
John Kessenich56bab042015-09-16 10:54:31 -06003717 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06003718 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07003719 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003720 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003721#ifdef AMD_EXTENSIONS
3722 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3723#else
Rex Xu5eafa472016-02-19 22:24:03 +08003724 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003725#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003726 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06003727 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08003728 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3729
3730 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06003731 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
3732 operands.push_back(imageOperands);
3733 spv::IdImmediate imageOperand = { true, *opIt++ };
3734 operands.push_back(imageOperand);
Rex Xu129799a2017-07-05 17:23:28 +08003735#ifdef AMD_EXTENSIONS
3736 } else if (cracked.lod) {
3737 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3738 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3739
John Kessenich149afc32018-08-14 13:31:43 -06003740 spv::IdImmediate imageOperands = { false, spv::ImageOperandsLodMask };
3741 operands.push_back(imageOperands);
3742 spv::IdImmediate imageOperand = { true, *opIt++ };
3743 operands.push_back(imageOperand);
Rex Xu129799a2017-07-05 17:23:28 +08003744#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003745 }
3746
3747 // Create the return type that was a special structure
3748 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003749 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003750 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3751 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3752
3753 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3754
3755 // Decode the return type
3756 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3757 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003758 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003759 // Process image atomic operations
3760
3761 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3762 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06003763 // For non-MS, the sample value should be 0
3764 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
3765 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06003766
John Kessenich8c8505c2016-07-26 12:50:38 -06003767 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003768 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003769
3770 std::vector<spv::Id> operands;
3771 operands.push_back(pointer);
3772 for (; opIt != arguments.end(); ++opIt)
3773 operands.push_back(*opIt);
3774
John Kessenich8c8505c2016-07-26 12:50:38 -06003775 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003776 }
3777 }
3778
amhagan05506bb2017-06-13 16:53:02 -04003779#ifdef AMD_EXTENSIONS
3780 // Check for fragment mask functions other than queries
3781 if (cracked.fragMask) {
3782 assert(sampler.ms);
3783
3784 auto opIt = arguments.begin();
3785 std::vector<spv::Id> operands;
3786
3787 // Extract the image if necessary
3788 if (builder.isSampledImage(params.sampler))
3789 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3790
3791 operands.push_back(params.sampler);
3792 ++opIt;
3793
3794 if (sampler.isSubpass()) {
3795 // add on the (0,0) coordinate
3796 spv::Id zero = builder.makeIntConstant(0);
3797 std::vector<spv::Id> comps;
3798 comps.push_back(zero);
3799 comps.push_back(zero);
3800 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3801 }
3802
3803 for (; opIt != arguments.end(); ++opIt)
3804 operands.push_back(*opIt);
3805
3806 spv::Op fragMaskOp = spv::OpNop;
3807 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3808 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3809 else if (node->getOp() == glslang::EOpFragmentFetch)
3810 fragMaskOp = spv::OpFragmentFetchAMD;
3811
3812 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3813 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3814 return builder.createOp(fragMaskOp, resultType(), operands);
3815 }
3816#endif
3817
Rex Xufc618912015-09-09 16:42:49 +08003818 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003819 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003820 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3821
John Kessenichfc51d282015-08-19 13:34:18 -06003822 // check for bias argument
3823 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003824#ifdef AMD_EXTENSIONS
3825 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3826#else
Rex Xu71519fe2015-11-11 15:35:47 +08003827 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003828#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003829 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003830#ifdef AMD_EXTENSIONS
3831 if (cracked.gather)
3832 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08003833
3834 if (f16ShadowCompare)
3835 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003836#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003837 if (cracked.offset)
3838 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003839#ifdef AMD_EXTENSIONS
3840 else if (cracked.offsets)
3841 ++nonBiasArgCount;
3842#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003843 if (cracked.grad)
3844 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003845 if (cracked.lodClamp)
3846 ++nonBiasArgCount;
3847 if (sparse)
3848 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003849
3850 if ((int)arguments.size() > nonBiasArgCount)
3851 bias = true;
3852 }
3853
John Kessenicha5c33d62016-06-02 23:45:21 -06003854 // See if the sampler param should really be just the SPV image part
3855 if (cracked.fetch) {
3856 // a fetch needs to have the image extracted first
3857 if (builder.isSampledImage(params.sampler))
3858 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3859 }
3860
Rex Xu225e0fc2016-11-17 17:47:59 +08003861#ifdef AMD_EXTENSIONS
3862 if (cracked.gather) {
3863 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3864 if (bias || cracked.lod ||
3865 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3866 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003867 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003868 }
3869 }
3870#endif
3871
John Kessenichfc51d282015-08-19 13:34:18 -06003872 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003873
John Kessenichfc51d282015-08-19 13:34:18 -06003874 params.coords = arguments[1];
3875 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003876 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003877
3878 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08003879#ifdef AMD_EXTENSIONS
3880 if (cubeCompare || f16ShadowCompare) {
3881#else
Rex Xu48edadf2015-12-31 16:11:41 +08003882 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08003883#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003884 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003885 ++extraArgs;
3886 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003887 params.Dref = arguments[2];
3888 ++extraArgs;
3889 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003890 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003891 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003892 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003893 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003894 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003895 dRefComp = builder.getNumComponents(params.coords) - 1;
3896 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003897 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3898 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003899
3900 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003901 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003902 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003903 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003904 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3905 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3906 noImplicitLod = true;
3907 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003908
3909 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003910 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003911 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003912 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003913 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003914
3915 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003916 if (cracked.grad) {
3917 params.gradX = arguments[2 + extraArgs];
3918 params.gradY = arguments[3 + extraArgs];
3919 extraArgs += 2;
3920 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003921
3922 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003923 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003924 params.offset = arguments[2 + extraArgs];
3925 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003926 } else if (cracked.offsets) {
3927 params.offsets = arguments[2 + extraArgs];
3928 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003929 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003930
3931 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003932 if (cracked.lodClamp) {
3933 params.lodClamp = arguments[2 + extraArgs];
3934 ++extraArgs;
3935 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003936
3937 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003938 if (sparse) {
3939 params.texelOut = arguments[2 + extraArgs];
3940 ++extraArgs;
3941 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003942
John Kessenich76d4dfc2016-06-16 12:43:23 -06003943 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003944 if (cracked.gather && ! sampler.shadow) {
3945 // default component is 0, if missing, otherwise an argument
3946 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003947 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003948 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003949 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003950 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003951 }
3952
3953 // bias
3954 if (bias) {
3955 params.bias = arguments[2 + extraArgs];
3956 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003957 }
John Kessenichfc51d282015-08-19 13:34:18 -06003958
John Kessenich65336482016-06-16 14:06:26 -06003959 // projective component (might not to move)
3960 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3961 // are divided by the last component of P."
3962 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3963 // unused components will appear after all used components."
3964 if (cracked.proj) {
3965 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3966 int projTargetComp;
3967 switch (sampler.dim) {
3968 case glslang::Esd1D: projTargetComp = 1; break;
3969 case glslang::Esd2D: projTargetComp = 2; break;
3970 case glslang::EsdRect: projTargetComp = 2; break;
3971 default: projTargetComp = projSourceComp; break;
3972 }
3973 // copy the projective coordinate if we have to
3974 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003975 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003976 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3977 projSourceComp);
3978 params.coords = builder.createCompositeInsert(projComp, params.coords,
3979 builder.getTypeId(params.coords), projTargetComp);
3980 }
3981 }
3982
St0fFa1184dd2018-04-09 21:08:14 +02003983 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07003984 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02003985 );
LoopDawg4425f242018-02-18 11:40:01 -07003986
3987 if (components != node->getType().getVectorSize())
3988 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3989
3990 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06003991}
3992
3993spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3994{
3995 // Grab the function's pointer from the previously created function
3996 spv::Function* function = functionMap[node->getName().c_str()];
3997 if (! function)
3998 return 0;
3999
4000 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4001 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4002
4003 // See comments in makeFunctions() for details about the semantics for parameter passing.
4004 //
4005 // These imply we need a four step process:
4006 // 1. Evaluate the arguments
4007 // 2. Allocate and make copies of in, out, and inout arguments
4008 // 3. Make the call
4009 // 4. Copy back the results
4010
John Kessenichd3ed90b2018-05-04 11:43:03 -06004011 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004012 std::vector<spv::Builder::AccessChain> lValues;
4013 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004014 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004015 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004016 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004017 // build l-value
4018 builder.clearAccessChain();
4019 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004020 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004021 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004022 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004023 // save l-value
4024 lValues.push_back(builder.getAccessChain());
4025 } else {
4026 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004027 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004028 }
4029 }
4030
4031 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4032 // copy the original into that space.
4033 //
4034 // Also, build up the list of actual arguments to pass in for the call
4035 int lValueCount = 0;
4036 int rValueCount = 0;
4037 std::vector<spv::Id> spvArgs;
4038 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4039 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004040 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004041 builder.setAccessChain(lValues[lValueCount]);
4042 arg = builder.accessChainGetLValue();
4043 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004044 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004045 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004046 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004047 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4048 // need to copy the input into output space
4049 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004050 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004051 builder.clearAccessChain();
4052 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004053 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004054 }
4055 ++lValueCount;
4056 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004057 // process r-value, which involves a copy for a type mismatch
4058 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4059 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4060 builder.clearAccessChain();
4061 builder.setAccessChainLValue(argCopy);
4062 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4063 arg = builder.createLoad(argCopy);
4064 } else
4065 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004066 ++rValueCount;
4067 }
4068 spvArgs.push_back(arg);
4069 }
4070
4071 // 3. Make the call.
4072 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004073 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004074
4075 // 4. Copy back out an "out" arguments.
4076 lValueCount = 0;
4077 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004078 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004079 ++lValueCount;
4080 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004081 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4082 spv::Id copy = builder.createLoad(spvArgs[a]);
4083 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004084 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004085 }
4086 ++lValueCount;
4087 }
4088 }
4089
4090 return result;
4091}
4092
4093// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004094spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004095 spv::Id typeId, spv::Id left, spv::Id right,
4096 glslang::TBasicType typeProxy, bool reduceComparison)
4097{
John Kessenich66011cb2018-03-06 16:12:04 -07004098 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4099 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004100 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004101
4102 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004103 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004104 bool comparison = false;
4105
4106 switch (op) {
4107 case glslang::EOpAdd:
4108 case glslang::EOpAddAssign:
4109 if (isFloat)
4110 binOp = spv::OpFAdd;
4111 else
4112 binOp = spv::OpIAdd;
4113 break;
4114 case glslang::EOpSub:
4115 case glslang::EOpSubAssign:
4116 if (isFloat)
4117 binOp = spv::OpFSub;
4118 else
4119 binOp = spv::OpISub;
4120 break;
4121 case glslang::EOpMul:
4122 case glslang::EOpMulAssign:
4123 if (isFloat)
4124 binOp = spv::OpFMul;
4125 else
4126 binOp = spv::OpIMul;
4127 break;
4128 case glslang::EOpVectorTimesScalar:
4129 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004130 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004131 if (builder.isVector(right))
4132 std::swap(left, right);
4133 assert(builder.isScalar(right));
4134 needMatchingVectors = false;
4135 binOp = spv::OpVectorTimesScalar;
4136 } else
4137 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004138 break;
4139 case glslang::EOpVectorTimesMatrix:
4140 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004141 binOp = spv::OpVectorTimesMatrix;
4142 break;
4143 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004144 binOp = spv::OpMatrixTimesVector;
4145 break;
4146 case glslang::EOpMatrixTimesScalar:
4147 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004148 binOp = spv::OpMatrixTimesScalar;
4149 break;
4150 case glslang::EOpMatrixTimesMatrix:
4151 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004152 binOp = spv::OpMatrixTimesMatrix;
4153 break;
4154 case glslang::EOpOuterProduct:
4155 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004156 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004157 break;
4158
4159 case glslang::EOpDiv:
4160 case glslang::EOpDivAssign:
4161 if (isFloat)
4162 binOp = spv::OpFDiv;
4163 else if (isUnsigned)
4164 binOp = spv::OpUDiv;
4165 else
4166 binOp = spv::OpSDiv;
4167 break;
4168 case glslang::EOpMod:
4169 case glslang::EOpModAssign:
4170 if (isFloat)
4171 binOp = spv::OpFMod;
4172 else if (isUnsigned)
4173 binOp = spv::OpUMod;
4174 else
4175 binOp = spv::OpSMod;
4176 break;
4177 case glslang::EOpRightShift:
4178 case glslang::EOpRightShiftAssign:
4179 if (isUnsigned)
4180 binOp = spv::OpShiftRightLogical;
4181 else
4182 binOp = spv::OpShiftRightArithmetic;
4183 break;
4184 case glslang::EOpLeftShift:
4185 case glslang::EOpLeftShiftAssign:
4186 binOp = spv::OpShiftLeftLogical;
4187 break;
4188 case glslang::EOpAnd:
4189 case glslang::EOpAndAssign:
4190 binOp = spv::OpBitwiseAnd;
4191 break;
4192 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004193 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004194 binOp = spv::OpLogicalAnd;
4195 break;
4196 case glslang::EOpInclusiveOr:
4197 case glslang::EOpInclusiveOrAssign:
4198 binOp = spv::OpBitwiseOr;
4199 break;
4200 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004201 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004202 binOp = spv::OpLogicalOr;
4203 break;
4204 case glslang::EOpExclusiveOr:
4205 case glslang::EOpExclusiveOrAssign:
4206 binOp = spv::OpBitwiseXor;
4207 break;
4208 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004209 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004210 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004211 break;
4212
4213 case glslang::EOpLessThan:
4214 case glslang::EOpGreaterThan:
4215 case glslang::EOpLessThanEqual:
4216 case glslang::EOpGreaterThanEqual:
4217 case glslang::EOpEqual:
4218 case glslang::EOpNotEqual:
4219 case glslang::EOpVectorEqual:
4220 case glslang::EOpVectorNotEqual:
4221 comparison = true;
4222 break;
4223 default:
4224 break;
4225 }
4226
John Kessenich7c1aa102015-10-15 13:29:11 -06004227 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004228 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004229 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07004230 if (builder.isMatrix(left) || builder.isMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004231 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004232
4233 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004234 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004235 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004236
qining25262b32016-05-06 17:25:16 -04004237 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004238 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004239 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004240 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004241 }
4242
4243 if (! comparison)
4244 return 0;
4245
John Kessenich7c1aa102015-10-15 13:29:11 -06004246 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004247
John Kessenich4583b612016-08-07 19:14:22 -06004248 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004249 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4250 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004251 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004252 return result;
4253 }
John Kessenich140f3df2015-06-26 16:58:36 -06004254
4255 switch (op) {
4256 case glslang::EOpLessThan:
4257 if (isFloat)
4258 binOp = spv::OpFOrdLessThan;
4259 else if (isUnsigned)
4260 binOp = spv::OpULessThan;
4261 else
4262 binOp = spv::OpSLessThan;
4263 break;
4264 case glslang::EOpGreaterThan:
4265 if (isFloat)
4266 binOp = spv::OpFOrdGreaterThan;
4267 else if (isUnsigned)
4268 binOp = spv::OpUGreaterThan;
4269 else
4270 binOp = spv::OpSGreaterThan;
4271 break;
4272 case glslang::EOpLessThanEqual:
4273 if (isFloat)
4274 binOp = spv::OpFOrdLessThanEqual;
4275 else if (isUnsigned)
4276 binOp = spv::OpULessThanEqual;
4277 else
4278 binOp = spv::OpSLessThanEqual;
4279 break;
4280 case glslang::EOpGreaterThanEqual:
4281 if (isFloat)
4282 binOp = spv::OpFOrdGreaterThanEqual;
4283 else if (isUnsigned)
4284 binOp = spv::OpUGreaterThanEqual;
4285 else
4286 binOp = spv::OpSGreaterThanEqual;
4287 break;
4288 case glslang::EOpEqual:
4289 case glslang::EOpVectorEqual:
4290 if (isFloat)
4291 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004292 else if (isBool)
4293 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004294 else
4295 binOp = spv::OpIEqual;
4296 break;
4297 case glslang::EOpNotEqual:
4298 case glslang::EOpVectorNotEqual:
4299 if (isFloat)
4300 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004301 else if (isBool)
4302 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004303 else
4304 binOp = spv::OpINotEqual;
4305 break;
4306 default:
4307 break;
4308 }
4309
qining25262b32016-05-06 17:25:16 -04004310 if (binOp != spv::OpNop) {
4311 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004312 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004313 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004314 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004315 }
John Kessenich140f3df2015-06-26 16:58:36 -06004316
4317 return 0;
4318}
4319
John Kessenich04bb8a02015-12-12 12:28:14 -07004320//
4321// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
4322// These can be any of:
4323//
4324// matrix * scalar
4325// scalar * matrix
4326// matrix * matrix linear algebraic
4327// matrix * vector
4328// vector * matrix
4329// matrix * matrix componentwise
4330// matrix op matrix op in {+, -, /}
4331// matrix op scalar op in {+, -, /}
4332// scalar op matrix op in {+, -, /}
4333//
John Kessenichead86222018-03-28 18:01:20 -06004334spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4335 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07004336{
4337 bool firstClass = true;
4338
4339 // First, handle first-class matrix operations (* and matrix/scalar)
4340 switch (op) {
4341 case spv::OpFDiv:
4342 if (builder.isMatrix(left) && builder.isScalar(right)) {
4343 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01004344 spv::Id resultType = builder.getTypeId(right);
4345 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07004346 op = spv::OpMatrixTimesScalar;
4347 } else
4348 firstClass = false;
4349 break;
4350 case spv::OpMatrixTimesScalar:
4351 if (builder.isMatrix(right))
4352 std::swap(left, right);
4353 assert(builder.isScalar(right));
4354 break;
4355 case spv::OpVectorTimesMatrix:
4356 assert(builder.isVector(left));
4357 assert(builder.isMatrix(right));
4358 break;
4359 case spv::OpMatrixTimesVector:
4360 assert(builder.isMatrix(left));
4361 assert(builder.isVector(right));
4362 break;
4363 case spv::OpMatrixTimesMatrix:
4364 assert(builder.isMatrix(left));
4365 assert(builder.isMatrix(right));
4366 break;
4367 default:
4368 firstClass = false;
4369 break;
4370 }
4371
qining25262b32016-05-06 17:25:16 -04004372 if (firstClass) {
4373 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004374 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004375 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004376 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004377 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004378
LoopDawg592860c2016-06-09 08:57:35 -06004379 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004380 // The result type of all of them is the same type as the (a) matrix operand.
4381 // The algorithm is to:
4382 // - break the matrix(es) into vectors
4383 // - smear any scalar to a vector
4384 // - do vector operations
4385 // - make a matrix out the vector results
4386 switch (op) {
4387 case spv::OpFAdd:
4388 case spv::OpFSub:
4389 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004390 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004391 case spv::OpFMul:
4392 {
4393 // one time set up...
4394 bool leftMat = builder.isMatrix(left);
4395 bool rightMat = builder.isMatrix(right);
4396 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4397 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4398 spv::Id scalarType = builder.getScalarTypeId(typeId);
4399 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4400 std::vector<spv::Id> results;
4401 spv::Id smearVec = spv::NoResult;
4402 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06004403 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004404 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06004405 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004406
4407 // do each vector op
4408 for (unsigned int c = 0; c < numCols; ++c) {
4409 std::vector<unsigned int> indexes;
4410 indexes.push_back(c);
4411 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4412 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004413 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06004414 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004415 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004416 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004417 }
4418
4419 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004420 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004421 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004422 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07004423 }
4424 default:
4425 assert(0);
4426 return spv::NoResult;
4427 }
4428}
4429
John Kessenichead86222018-03-28 18:01:20 -06004430spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
4431 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004432{
4433 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004434 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004435 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07004436 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4437 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004438
4439 switch (op) {
4440 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004441 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004442 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004443 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06004444 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004445 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004446 unaryOp = spv::OpSNegate;
4447 break;
4448
4449 case glslang::EOpLogicalNot:
4450 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004451 unaryOp = spv::OpLogicalNot;
4452 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004453 case glslang::EOpBitwiseNot:
4454 unaryOp = spv::OpNot;
4455 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004456
John Kessenich140f3df2015-06-26 16:58:36 -06004457 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004458 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004459 break;
4460 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004461 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004462 break;
4463 case glslang::EOpTranspose:
4464 unaryOp = spv::OpTranspose;
4465 break;
4466
4467 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004468 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004469 break;
4470 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004471 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004472 break;
4473 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004474 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004475 break;
4476 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004477 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004478 break;
4479 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004480 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004481 break;
4482 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004483 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004484 break;
4485 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004486 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004487 break;
4488 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004489 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004490 break;
4491
4492 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004493 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004494 break;
4495 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004496 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004497 break;
4498 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004499 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004500 break;
4501 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004502 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004503 break;
4504 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004505 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004506 break;
4507 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004508 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004509 break;
4510
4511 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004512 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004513 break;
4514 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004515 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004516 break;
4517
4518 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004519 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004520 break;
4521 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004522 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004523 break;
4524 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004525 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004526 break;
4527 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004528 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004529 break;
4530 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004531 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004532 break;
4533 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004534 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004535 break;
4536
4537 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004538 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004539 break;
4540 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004541 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004542 break;
4543 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004544 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004545 break;
4546 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004547 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004548 break;
4549 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004550 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004551 break;
4552 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004553 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004554 break;
4555
4556 case glslang::EOpIsNan:
4557 unaryOp = spv::OpIsNan;
4558 break;
4559 case glslang::EOpIsInf:
4560 unaryOp = spv::OpIsInf;
4561 break;
LoopDawg592860c2016-06-09 08:57:35 -06004562 case glslang::EOpIsFinite:
4563 unaryOp = spv::OpIsFinite;
4564 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004565
Rex Xucbc426e2015-12-15 16:03:10 +08004566 case glslang::EOpFloatBitsToInt:
4567 case glslang::EOpFloatBitsToUint:
4568 case glslang::EOpIntBitsToFloat:
4569 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004570 case glslang::EOpDoubleBitsToInt64:
4571 case glslang::EOpDoubleBitsToUint64:
4572 case glslang::EOpInt64BitsToDouble:
4573 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004574 case glslang::EOpFloat16BitsToInt16:
4575 case glslang::EOpFloat16BitsToUint16:
4576 case glslang::EOpInt16BitsToFloat16:
4577 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08004578 unaryOp = spv::OpBitcast;
4579 break;
4580
John Kessenich140f3df2015-06-26 16:58:36 -06004581 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004582 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004583 break;
4584 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004585 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004586 break;
4587 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004588 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004589 break;
4590 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004591 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004592 break;
4593 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004594 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004595 break;
4596 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004597 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004598 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004599 case glslang::EOpPackSnorm4x8:
4600 libCall = spv::GLSLstd450PackSnorm4x8;
4601 break;
4602 case glslang::EOpUnpackSnorm4x8:
4603 libCall = spv::GLSLstd450UnpackSnorm4x8;
4604 break;
4605 case glslang::EOpPackUnorm4x8:
4606 libCall = spv::GLSLstd450PackUnorm4x8;
4607 break;
4608 case glslang::EOpUnpackUnorm4x8:
4609 libCall = spv::GLSLstd450UnpackUnorm4x8;
4610 break;
4611 case glslang::EOpPackDouble2x32:
4612 libCall = spv::GLSLstd450PackDouble2x32;
4613 break;
4614 case glslang::EOpUnpackDouble2x32:
4615 libCall = spv::GLSLstd450UnpackDouble2x32;
4616 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004617
Rex Xu8ff43de2016-04-22 16:51:45 +08004618 case glslang::EOpPackInt2x32:
4619 case glslang::EOpUnpackInt2x32:
4620 case glslang::EOpPackUint2x32:
4621 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07004622 case glslang::EOpPack16:
4623 case glslang::EOpPack32:
4624 case glslang::EOpPack64:
4625 case glslang::EOpUnpack32:
4626 case glslang::EOpUnpack16:
4627 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08004628 case glslang::EOpPackInt2x16:
4629 case glslang::EOpUnpackInt2x16:
4630 case glslang::EOpPackUint2x16:
4631 case glslang::EOpUnpackUint2x16:
4632 case glslang::EOpPackInt4x16:
4633 case glslang::EOpUnpackInt4x16:
4634 case glslang::EOpPackUint4x16:
4635 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004636 case glslang::EOpPackFloat2x16:
4637 case glslang::EOpUnpackFloat2x16:
4638 unaryOp = spv::OpBitcast;
4639 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004640
John Kessenich140f3df2015-06-26 16:58:36 -06004641 case glslang::EOpDPdx:
4642 unaryOp = spv::OpDPdx;
4643 break;
4644 case glslang::EOpDPdy:
4645 unaryOp = spv::OpDPdy;
4646 break;
4647 case glslang::EOpFwidth:
4648 unaryOp = spv::OpFwidth;
4649 break;
4650 case glslang::EOpDPdxFine:
4651 unaryOp = spv::OpDPdxFine;
4652 break;
4653 case glslang::EOpDPdyFine:
4654 unaryOp = spv::OpDPdyFine;
4655 break;
4656 case glslang::EOpFwidthFine:
4657 unaryOp = spv::OpFwidthFine;
4658 break;
4659 case glslang::EOpDPdxCoarse:
4660 unaryOp = spv::OpDPdxCoarse;
4661 break;
4662 case glslang::EOpDPdyCoarse:
4663 unaryOp = spv::OpDPdyCoarse;
4664 break;
4665 case glslang::EOpFwidthCoarse:
4666 unaryOp = spv::OpFwidthCoarse;
4667 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004668 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08004669#ifdef AMD_EXTENSIONS
4670 if (typeProxy == glslang::EbtFloat16)
4671 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
4672#endif
Rex Xu7a26c172015-12-08 17:12:09 +08004673 libCall = spv::GLSLstd450InterpolateAtCentroid;
4674 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004675 case glslang::EOpAny:
4676 unaryOp = spv::OpAny;
4677 break;
4678 case glslang::EOpAll:
4679 unaryOp = spv::OpAll;
4680 break;
4681
4682 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004683 if (isFloat)
4684 libCall = spv::GLSLstd450FAbs;
4685 else
4686 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004687 break;
4688 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004689 if (isFloat)
4690 libCall = spv::GLSLstd450FSign;
4691 else
4692 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004693 break;
4694
John Kessenichfc51d282015-08-19 13:34:18 -06004695 case glslang::EOpAtomicCounterIncrement:
4696 case glslang::EOpAtomicCounterDecrement:
4697 case glslang::EOpAtomicCounter:
4698 {
4699 // Handle all of the atomics in one place, in createAtomicOperation()
4700 std::vector<spv::Id> operands;
4701 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06004702 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004703 }
4704
John Kessenichfc51d282015-08-19 13:34:18 -06004705 case glslang::EOpBitFieldReverse:
4706 unaryOp = spv::OpBitReverse;
4707 break;
4708 case glslang::EOpBitCount:
4709 unaryOp = spv::OpBitCount;
4710 break;
4711 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004712 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004713 break;
4714 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004715 if (isUnsigned)
4716 libCall = spv::GLSLstd450FindUMsb;
4717 else
4718 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004719 break;
4720
Rex Xu574ab042016-04-14 16:53:07 +08004721 case glslang::EOpBallot:
4722 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004723 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004724 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004725 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004726#ifdef AMD_EXTENSIONS
4727 case glslang::EOpMinInvocations:
4728 case glslang::EOpMaxInvocations:
4729 case glslang::EOpAddInvocations:
4730 case glslang::EOpMinInvocationsNonUniform:
4731 case glslang::EOpMaxInvocationsNonUniform:
4732 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004733 case glslang::EOpMinInvocationsInclusiveScan:
4734 case glslang::EOpMaxInvocationsInclusiveScan:
4735 case glslang::EOpAddInvocationsInclusiveScan:
4736 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4737 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4738 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4739 case glslang::EOpMinInvocationsExclusiveScan:
4740 case glslang::EOpMaxInvocationsExclusiveScan:
4741 case glslang::EOpAddInvocationsExclusiveScan:
4742 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4743 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4744 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004745#endif
Rex Xu51596642016-09-21 18:56:12 +08004746 {
4747 std::vector<spv::Id> operands;
4748 operands.push_back(operand);
4749 return createInvocationsOperation(op, typeId, operands, typeProxy);
4750 }
John Kessenich66011cb2018-03-06 16:12:04 -07004751 case glslang::EOpSubgroupAll:
4752 case glslang::EOpSubgroupAny:
4753 case glslang::EOpSubgroupAllEqual:
4754 case glslang::EOpSubgroupBroadcastFirst:
4755 case glslang::EOpSubgroupBallot:
4756 case glslang::EOpSubgroupInverseBallot:
4757 case glslang::EOpSubgroupBallotBitCount:
4758 case glslang::EOpSubgroupBallotInclusiveBitCount:
4759 case glslang::EOpSubgroupBallotExclusiveBitCount:
4760 case glslang::EOpSubgroupBallotFindLSB:
4761 case glslang::EOpSubgroupBallotFindMSB:
4762 case glslang::EOpSubgroupAdd:
4763 case glslang::EOpSubgroupMul:
4764 case glslang::EOpSubgroupMin:
4765 case glslang::EOpSubgroupMax:
4766 case glslang::EOpSubgroupAnd:
4767 case glslang::EOpSubgroupOr:
4768 case glslang::EOpSubgroupXor:
4769 case glslang::EOpSubgroupInclusiveAdd:
4770 case glslang::EOpSubgroupInclusiveMul:
4771 case glslang::EOpSubgroupInclusiveMin:
4772 case glslang::EOpSubgroupInclusiveMax:
4773 case glslang::EOpSubgroupInclusiveAnd:
4774 case glslang::EOpSubgroupInclusiveOr:
4775 case glslang::EOpSubgroupInclusiveXor:
4776 case glslang::EOpSubgroupExclusiveAdd:
4777 case glslang::EOpSubgroupExclusiveMul:
4778 case glslang::EOpSubgroupExclusiveMin:
4779 case glslang::EOpSubgroupExclusiveMax:
4780 case glslang::EOpSubgroupExclusiveAnd:
4781 case glslang::EOpSubgroupExclusiveOr:
4782 case glslang::EOpSubgroupExclusiveXor:
4783 case glslang::EOpSubgroupQuadSwapHorizontal:
4784 case glslang::EOpSubgroupQuadSwapVertical:
4785 case glslang::EOpSubgroupQuadSwapDiagonal: {
4786 std::vector<spv::Id> operands;
4787 operands.push_back(operand);
4788 return createSubgroupOperation(op, typeId, operands, typeProxy);
4789 }
Rex Xu9d93a232016-05-05 12:30:44 +08004790#ifdef AMD_EXTENSIONS
4791 case glslang::EOpMbcnt:
4792 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4793 libCall = spv::MbcntAMD;
4794 break;
4795
4796 case glslang::EOpCubeFaceIndex:
4797 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4798 libCall = spv::CubeFaceIndexAMD;
4799 break;
4800
4801 case glslang::EOpCubeFaceCoord:
4802 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4803 libCall = spv::CubeFaceCoordAMD;
4804 break;
4805#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05004806#ifdef NV_EXTENSIONS
4807 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05004808 unaryOp = spv::OpGroupNonUniformPartitionNV;
4809 break;
4810#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004811 default:
4812 return 0;
4813 }
4814
4815 spv::Id id;
4816 if (libCall >= 0) {
4817 std::vector<spv::Id> args;
4818 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004819 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004820 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004821 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004822 }
John Kessenich140f3df2015-06-26 16:58:36 -06004823
John Kessenichead86222018-03-28 18:01:20 -06004824 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004825 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004826 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004827}
4828
John Kessenich7a53f762016-01-20 11:19:27 -07004829// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06004830spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4831 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07004832{
4833 // Handle unary operations vector by vector.
4834 // The result type is the same type as the original type.
4835 // The algorithm is to:
4836 // - break the matrix into vectors
4837 // - apply the operation to each vector
4838 // - make a matrix out the vector results
4839
4840 // get the types sorted out
4841 int numCols = builder.getNumColumns(operand);
4842 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004843 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4844 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004845 std::vector<spv::Id> results;
4846
4847 // do each vector op
4848 for (int c = 0; c < numCols; ++c) {
4849 std::vector<unsigned int> indexes;
4850 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004851 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4852 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06004853 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004854 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004855 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004856 }
4857
4858 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004859 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004860 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004861 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07004862}
4863
John Kessenichad7645f2018-06-04 19:11:25 -06004864// For converting integers where both the bitwidth and the signedness could
4865// change, but only do the width change here. The caller is still responsible
4866// for the signedness conversion.
4867spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07004868{
John Kessenichad7645f2018-06-04 19:11:25 -06004869 // Get the result type width, based on the type to convert to.
4870 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07004871 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06004872 case glslang::EOpConvInt16ToUint8:
4873 case glslang::EOpConvIntToUint8:
4874 case glslang::EOpConvInt64ToUint8:
4875 case glslang::EOpConvUint16ToInt8:
4876 case glslang::EOpConvUintToInt8:
4877 case glslang::EOpConvUint64ToInt8:
4878 width = 8;
4879 break;
John Kessenich66011cb2018-03-06 16:12:04 -07004880 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06004881 case glslang::EOpConvIntToUint16:
4882 case glslang::EOpConvInt64ToUint16:
4883 case glslang::EOpConvUint8ToInt16:
4884 case glslang::EOpConvUintToInt16:
4885 case glslang::EOpConvUint64ToInt16:
4886 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07004887 break;
4888 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06004889 case glslang::EOpConvInt16ToUint:
4890 case glslang::EOpConvInt64ToUint:
4891 case glslang::EOpConvUint8ToInt:
4892 case glslang::EOpConvUint16ToInt:
4893 case glslang::EOpConvUint64ToInt:
4894 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07004895 break;
4896 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07004897 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07004898 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07004899 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07004900 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07004901 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06004902 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07004903 break;
4904
4905 default:
4906 assert(false && "Default missing");
4907 break;
4908 }
4909
John Kessenichad7645f2018-06-04 19:11:25 -06004910 // Get the conversion operation and result type,
4911 // based on the target width, but the source type.
4912 spv::Id type = spv::NoType;
4913 spv::Op convOp = spv::OpNop;
4914 switch(op) {
4915 case glslang::EOpConvInt8ToUint16:
4916 case glslang::EOpConvInt8ToUint:
4917 case glslang::EOpConvInt8ToUint64:
4918 case glslang::EOpConvInt16ToUint8:
4919 case glslang::EOpConvInt16ToUint:
4920 case glslang::EOpConvInt16ToUint64:
4921 case glslang::EOpConvIntToUint8:
4922 case glslang::EOpConvIntToUint16:
4923 case glslang::EOpConvIntToUint64:
4924 case glslang::EOpConvInt64ToUint8:
4925 case glslang::EOpConvInt64ToUint16:
4926 case glslang::EOpConvInt64ToUint:
4927 convOp = spv::OpSConvert;
4928 type = builder.makeIntType(width);
4929 break;
4930 default:
4931 convOp = spv::OpUConvert;
4932 type = builder.makeUintType(width);
4933 break;
4934 }
4935
John Kessenich66011cb2018-03-06 16:12:04 -07004936 if (vectorSize > 0)
4937 type = builder.makeVectorType(type, vectorSize);
4938
John Kessenichad7645f2018-06-04 19:11:25 -06004939 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07004940}
4941
John Kessenichead86222018-03-28 18:01:20 -06004942spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
4943 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004944{
4945 spv::Op convOp = spv::OpNop;
4946 spv::Id zero = 0;
4947 spv::Id one = 0;
4948
4949 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4950
4951 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07004952 case glslang::EOpConvInt8ToBool:
4953 case glslang::EOpConvUint8ToBool:
4954 zero = builder.makeUint8Constant(0);
4955 zero = makeSmearedConstant(zero, vectorSize);
4956 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08004957 case glslang::EOpConvInt16ToBool:
4958 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07004959 zero = builder.makeUint16Constant(0);
4960 zero = makeSmearedConstant(zero, vectorSize);
4961 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4962 case glslang::EOpConvIntToBool:
4963 case glslang::EOpConvUintToBool:
4964 zero = builder.makeUintConstant(0);
4965 zero = makeSmearedConstant(zero, vectorSize);
4966 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4967 case glslang::EOpConvInt64ToBool:
4968 case glslang::EOpConvUint64ToBool:
4969 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004970 zero = makeSmearedConstant(zero, vectorSize);
4971 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4972
4973 case glslang::EOpConvFloatToBool:
4974 zero = builder.makeFloatConstant(0.0F);
4975 zero = makeSmearedConstant(zero, vectorSize);
4976 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4977
4978 case glslang::EOpConvDoubleToBool:
4979 zero = builder.makeDoubleConstant(0.0);
4980 zero = makeSmearedConstant(zero, vectorSize);
4981 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4982
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004983 case glslang::EOpConvFloat16ToBool:
4984 zero = builder.makeFloat16Constant(0.0F);
4985 zero = makeSmearedConstant(zero, vectorSize);
4986 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004987
John Kessenich140f3df2015-06-26 16:58:36 -06004988 case glslang::EOpConvBoolToFloat:
4989 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004990 zero = builder.makeFloatConstant(0.0F);
4991 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004992 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004993
John Kessenich140f3df2015-06-26 16:58:36 -06004994 case glslang::EOpConvBoolToDouble:
4995 convOp = spv::OpSelect;
4996 zero = builder.makeDoubleConstant(0.0);
4997 one = builder.makeDoubleConstant(1.0);
4998 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004999
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005000 case glslang::EOpConvBoolToFloat16:
5001 convOp = spv::OpSelect;
5002 zero = builder.makeFloat16Constant(0.0F);
5003 one = builder.makeFloat16Constant(1.0F);
5004 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005005
5006 case glslang::EOpConvBoolToInt8:
5007 zero = builder.makeInt8Constant(0);
5008 one = builder.makeInt8Constant(1);
5009 convOp = spv::OpSelect;
5010 break;
5011
5012 case glslang::EOpConvBoolToUint8:
5013 zero = builder.makeUint8Constant(0);
5014 one = builder.makeUint8Constant(1);
5015 convOp = spv::OpSelect;
5016 break;
5017
5018 case glslang::EOpConvBoolToInt16:
5019 zero = builder.makeInt16Constant(0);
5020 one = builder.makeInt16Constant(1);
5021 convOp = spv::OpSelect;
5022 break;
5023
5024 case glslang::EOpConvBoolToUint16:
5025 zero = builder.makeUint16Constant(0);
5026 one = builder.makeUint16Constant(1);
5027 convOp = spv::OpSelect;
5028 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005029
John Kessenich140f3df2015-06-26 16:58:36 -06005030 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005031 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005032 if (op == glslang::EOpConvBoolToInt64)
5033 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005034 else
5035 zero = builder.makeIntConstant(0);
5036
5037 if (op == glslang::EOpConvBoolToInt64)
5038 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005039 else
5040 one = builder.makeIntConstant(1);
5041
John Kessenich140f3df2015-06-26 16:58:36 -06005042 convOp = spv::OpSelect;
5043 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005044
John Kessenich140f3df2015-06-26 16:58:36 -06005045 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005046 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005047 if (op == glslang::EOpConvBoolToUint64)
5048 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005049 else
5050 zero = builder.makeUintConstant(0);
5051
5052 if (op == glslang::EOpConvBoolToUint64)
5053 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005054 else
5055 one = builder.makeUintConstant(1);
5056
John Kessenich140f3df2015-06-26 16:58:36 -06005057 convOp = spv::OpSelect;
5058 break;
5059
John Kessenich66011cb2018-03-06 16:12:04 -07005060 case glslang::EOpConvInt8ToFloat16:
5061 case glslang::EOpConvInt8ToFloat:
5062 case glslang::EOpConvInt8ToDouble:
5063 case glslang::EOpConvInt16ToFloat16:
5064 case glslang::EOpConvInt16ToFloat:
5065 case glslang::EOpConvInt16ToDouble:
5066 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005067 case glslang::EOpConvIntToFloat:
5068 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005069 case glslang::EOpConvInt64ToFloat:
5070 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005071 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005072 convOp = spv::OpConvertSToF;
5073 break;
5074
John Kessenich66011cb2018-03-06 16:12:04 -07005075 case glslang::EOpConvUint8ToFloat16:
5076 case glslang::EOpConvUint8ToFloat:
5077 case glslang::EOpConvUint8ToDouble:
5078 case glslang::EOpConvUint16ToFloat16:
5079 case glslang::EOpConvUint16ToFloat:
5080 case glslang::EOpConvUint16ToDouble:
5081 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005082 case glslang::EOpConvUintToFloat:
5083 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005084 case glslang::EOpConvUint64ToFloat:
5085 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005086 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005087 convOp = spv::OpConvertUToF;
5088 break;
5089
5090 case glslang::EOpConvDoubleToFloat:
5091 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005092 case glslang::EOpConvDoubleToFloat16:
5093 case glslang::EOpConvFloat16ToDouble:
5094 case glslang::EOpConvFloatToFloat16:
5095 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005096 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005097 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005098 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005099 break;
5100
John Kessenich66011cb2018-03-06 16:12:04 -07005101 case glslang::EOpConvFloat16ToInt8:
5102 case glslang::EOpConvFloatToInt8:
5103 case glslang::EOpConvDoubleToInt8:
5104 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005105 case glslang::EOpConvFloatToInt16:
5106 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005107 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005108 case glslang::EOpConvFloatToInt:
5109 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005110 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005111 case glslang::EOpConvFloatToInt64:
5112 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005113 convOp = spv::OpConvertFToS;
5114 break;
5115
John Kessenich66011cb2018-03-06 16:12:04 -07005116 case glslang::EOpConvUint8ToInt8:
5117 case glslang::EOpConvInt8ToUint8:
5118 case glslang::EOpConvUint16ToInt16:
5119 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005120 case glslang::EOpConvUintToInt:
5121 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005122 case glslang::EOpConvUint64ToInt64:
5123 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005124 if (builder.isInSpecConstCodeGenMode()) {
5125 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005126 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5127 zero = builder.makeUint8Constant(0);
5128 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005129 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005130 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5131 zero = builder.makeUint64Constant(0);
5132 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005133 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005134 }
qining189b2032016-04-12 23:16:20 -04005135 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005136 // Use OpIAdd, instead of OpBitcast to do the conversion when
5137 // generating for OpSpecConstantOp instruction.
5138 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5139 }
5140 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005141 convOp = spv::OpBitcast;
5142 break;
5143
John Kessenich66011cb2018-03-06 16:12:04 -07005144 case glslang::EOpConvFloat16ToUint8:
5145 case glslang::EOpConvFloatToUint8:
5146 case glslang::EOpConvDoubleToUint8:
5147 case glslang::EOpConvFloat16ToUint16:
5148 case glslang::EOpConvFloatToUint16:
5149 case glslang::EOpConvDoubleToUint16:
5150 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005151 case glslang::EOpConvFloatToUint:
5152 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005153 case glslang::EOpConvFloatToUint64:
5154 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005155 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005156 convOp = spv::OpConvertFToU;
5157 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005158
John Kessenich66011cb2018-03-06 16:12:04 -07005159 case glslang::EOpConvInt8ToInt16:
5160 case glslang::EOpConvInt8ToInt:
5161 case glslang::EOpConvInt8ToInt64:
5162 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005163 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005164 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005165 case glslang::EOpConvIntToInt8:
5166 case glslang::EOpConvIntToInt16:
5167 case glslang::EOpConvIntToInt64:
5168 case glslang::EOpConvInt64ToInt8:
5169 case glslang::EOpConvInt64ToInt16:
5170 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005171 convOp = spv::OpSConvert;
5172 break;
5173
John Kessenich66011cb2018-03-06 16:12:04 -07005174 case glslang::EOpConvUint8ToUint16:
5175 case glslang::EOpConvUint8ToUint:
5176 case glslang::EOpConvUint8ToUint64:
5177 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005178 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005179 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005180 case glslang::EOpConvUintToUint8:
5181 case glslang::EOpConvUintToUint16:
5182 case glslang::EOpConvUintToUint64:
5183 case glslang::EOpConvUint64ToUint8:
5184 case glslang::EOpConvUint64ToUint16:
5185 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005186 convOp = spv::OpUConvert;
5187 break;
5188
John Kessenich66011cb2018-03-06 16:12:04 -07005189 case glslang::EOpConvInt8ToUint16:
5190 case glslang::EOpConvInt8ToUint:
5191 case glslang::EOpConvInt8ToUint64:
5192 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005193 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005194 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005195 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005196 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005197 case glslang::EOpConvIntToUint64:
5198 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005199 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005200 case glslang::EOpConvInt64ToUint:
5201 case glslang::EOpConvUint8ToInt16:
5202 case glslang::EOpConvUint8ToInt:
5203 case glslang::EOpConvUint8ToInt64:
5204 case glslang::EOpConvUint16ToInt8:
5205 case glslang::EOpConvUint16ToInt:
5206 case glslang::EOpConvUint16ToInt64:
5207 case glslang::EOpConvUintToInt8:
5208 case glslang::EOpConvUintToInt16:
5209 case glslang::EOpConvUintToInt64:
5210 case glslang::EOpConvUint64ToInt8:
5211 case glslang::EOpConvUint64ToInt16:
5212 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005213 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005214 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005215
5216 if (builder.isInSpecConstCodeGenMode()) {
5217 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005218 switch(op) {
5219 case glslang::EOpConvInt16ToUint8:
5220 case glslang::EOpConvIntToUint8:
5221 case glslang::EOpConvInt64ToUint8:
5222 case glslang::EOpConvUint16ToInt8:
5223 case glslang::EOpConvUintToInt8:
5224 case glslang::EOpConvUint64ToInt8:
5225 zero = builder.makeUint8Constant(0);
5226 break;
5227 case glslang::EOpConvInt8ToUint16:
5228 case glslang::EOpConvIntToUint16:
5229 case glslang::EOpConvInt64ToUint16:
5230 case glslang::EOpConvUint8ToInt16:
5231 case glslang::EOpConvUintToInt16:
5232 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005233 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005234 break;
5235 case glslang::EOpConvInt8ToUint:
5236 case glslang::EOpConvInt16ToUint:
5237 case glslang::EOpConvInt64ToUint:
5238 case glslang::EOpConvUint8ToInt:
5239 case glslang::EOpConvUint16ToInt:
5240 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005241 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005242 break;
5243 case glslang::EOpConvInt8ToUint64:
5244 case glslang::EOpConvInt16ToUint64:
5245 case glslang::EOpConvIntToUint64:
5246 case glslang::EOpConvUint8ToInt64:
5247 case glslang::EOpConvUint16ToInt64:
5248 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005249 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005250 break;
5251 default:
5252 assert(false && "Default missing");
5253 break;
5254 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005255 zero = makeSmearedConstant(zero, vectorSize);
5256 // Use OpIAdd, instead of OpBitcast to do the conversion when
5257 // generating for OpSpecConstantOp instruction.
5258 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5259 }
5260 // For normal run-time conversion instruction, use OpBitcast.
5261 convOp = spv::OpBitcast;
5262 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005263 default:
5264 break;
5265 }
5266
5267 spv::Id result = 0;
5268 if (convOp == spv::OpNop)
5269 return result;
5270
5271 if (convOp == spv::OpSelect) {
5272 zero = makeSmearedConstant(zero, vectorSize);
5273 one = makeSmearedConstant(one, vectorSize);
5274 result = builder.createTriOp(convOp, destType, operand, one, zero);
5275 } else
5276 result = builder.createUnaryOp(convOp, destType, operand);
5277
John Kessenichead86222018-03-28 18:01:20 -06005278 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005279 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005280 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06005281}
5282
5283spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
5284{
5285 if (vectorSize == 0)
5286 return constant;
5287
5288 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
5289 std::vector<spv::Id> components;
5290 for (int c = 0; c < vectorSize; ++c)
5291 components.push_back(constant);
5292 return builder.makeCompositeConstant(vectorTypeId, components);
5293}
5294
John Kessenich426394d2015-07-23 10:22:48 -06005295// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07005296spv::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 -06005297{
5298 spv::Op opCode = spv::OpNop;
5299
5300 switch (op) {
5301 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08005302 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005303 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06005304 opCode = spv::OpAtomicIAdd;
5305 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06005306 case glslang::EOpAtomicCounterSubtract:
5307 opCode = spv::OpAtomicISub;
5308 break;
John Kessenich426394d2015-07-23 10:22:48 -06005309 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08005310 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005311 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08005312 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06005313 break;
5314 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08005315 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005316 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08005317 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06005318 break;
5319 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08005320 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005321 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06005322 opCode = spv::OpAtomicAnd;
5323 break;
5324 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08005325 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005326 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06005327 opCode = spv::OpAtomicOr;
5328 break;
5329 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08005330 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005331 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06005332 opCode = spv::OpAtomicXor;
5333 break;
5334 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08005335 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005336 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06005337 opCode = spv::OpAtomicExchange;
5338 break;
5339 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08005340 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005341 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06005342 opCode = spv::OpAtomicCompareExchange;
5343 break;
5344 case glslang::EOpAtomicCounterIncrement:
5345 opCode = spv::OpAtomicIIncrement;
5346 break;
5347 case glslang::EOpAtomicCounterDecrement:
5348 opCode = spv::OpAtomicIDecrement;
5349 break;
5350 case glslang::EOpAtomicCounter:
5351 opCode = spv::OpAtomicLoad;
5352 break;
5353 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005354 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06005355 break;
5356 }
5357
Rex Xue8fe8b02017-09-26 15:42:56 +08005358 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
5359 builder.addCapability(spv::CapabilityInt64Atomics);
5360
John Kessenich426394d2015-07-23 10:22:48 -06005361 // Sort out the operands
5362 // - mapping from glslang -> SPV
5363 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06005364 // - compare-exchange swaps the value and comparator
5365 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06005366 // - EOpAtomicCounterDecrement needs a post decrement
John Kessenich426394d2015-07-23 10:22:48 -06005367 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
5368 auto opIt = operands.begin(); // walk the glslang operands
5369 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08005370 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
5371 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
5372 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08005373 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
5374 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08005375 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06005376 spvAtomicOperands.push_back(*(opIt + 1));
5377 spvAtomicOperands.push_back(*opIt);
5378 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08005379 }
John Kessenich426394d2015-07-23 10:22:48 -06005380
John Kessenich3e60a6f2015-09-14 22:45:16 -06005381 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06005382 for (; opIt != operands.end(); ++opIt)
5383 spvAtomicOperands.push_back(*opIt);
5384
John Kessenich48d6e792017-10-06 21:21:48 -06005385 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
5386
5387 // GLSL and HLSL atomic-counter decrement return post-decrement value,
5388 // while SPIR-V returns pre-decrement value. Translate between these semantics.
5389 if (op == glslang::EOpAtomicCounterDecrement)
5390 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
5391
5392 return resultId;
John Kessenich426394d2015-07-23 10:22:48 -06005393}
5394
John Kessenich91cef522016-05-05 16:45:40 -06005395// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08005396spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06005397{
Corentin Walleze7061422018-08-08 15:20:15 +02005398#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07005399 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5400 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02005401#endif
Rex Xu9d93a232016-05-05 12:30:44 +08005402
Rex Xu51596642016-09-21 18:56:12 +08005403 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06005404 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08005405 spv::GroupOperation groupOperation = spv::GroupOperationMax;
5406
chaocf200da82016-12-20 12:44:35 -08005407 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
5408 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08005409 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
5410 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005411 } else if (op == glslang::EOpAnyInvocation ||
5412 op == glslang::EOpAllInvocations ||
5413 op == glslang::EOpAllInvocationsEqual) {
5414 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
5415 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08005416 } else {
5417 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04005418#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08005419 if (op == glslang::EOpMinInvocationsNonUniform ||
5420 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08005421 op == glslang::EOpAddInvocationsNonUniform ||
5422 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5423 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5424 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
5425 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
5426 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
5427 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08005428 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04005429#endif
Rex Xu51596642016-09-21 18:56:12 +08005430
Rex Xu9d93a232016-05-05 12:30:44 +08005431#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08005432 switch (op) {
5433 case glslang::EOpMinInvocations:
5434 case glslang::EOpMaxInvocations:
5435 case glslang::EOpAddInvocations:
5436 case glslang::EOpMinInvocationsNonUniform:
5437 case glslang::EOpMaxInvocationsNonUniform:
5438 case glslang::EOpAddInvocationsNonUniform:
5439 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08005440 break;
5441 case glslang::EOpMinInvocationsInclusiveScan:
5442 case glslang::EOpMaxInvocationsInclusiveScan:
5443 case glslang::EOpAddInvocationsInclusiveScan:
5444 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5445 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5446 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5447 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08005448 break;
5449 case glslang::EOpMinInvocationsExclusiveScan:
5450 case glslang::EOpMaxInvocationsExclusiveScan:
5451 case glslang::EOpAddInvocationsExclusiveScan:
5452 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5453 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5454 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5455 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08005456 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07005457 default:
5458 break;
Rex Xu430ef402016-10-14 17:22:23 +08005459 }
John Kessenich149afc32018-08-14 13:31:43 -06005460 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
5461 spvGroupOperands.push_back(scope);
5462 if (groupOperation != spv::GroupOperationMax) {
5463 spv::IdImmediate groupOp = { false, groupOperation };
5464 spvGroupOperands.push_back(groupOp);
5465 }
Rex Xu9d93a232016-05-05 12:30:44 +08005466#endif
Rex Xu51596642016-09-21 18:56:12 +08005467 }
5468
John Kessenich149afc32018-08-14 13:31:43 -06005469 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
5470 spv::IdImmediate op = { true, *opIt };
5471 spvGroupOperands.push_back(op);
5472 }
John Kessenich91cef522016-05-05 16:45:40 -06005473
5474 switch (op) {
5475 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005476 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08005477 break;
John Kessenich91cef522016-05-05 16:45:40 -06005478 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005479 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08005480 break;
John Kessenich91cef522016-05-05 16:45:40 -06005481 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005482 opCode = spv::OpSubgroupAllEqualKHR;
5483 break;
Rex Xu51596642016-09-21 18:56:12 +08005484 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08005485 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08005486 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005487 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005488 break;
5489 case glslang::EOpReadFirstInvocation:
5490 opCode = spv::OpSubgroupFirstInvocationKHR;
5491 break;
5492 case glslang::EOpBallot:
5493 {
5494 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
5495 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
5496 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
5497 //
5498 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
5499 //
5500 spv::Id uintType = builder.makeUintType(32);
5501 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
5502 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
5503
5504 std::vector<spv::Id> components;
5505 components.push_back(builder.createCompositeExtract(result, uintType, 0));
5506 components.push_back(builder.createCompositeExtract(result, uintType, 1));
5507
5508 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
5509 return builder.createUnaryOp(spv::OpBitcast, typeId,
5510 builder.createCompositeConstruct(uvec2Type, components));
5511 }
5512
Rex Xu9d93a232016-05-05 12:30:44 +08005513#ifdef AMD_EXTENSIONS
5514 case glslang::EOpMinInvocations:
5515 case glslang::EOpMaxInvocations:
5516 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08005517 case glslang::EOpMinInvocationsInclusiveScan:
5518 case glslang::EOpMaxInvocationsInclusiveScan:
5519 case glslang::EOpAddInvocationsInclusiveScan:
5520 case glslang::EOpMinInvocationsExclusiveScan:
5521 case glslang::EOpMaxInvocationsExclusiveScan:
5522 case glslang::EOpAddInvocationsExclusiveScan:
5523 if (op == glslang::EOpMinInvocations ||
5524 op == glslang::EOpMinInvocationsInclusiveScan ||
5525 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005526 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005527 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005528 else {
5529 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005530 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005531 else
Rex Xu51596642016-09-21 18:56:12 +08005532 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005533 }
Rex Xu430ef402016-10-14 17:22:23 +08005534 } else if (op == glslang::EOpMaxInvocations ||
5535 op == glslang::EOpMaxInvocationsInclusiveScan ||
5536 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005537 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005538 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005539 else {
5540 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005541 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005542 else
Rex Xu51596642016-09-21 18:56:12 +08005543 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005544 }
5545 } else {
5546 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005547 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005548 else
Rex Xu51596642016-09-21 18:56:12 +08005549 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005550 }
5551
Rex Xu2bbbe062016-08-23 15:41:05 +08005552 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005553 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005554
5555 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005556 case glslang::EOpMinInvocationsNonUniform:
5557 case glslang::EOpMaxInvocationsNonUniform:
5558 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005559 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5560 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5561 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5562 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5563 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5564 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5565 if (op == glslang::EOpMinInvocationsNonUniform ||
5566 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5567 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005568 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005569 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005570 else {
5571 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005572 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005573 else
Rex Xu51596642016-09-21 18:56:12 +08005574 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005575 }
5576 }
Rex Xu430ef402016-10-14 17:22:23 +08005577 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5578 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5579 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005580 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005581 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005582 else {
5583 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005584 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005585 else
Rex Xu51596642016-09-21 18:56:12 +08005586 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005587 }
5588 }
5589 else {
5590 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005591 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005592 else
Rex Xu51596642016-09-21 18:56:12 +08005593 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005594 }
5595
Rex Xu2bbbe062016-08-23 15:41:05 +08005596 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005597 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005598
5599 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005600#endif
John Kessenich91cef522016-05-05 16:45:40 -06005601 default:
5602 logger->missingFunctionality("invocation operation");
5603 return spv::NoResult;
5604 }
Rex Xu51596642016-09-21 18:56:12 +08005605
5606 assert(opCode != spv::OpNop);
5607 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005608}
5609
Rex Xu2bbbe062016-08-23 15:41:05 +08005610// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06005611spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
5612 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005613{
Rex Xub7072052016-09-26 15:53:40 +08005614#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005615 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5616 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005617 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005618 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005619 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5620 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5621 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005622#else
5623 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5624 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005625 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5626 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005627#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005628
5629 // Handle group invocation operations scalar by scalar.
5630 // The result type is the same type as the original type.
5631 // The algorithm is to:
5632 // - break the vector into scalars
5633 // - apply the operation to each scalar
5634 // - make a vector out the scalar results
5635
5636 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005637 int numComponents = builder.getNumComponents(operands[0]);
5638 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005639 std::vector<spv::Id> results;
5640
5641 // do each scalar op
5642 for (int comp = 0; comp < numComponents; ++comp) {
5643 std::vector<unsigned int> indexes;
5644 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06005645 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
5646 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005647 if (op == spv::OpSubgroupReadInvocationKHR) {
5648 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06005649 spv::IdImmediate operand = { true, operands[1] };
5650 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08005651 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06005652 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
5653 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08005654 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06005655 spv::IdImmediate operand = { true, operands[1] };
5656 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08005657 } else {
John Kessenich149afc32018-08-14 13:31:43 -06005658 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
5659 spvGroupOperands.push_back(scope);
5660 spv::IdImmediate groupOp = { false, groupOperation };
5661 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08005662 spvGroupOperands.push_back(scalar);
5663 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005664
Rex Xub7072052016-09-26 15:53:40 +08005665 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005666 }
5667
5668 // put the pieces together
5669 return builder.createCompositeConstruct(typeId, results);
5670}
Rex Xu2bbbe062016-08-23 15:41:05 +08005671
John Kessenich66011cb2018-03-06 16:12:04 -07005672// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06005673spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
5674 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07005675{
5676 // Add the required capabilities.
5677 switch (op) {
5678 case glslang::EOpSubgroupElect:
5679 builder.addCapability(spv::CapabilityGroupNonUniform);
5680 break;
5681 case glslang::EOpSubgroupAll:
5682 case glslang::EOpSubgroupAny:
5683 case glslang::EOpSubgroupAllEqual:
5684 builder.addCapability(spv::CapabilityGroupNonUniform);
5685 builder.addCapability(spv::CapabilityGroupNonUniformVote);
5686 break;
5687 case glslang::EOpSubgroupBroadcast:
5688 case glslang::EOpSubgroupBroadcastFirst:
5689 case glslang::EOpSubgroupBallot:
5690 case glslang::EOpSubgroupInverseBallot:
5691 case glslang::EOpSubgroupBallotBitExtract:
5692 case glslang::EOpSubgroupBallotBitCount:
5693 case glslang::EOpSubgroupBallotInclusiveBitCount:
5694 case glslang::EOpSubgroupBallotExclusiveBitCount:
5695 case glslang::EOpSubgroupBallotFindLSB:
5696 case glslang::EOpSubgroupBallotFindMSB:
5697 builder.addCapability(spv::CapabilityGroupNonUniform);
5698 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
5699 break;
5700 case glslang::EOpSubgroupShuffle:
5701 case glslang::EOpSubgroupShuffleXor:
5702 builder.addCapability(spv::CapabilityGroupNonUniform);
5703 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
5704 break;
5705 case glslang::EOpSubgroupShuffleUp:
5706 case glslang::EOpSubgroupShuffleDown:
5707 builder.addCapability(spv::CapabilityGroupNonUniform);
5708 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
5709 break;
5710 case glslang::EOpSubgroupAdd:
5711 case glslang::EOpSubgroupMul:
5712 case glslang::EOpSubgroupMin:
5713 case glslang::EOpSubgroupMax:
5714 case glslang::EOpSubgroupAnd:
5715 case glslang::EOpSubgroupOr:
5716 case glslang::EOpSubgroupXor:
5717 case glslang::EOpSubgroupInclusiveAdd:
5718 case glslang::EOpSubgroupInclusiveMul:
5719 case glslang::EOpSubgroupInclusiveMin:
5720 case glslang::EOpSubgroupInclusiveMax:
5721 case glslang::EOpSubgroupInclusiveAnd:
5722 case glslang::EOpSubgroupInclusiveOr:
5723 case glslang::EOpSubgroupInclusiveXor:
5724 case glslang::EOpSubgroupExclusiveAdd:
5725 case glslang::EOpSubgroupExclusiveMul:
5726 case glslang::EOpSubgroupExclusiveMin:
5727 case glslang::EOpSubgroupExclusiveMax:
5728 case glslang::EOpSubgroupExclusiveAnd:
5729 case glslang::EOpSubgroupExclusiveOr:
5730 case glslang::EOpSubgroupExclusiveXor:
5731 builder.addCapability(spv::CapabilityGroupNonUniform);
5732 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
5733 break;
5734 case glslang::EOpSubgroupClusteredAdd:
5735 case glslang::EOpSubgroupClusteredMul:
5736 case glslang::EOpSubgroupClusteredMin:
5737 case glslang::EOpSubgroupClusteredMax:
5738 case glslang::EOpSubgroupClusteredAnd:
5739 case glslang::EOpSubgroupClusteredOr:
5740 case glslang::EOpSubgroupClusteredXor:
5741 builder.addCapability(spv::CapabilityGroupNonUniform);
5742 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
5743 break;
5744 case glslang::EOpSubgroupQuadBroadcast:
5745 case glslang::EOpSubgroupQuadSwapHorizontal:
5746 case glslang::EOpSubgroupQuadSwapVertical:
5747 case glslang::EOpSubgroupQuadSwapDiagonal:
5748 builder.addCapability(spv::CapabilityGroupNonUniform);
5749 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
5750 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005751#ifdef NV_EXTENSIONS
5752 case glslang::EOpSubgroupPartitionedAdd:
5753 case glslang::EOpSubgroupPartitionedMul:
5754 case glslang::EOpSubgroupPartitionedMin:
5755 case glslang::EOpSubgroupPartitionedMax:
5756 case glslang::EOpSubgroupPartitionedAnd:
5757 case glslang::EOpSubgroupPartitionedOr:
5758 case glslang::EOpSubgroupPartitionedXor:
5759 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5760 case glslang::EOpSubgroupPartitionedInclusiveMul:
5761 case glslang::EOpSubgroupPartitionedInclusiveMin:
5762 case glslang::EOpSubgroupPartitionedInclusiveMax:
5763 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5764 case glslang::EOpSubgroupPartitionedInclusiveOr:
5765 case glslang::EOpSubgroupPartitionedInclusiveXor:
5766 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5767 case glslang::EOpSubgroupPartitionedExclusiveMul:
5768 case glslang::EOpSubgroupPartitionedExclusiveMin:
5769 case glslang::EOpSubgroupPartitionedExclusiveMax:
5770 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5771 case glslang::EOpSubgroupPartitionedExclusiveOr:
5772 case glslang::EOpSubgroupPartitionedExclusiveXor:
5773 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
5774 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
5775 break;
5776#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005777 default: assert(0 && "Unhandled subgroup operation!");
5778 }
5779
5780 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
5781 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
5782 const bool isBool = typeProxy == glslang::EbtBool;
5783
5784 spv::Op opCode = spv::OpNop;
5785
5786 // Figure out which opcode to use.
5787 switch (op) {
5788 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
5789 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
5790 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
5791 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
5792 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
5793 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
5794 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
5795 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
5796 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
5797 case glslang::EOpSubgroupBallotBitCount:
5798 case glslang::EOpSubgroupBallotInclusiveBitCount:
5799 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
5800 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
5801 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
5802 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
5803 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
5804 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
5805 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
5806 case glslang::EOpSubgroupAdd:
5807 case glslang::EOpSubgroupInclusiveAdd:
5808 case glslang::EOpSubgroupExclusiveAdd:
5809 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005810#ifdef NV_EXTENSIONS
5811 case glslang::EOpSubgroupPartitionedAdd:
5812 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5813 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5814#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005815 if (isFloat) {
5816 opCode = spv::OpGroupNonUniformFAdd;
5817 } else {
5818 opCode = spv::OpGroupNonUniformIAdd;
5819 }
5820 break;
5821 case glslang::EOpSubgroupMul:
5822 case glslang::EOpSubgroupInclusiveMul:
5823 case glslang::EOpSubgroupExclusiveMul:
5824 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005825#ifdef NV_EXTENSIONS
5826 case glslang::EOpSubgroupPartitionedMul:
5827 case glslang::EOpSubgroupPartitionedInclusiveMul:
5828 case glslang::EOpSubgroupPartitionedExclusiveMul:
5829#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005830 if (isFloat) {
5831 opCode = spv::OpGroupNonUniformFMul;
5832 } else {
5833 opCode = spv::OpGroupNonUniformIMul;
5834 }
5835 break;
5836 case glslang::EOpSubgroupMin:
5837 case glslang::EOpSubgroupInclusiveMin:
5838 case glslang::EOpSubgroupExclusiveMin:
5839 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005840#ifdef NV_EXTENSIONS
5841 case glslang::EOpSubgroupPartitionedMin:
5842 case glslang::EOpSubgroupPartitionedInclusiveMin:
5843 case glslang::EOpSubgroupPartitionedExclusiveMin:
5844#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005845 if (isFloat) {
5846 opCode = spv::OpGroupNonUniformFMin;
5847 } else if (isUnsigned) {
5848 opCode = spv::OpGroupNonUniformUMin;
5849 } else {
5850 opCode = spv::OpGroupNonUniformSMin;
5851 }
5852 break;
5853 case glslang::EOpSubgroupMax:
5854 case glslang::EOpSubgroupInclusiveMax:
5855 case glslang::EOpSubgroupExclusiveMax:
5856 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005857#ifdef NV_EXTENSIONS
5858 case glslang::EOpSubgroupPartitionedMax:
5859 case glslang::EOpSubgroupPartitionedInclusiveMax:
5860 case glslang::EOpSubgroupPartitionedExclusiveMax:
5861#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005862 if (isFloat) {
5863 opCode = spv::OpGroupNonUniformFMax;
5864 } else if (isUnsigned) {
5865 opCode = spv::OpGroupNonUniformUMax;
5866 } else {
5867 opCode = spv::OpGroupNonUniformSMax;
5868 }
5869 break;
5870 case glslang::EOpSubgroupAnd:
5871 case glslang::EOpSubgroupInclusiveAnd:
5872 case glslang::EOpSubgroupExclusiveAnd:
5873 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005874#ifdef NV_EXTENSIONS
5875 case glslang::EOpSubgroupPartitionedAnd:
5876 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5877 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5878#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005879 if (isBool) {
5880 opCode = spv::OpGroupNonUniformLogicalAnd;
5881 } else {
5882 opCode = spv::OpGroupNonUniformBitwiseAnd;
5883 }
5884 break;
5885 case glslang::EOpSubgroupOr:
5886 case glslang::EOpSubgroupInclusiveOr:
5887 case glslang::EOpSubgroupExclusiveOr:
5888 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005889#ifdef NV_EXTENSIONS
5890 case glslang::EOpSubgroupPartitionedOr:
5891 case glslang::EOpSubgroupPartitionedInclusiveOr:
5892 case glslang::EOpSubgroupPartitionedExclusiveOr:
5893#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005894 if (isBool) {
5895 opCode = spv::OpGroupNonUniformLogicalOr;
5896 } else {
5897 opCode = spv::OpGroupNonUniformBitwiseOr;
5898 }
5899 break;
5900 case glslang::EOpSubgroupXor:
5901 case glslang::EOpSubgroupInclusiveXor:
5902 case glslang::EOpSubgroupExclusiveXor:
5903 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005904#ifdef NV_EXTENSIONS
5905 case glslang::EOpSubgroupPartitionedXor:
5906 case glslang::EOpSubgroupPartitionedInclusiveXor:
5907 case glslang::EOpSubgroupPartitionedExclusiveXor:
5908#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005909 if (isBool) {
5910 opCode = spv::OpGroupNonUniformLogicalXor;
5911 } else {
5912 opCode = spv::OpGroupNonUniformBitwiseXor;
5913 }
5914 break;
5915 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
5916 case glslang::EOpSubgroupQuadSwapHorizontal:
5917 case glslang::EOpSubgroupQuadSwapVertical:
5918 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
5919 default: assert(0 && "Unhandled subgroup operation!");
5920 }
5921
John Kessenich149afc32018-08-14 13:31:43 -06005922 // get the right Group Operation
5923 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07005924 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06005925 default:
5926 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005927 case glslang::EOpSubgroupBallotBitCount:
5928 case glslang::EOpSubgroupAdd:
5929 case glslang::EOpSubgroupMul:
5930 case glslang::EOpSubgroupMin:
5931 case glslang::EOpSubgroupMax:
5932 case glslang::EOpSubgroupAnd:
5933 case glslang::EOpSubgroupOr:
5934 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06005935 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07005936 break;
5937 case glslang::EOpSubgroupBallotInclusiveBitCount:
5938 case glslang::EOpSubgroupInclusiveAdd:
5939 case glslang::EOpSubgroupInclusiveMul:
5940 case glslang::EOpSubgroupInclusiveMin:
5941 case glslang::EOpSubgroupInclusiveMax:
5942 case glslang::EOpSubgroupInclusiveAnd:
5943 case glslang::EOpSubgroupInclusiveOr:
5944 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06005945 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07005946 break;
5947 case glslang::EOpSubgroupBallotExclusiveBitCount:
5948 case glslang::EOpSubgroupExclusiveAdd:
5949 case glslang::EOpSubgroupExclusiveMul:
5950 case glslang::EOpSubgroupExclusiveMin:
5951 case glslang::EOpSubgroupExclusiveMax:
5952 case glslang::EOpSubgroupExclusiveAnd:
5953 case glslang::EOpSubgroupExclusiveOr:
5954 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06005955 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07005956 break;
5957 case glslang::EOpSubgroupClusteredAdd:
5958 case glslang::EOpSubgroupClusteredMul:
5959 case glslang::EOpSubgroupClusteredMin:
5960 case glslang::EOpSubgroupClusteredMax:
5961 case glslang::EOpSubgroupClusteredAnd:
5962 case glslang::EOpSubgroupClusteredOr:
5963 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06005964 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07005965 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005966#ifdef NV_EXTENSIONS
5967 case glslang::EOpSubgroupPartitionedAdd:
5968 case glslang::EOpSubgroupPartitionedMul:
5969 case glslang::EOpSubgroupPartitionedMin:
5970 case glslang::EOpSubgroupPartitionedMax:
5971 case glslang::EOpSubgroupPartitionedAnd:
5972 case glslang::EOpSubgroupPartitionedOr:
5973 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06005974 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005975 break;
5976 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5977 case glslang::EOpSubgroupPartitionedInclusiveMul:
5978 case glslang::EOpSubgroupPartitionedInclusiveMin:
5979 case glslang::EOpSubgroupPartitionedInclusiveMax:
5980 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5981 case glslang::EOpSubgroupPartitionedInclusiveOr:
5982 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06005983 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005984 break;
5985 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5986 case glslang::EOpSubgroupPartitionedExclusiveMul:
5987 case glslang::EOpSubgroupPartitionedExclusiveMin:
5988 case glslang::EOpSubgroupPartitionedExclusiveMax:
5989 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5990 case glslang::EOpSubgroupPartitionedExclusiveOr:
5991 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06005992 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005993 break;
5994#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005995 }
5996
John Kessenich149afc32018-08-14 13:31:43 -06005997 // build the instruction
5998 std::vector<spv::IdImmediate> spvGroupOperands;
5999
6000 // Every operation begins with the Execution Scope operand.
6001 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6002 spvGroupOperands.push_back(executionScope);
6003
6004 // Next, for all operations that use a Group Operation, push that as an operand.
6005 if (groupOperation != spv::GroupOperationMax) {
6006 spv::IdImmediate groupOperand = { false, groupOperation };
6007 spvGroupOperands.push_back(groupOperand);
6008 }
6009
John Kessenich66011cb2018-03-06 16:12:04 -07006010 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006011 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6012 spv::IdImmediate operand = { true, *opIt };
6013 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006014 }
6015
6016 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006017 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006018 switch (op) {
6019 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006020 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6021 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6022 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6023 }
6024 if (directionId != spv::NoResult) {
6025 spv::IdImmediate direction = { true, directionId };
6026 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006027 }
6028
6029 return builder.createOp(opCode, typeId, spvGroupOperands);
6030}
6031
John Kessenich5e4b1242015-08-06 22:53:06 -06006032spv::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 -06006033{
John Kessenich66011cb2018-03-06 16:12:04 -07006034 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6035 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006036
John Kessenich140f3df2015-06-26 16:58:36 -06006037 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006038 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006039 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006040 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006041 spv::Id typeId0 = 0;
6042 if (consumedOperands > 0)
6043 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006044 spv::Id typeId1 = 0;
6045 if (consumedOperands > 1)
6046 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006047 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006048
6049 switch (op) {
6050 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006051 if (isFloat)
6052 libCall = spv::GLSLstd450FMin;
6053 else if (isUnsigned)
6054 libCall = spv::GLSLstd450UMin;
6055 else
6056 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006057 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006058 break;
6059 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006060 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006061 break;
6062 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006063 if (isFloat)
6064 libCall = spv::GLSLstd450FMax;
6065 else if (isUnsigned)
6066 libCall = spv::GLSLstd450UMax;
6067 else
6068 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006069 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006070 break;
6071 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006072 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006073 break;
6074 case glslang::EOpDot:
6075 opCode = spv::OpDot;
6076 break;
6077 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006078 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006079 break;
6080
6081 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006082 if (isFloat)
6083 libCall = spv::GLSLstd450FClamp;
6084 else if (isUnsigned)
6085 libCall = spv::GLSLstd450UClamp;
6086 else
6087 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006088 builder.promoteScalar(precision, operands.front(), operands[1]);
6089 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006090 break;
6091 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006092 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6093 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006094 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006095 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006096 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006097 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006098 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006099 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006100 break;
6101 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006102 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006103 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006104 break;
6105 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006106 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006107 builder.promoteScalar(precision, operands[0], operands[2]);
6108 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006109 break;
6110
6111 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006112 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006113 break;
6114 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006115 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006116 break;
6117 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006118 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006119 break;
6120 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006121 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006122 break;
6123 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006124 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006125 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006126 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006127#ifdef AMD_EXTENSIONS
6128 if (typeProxy == glslang::EbtFloat16)
6129 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6130#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006131 libCall = spv::GLSLstd450InterpolateAtSample;
6132 break;
6133 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006134#ifdef AMD_EXTENSIONS
6135 if (typeProxy == glslang::EbtFloat16)
6136 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6137#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006138 libCall = spv::GLSLstd450InterpolateAtOffset;
6139 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006140 case glslang::EOpAddCarry:
6141 opCode = spv::OpIAddCarry;
6142 typeId = builder.makeStructResultType(typeId0, typeId0);
6143 consumedOperands = 2;
6144 break;
6145 case glslang::EOpSubBorrow:
6146 opCode = spv::OpISubBorrow;
6147 typeId = builder.makeStructResultType(typeId0, typeId0);
6148 consumedOperands = 2;
6149 break;
6150 case glslang::EOpUMulExtended:
6151 opCode = spv::OpUMulExtended;
6152 typeId = builder.makeStructResultType(typeId0, typeId0);
6153 consumedOperands = 2;
6154 break;
6155 case glslang::EOpIMulExtended:
6156 opCode = spv::OpSMulExtended;
6157 typeId = builder.makeStructResultType(typeId0, typeId0);
6158 consumedOperands = 2;
6159 break;
6160 case glslang::EOpBitfieldExtract:
6161 if (isUnsigned)
6162 opCode = spv::OpBitFieldUExtract;
6163 else
6164 opCode = spv::OpBitFieldSExtract;
6165 break;
6166 case glslang::EOpBitfieldInsert:
6167 opCode = spv::OpBitFieldInsert;
6168 break;
6169
6170 case glslang::EOpFma:
6171 libCall = spv::GLSLstd450Fma;
6172 break;
6173 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006174 {
6175 libCall = spv::GLSLstd450FrexpStruct;
6176 assert(builder.isPointerType(typeId1));
6177 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006178 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006179#ifdef AMD_EXTENSIONS
6180 if (width == 16)
6181 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6182 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
6183#endif
Rex Xu470026f2017-03-29 17:12:40 +08006184 if (builder.getNumComponents(operands[0]) == 1)
6185 frexpIntType = builder.makeIntegerType(width, true);
6186 else
6187 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6188 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6189 consumedOperands = 1;
6190 }
John Kessenich55e7d112015-11-15 21:33:39 -07006191 break;
6192 case glslang::EOpLdexp:
6193 libCall = spv::GLSLstd450Ldexp;
6194 break;
6195
Rex Xu574ab042016-04-14 16:53:07 +08006196 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08006197 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08006198
John Kessenich66011cb2018-03-06 16:12:04 -07006199 case glslang::EOpSubgroupBroadcast:
6200 case glslang::EOpSubgroupBallotBitExtract:
6201 case glslang::EOpSubgroupShuffle:
6202 case glslang::EOpSubgroupShuffleXor:
6203 case glslang::EOpSubgroupShuffleUp:
6204 case glslang::EOpSubgroupShuffleDown:
6205 case glslang::EOpSubgroupClusteredAdd:
6206 case glslang::EOpSubgroupClusteredMul:
6207 case glslang::EOpSubgroupClusteredMin:
6208 case glslang::EOpSubgroupClusteredMax:
6209 case glslang::EOpSubgroupClusteredAnd:
6210 case glslang::EOpSubgroupClusteredOr:
6211 case glslang::EOpSubgroupClusteredXor:
6212 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006213#ifdef NV_EXTENSIONS
6214 case glslang::EOpSubgroupPartitionedAdd:
6215 case glslang::EOpSubgroupPartitionedMul:
6216 case glslang::EOpSubgroupPartitionedMin:
6217 case glslang::EOpSubgroupPartitionedMax:
6218 case glslang::EOpSubgroupPartitionedAnd:
6219 case glslang::EOpSubgroupPartitionedOr:
6220 case glslang::EOpSubgroupPartitionedXor:
6221 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6222 case glslang::EOpSubgroupPartitionedInclusiveMul:
6223 case glslang::EOpSubgroupPartitionedInclusiveMin:
6224 case glslang::EOpSubgroupPartitionedInclusiveMax:
6225 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6226 case glslang::EOpSubgroupPartitionedInclusiveOr:
6227 case glslang::EOpSubgroupPartitionedInclusiveXor:
6228 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6229 case glslang::EOpSubgroupPartitionedExclusiveMul:
6230 case glslang::EOpSubgroupPartitionedExclusiveMin:
6231 case glslang::EOpSubgroupPartitionedExclusiveMax:
6232 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6233 case glslang::EOpSubgroupPartitionedExclusiveOr:
6234 case glslang::EOpSubgroupPartitionedExclusiveXor:
6235#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006236 return createSubgroupOperation(op, typeId, operands, typeProxy);
6237
Rex Xu9d93a232016-05-05 12:30:44 +08006238#ifdef AMD_EXTENSIONS
6239 case glslang::EOpSwizzleInvocations:
6240 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6241 libCall = spv::SwizzleInvocationsAMD;
6242 break;
6243 case glslang::EOpSwizzleInvocationsMasked:
6244 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6245 libCall = spv::SwizzleInvocationsMaskedAMD;
6246 break;
6247 case glslang::EOpWriteInvocation:
6248 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6249 libCall = spv::WriteInvocationAMD;
6250 break;
6251
6252 case glslang::EOpMin3:
6253 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6254 if (isFloat)
6255 libCall = spv::FMin3AMD;
6256 else {
6257 if (isUnsigned)
6258 libCall = spv::UMin3AMD;
6259 else
6260 libCall = spv::SMin3AMD;
6261 }
6262 break;
6263 case glslang::EOpMax3:
6264 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6265 if (isFloat)
6266 libCall = spv::FMax3AMD;
6267 else {
6268 if (isUnsigned)
6269 libCall = spv::UMax3AMD;
6270 else
6271 libCall = spv::SMax3AMD;
6272 }
6273 break;
6274 case glslang::EOpMid3:
6275 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6276 if (isFloat)
6277 libCall = spv::FMid3AMD;
6278 else {
6279 if (isUnsigned)
6280 libCall = spv::UMid3AMD;
6281 else
6282 libCall = spv::SMid3AMD;
6283 }
6284 break;
6285
6286 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006287 if (typeProxy == glslang::EbtFloat16)
6288 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08006289 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
6290 libCall = spv::InterpolateAtVertexAMD;
6291 break;
6292#endif
6293
John Kessenich140f3df2015-06-26 16:58:36 -06006294 default:
6295 return 0;
6296 }
6297
6298 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07006299 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05006300 // Use an extended instruction from the standard library.
6301 // Construct the call arguments, without modifying the original operands vector.
6302 // We might need the remaining arguments, e.g. in the EOpFrexp case.
6303 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08006304 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07006305 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07006306 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06006307 case 0:
6308 // should all be handled by visitAggregate and createNoArgOperation
6309 assert(0);
6310 return 0;
6311 case 1:
6312 // should all be handled by createUnaryOperation
6313 assert(0);
6314 return 0;
6315 case 2:
6316 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
6317 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006318 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006319 // anything 3 or over doesn't have l-value operands, so all should be consumed
6320 assert(consumedOperands == operands.size());
6321 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06006322 break;
6323 }
6324 }
6325
John Kessenich55e7d112015-11-15 21:33:39 -07006326 // Decode the return types that were structures
6327 switch (op) {
6328 case glslang::EOpAddCarry:
6329 case glslang::EOpSubBorrow:
6330 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6331 id = builder.createCompositeExtract(id, typeId0, 0);
6332 break;
6333 case glslang::EOpUMulExtended:
6334 case glslang::EOpIMulExtended:
6335 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
6336 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6337 break;
6338 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006339 {
6340 assert(operands.size() == 2);
6341 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
6342 // "exp" is floating-point type (from HLSL intrinsic)
6343 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
6344 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
6345 builder.createStore(member1, operands[1]);
6346 } else
6347 // "exp" is integer type (from GLSL built-in function)
6348 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
6349 id = builder.createCompositeExtract(id, typeId0, 0);
6350 }
John Kessenich55e7d112015-11-15 21:33:39 -07006351 break;
6352 default:
6353 break;
6354 }
6355
John Kessenich32cfd492016-02-02 12:37:46 -07006356 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006357}
6358
Rex Xu9d93a232016-05-05 12:30:44 +08006359// Intrinsics with no arguments (or no return value, and no precision).
6360spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06006361{
6362 // TODO: get the barrier operands correct
6363
6364 switch (op) {
6365 case glslang::EOpEmitVertex:
6366 builder.createNoResultOp(spv::OpEmitVertex);
6367 return 0;
6368 case glslang::EOpEndPrimitive:
6369 builder.createNoResultOp(spv::OpEndPrimitive);
6370 return 0;
6371 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006372 if (glslangIntermediate->getStage() == EShLangTessControl) {
6373 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
6374 // TODO: prefer the following, when available:
6375 // builder.createControlBarrier(spv::ScopePatch, spv::ScopePatch,
6376 // spv::MemorySemanticsPatchMask |
6377 // spv::MemorySemanticsAcquireReleaseMask);
6378 } else {
6379 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6380 spv::MemorySemanticsWorkgroupMemoryMask |
6381 spv::MemorySemanticsAcquireReleaseMask);
6382 }
John Kessenich140f3df2015-06-26 16:58:36 -06006383 return 0;
6384 case glslang::EOpMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006385 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory |
6386 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006387 return 0;
6388 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich82979362017-12-11 04:02:24 -07006389 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask |
6390 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006391 return 0;
6392 case glslang::EOpMemoryBarrierBuffer:
John Kessenich82979362017-12-11 04:02:24 -07006393 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6394 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006395 return 0;
6396 case glslang::EOpMemoryBarrierImage:
John Kessenich82979362017-12-11 04:02:24 -07006397 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask |
6398 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006399 return 0;
6400 case glslang::EOpMemoryBarrierShared:
John Kessenich82979362017-12-11 04:02:24 -07006401 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask |
6402 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006403 return 0;
6404 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006405 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
6406 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006407 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06006408 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006409 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07006410 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07006411 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006412 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07006413 case glslang::EOpDeviceMemoryBarrier:
6414 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6415 spv::MemorySemanticsImageMemoryMask |
6416 spv::MemorySemanticsAcquireReleaseMask);
6417 return 0;
6418 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
6419 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6420 spv::MemorySemanticsImageMemoryMask |
6421 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006422 return 0;
6423 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07006424 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6425 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006426 return 0;
6427 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006428 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6429 spv::MemorySemanticsWorkgroupMemoryMask |
6430 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006431 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07006432 case glslang::EOpSubgroupBarrier:
6433 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6434 spv::MemorySemanticsAcquireReleaseMask);
6435 return spv::NoResult;
6436 case glslang::EOpSubgroupMemoryBarrier:
6437 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6438 spv::MemorySemanticsAcquireReleaseMask);
6439 return spv::NoResult;
6440 case glslang::EOpSubgroupMemoryBarrierBuffer:
6441 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
6442 spv::MemorySemanticsAcquireReleaseMask);
6443 return spv::NoResult;
6444 case glslang::EOpSubgroupMemoryBarrierImage:
6445 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
6446 spv::MemorySemanticsAcquireReleaseMask);
6447 return spv::NoResult;
6448 case glslang::EOpSubgroupMemoryBarrierShared:
6449 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6450 spv::MemorySemanticsAcquireReleaseMask);
6451 return spv::NoResult;
6452 case glslang::EOpSubgroupElect: {
6453 std::vector<spv::Id> operands;
6454 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
6455 }
Rex Xu9d93a232016-05-05 12:30:44 +08006456#ifdef AMD_EXTENSIONS
6457 case glslang::EOpTime:
6458 {
6459 std::vector<spv::Id> args; // Dummy arguments
6460 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
6461 return builder.setPrecision(id, precision);
6462 }
6463#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006464 default:
Lei Zhang17535f72016-05-04 15:55:59 -04006465 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06006466 return 0;
6467 }
6468}
6469
6470spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
6471{
John Kessenich2f273362015-07-18 22:34:27 -06006472 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06006473 spv::Id id;
6474 if (symbolValues.end() != iter) {
6475 id = iter->second;
6476 return id;
6477 }
6478
6479 // it was not found, create it
6480 id = createSpvVariable(symbol);
6481 symbolValues[symbol->getId()] = id;
6482
Rex Xuc884b4a2016-06-29 15:03:44 +08006483 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006484 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
6485 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
6486 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07006487 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07006488 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06006489 if (symbol->getQualifier().hasIndex())
6490 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
6491 if (symbol->getQualifier().hasComponent())
6492 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06006493 // atomic counters use this:
6494 if (symbol->getQualifier().hasOffset())
6495 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006496 }
6497
scygan2c864272016-05-18 18:09:17 +02006498 if (symbol->getQualifier().hasLocation())
6499 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07006500 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07006501 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07006502 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06006503 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07006504 }
John Kessenich140f3df2015-06-26 16:58:36 -06006505 if (symbol->getQualifier().hasSet())
6506 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07006507 else if (IsDescriptorResource(symbol->getType())) {
6508 // default to 0
6509 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
6510 }
John Kessenich140f3df2015-06-26 16:58:36 -06006511 if (symbol->getQualifier().hasBinding())
6512 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07006513 if (symbol->getQualifier().hasAttachment())
6514 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06006515 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07006516 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06006517 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06006518 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07006519 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06006520 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07006521 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
6522 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
6523 builder.addDecoration(id, spv::DecorationXfbStride, stride);
6524 }
6525 if (symbol->getQualifier().hasXfbOffset())
6526 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006527 }
6528
Rex Xu1da878f2016-02-21 20:59:01 +08006529 if (symbol->getType().isImage()) {
6530 std::vector<spv::Decoration> memory;
6531 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
6532 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07006533 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08006534 }
6535
John Kessenich140f3df2015-06-26 16:58:36 -06006536 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06006537 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06006538 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07006539 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06006540
John Kessenich5611c6d2018-04-05 11:25:02 -06006541 // nonuniform
6542 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
6543
John Kessenichecba76f2017-01-06 00:34:48 -07006544#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08006545 if (builtIn == spv::BuiltInSampleMask) {
6546 spv::Decoration decoration;
6547 // GL_NV_sample_mask_override_coverage extension
6548 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08006549 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08006550 else
6551 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07006552 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08006553 if (decoration != spv::DecorationMax) {
6554 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
6555 }
6556 }
chaoc771d89f2017-01-13 01:10:53 -08006557 else if (builtIn == spv::BuiltInLayer) {
6558 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06006559 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006560 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08006561 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
6562 builder.addExtension(spv::E_SPV_NV_viewport_array2);
6563 }
John Kessenichb41bff62017-08-11 13:07:17 -06006564 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006565 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
6566 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08006567 builder.addCapability(spv::CapabilityShaderStereoViewNV);
6568 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
6569 }
6570 }
6571
chaoc6e5acae2016-12-20 13:28:52 -08006572 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006573 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08006574 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08006575 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
6576 }
chaoc0ad6a4e2016-12-19 16:29:34 -08006577#endif
6578
John Kessenich5d610ee2018-03-07 18:05:55 -07006579 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
6580 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
6581 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
6582 symbol->getType().getQualifier().semanticName);
6583 }
6584
John Kessenich140f3df2015-06-26 16:58:36 -06006585 return id;
6586}
6587
John Kessenich55e7d112015-11-15 21:33:39 -07006588// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07006589// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07006590//
6591// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
6592//
6593// Recursively walk the nodes. The nodes form a tree whose leaves are
6594// regular constants, which themselves are trees that createSpvConstant()
6595// recursively walks. So, this function walks the "top" of the tree:
6596// - emit specialization constant-building instructions for specConstant
6597// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04006598spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07006599{
John Kessenich7cc0e282016-03-20 00:46:02 -06006600 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07006601
qining4f4bb812016-04-03 23:55:17 -04006602 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07006603 if (! node.getQualifier().specConstant) {
6604 // hand off to the non-spec-constant path
6605 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
6606 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04006607 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07006608 nextConst, false);
6609 }
6610
6611 // We now know we have a specialization constant to build
6612
John Kessenichd94c0032016-05-30 19:29:40 -06006613 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04006614 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
6615 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
6616 std::vector<spv::Id> dimConstId;
6617 for (int dim = 0; dim < 3; ++dim) {
6618 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
6619 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07006620 if (specConst) {
6621 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
6622 glslangIntermediate->getLocalSizeSpecId(dim));
6623 }
qining4f4bb812016-04-03 23:55:17 -04006624 }
6625 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
6626 }
6627
6628 // An AST node labelled as specialization constant should be a symbol node.
6629 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
6630 if (auto* sn = node.getAsSymbolNode()) {
6631 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04006632 // Traverse the constant constructor sub tree like generating normal run-time instructions.
6633 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
6634 // will set the builder into spec constant op instruction generating mode.
6635 sub_tree->traverse(this);
6636 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04006637 } else if (auto* const_union_array = &sn->getConstArray()){
6638 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01006639 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
6640 builder.addName(id, sn->getName().c_str());
6641 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07006642 }
6643 }
qining4f4bb812016-04-03 23:55:17 -04006644
6645 // Neither a front-end constant node, nor a specialization constant node with constant union array or
6646 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04006647 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04006648 exit(1);
6649 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07006650}
6651
John Kessenich140f3df2015-06-26 16:58:36 -06006652// Use 'consts' as the flattened glslang source of scalar constants to recursively
6653// build the aggregate SPIR-V constant.
6654//
6655// If there are not enough elements present in 'consts', 0 will be substituted;
6656// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
6657//
qining08408382016-03-21 09:51:37 -04006658spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06006659{
6660 // vector of constants for SPIR-V
6661 std::vector<spv::Id> spvConsts;
6662
6663 // Type is used for struct and array constants
6664 spv::Id typeId = convertGlslangToSpvType(glslangType);
6665
6666 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006667 glslang::TType elementType(glslangType, 0);
6668 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04006669 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006670 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006671 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06006672 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04006673 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006674 } else if (glslangType.getStruct()) {
6675 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
6676 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04006677 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06006678 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06006679 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
6680 bool zero = nextConst >= consts.size();
6681 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006682 case glslang::EbtInt8:
6683 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
6684 break;
6685 case glslang::EbtUint8:
6686 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
6687 break;
6688 case glslang::EbtInt16:
6689 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
6690 break;
6691 case glslang::EbtUint16:
6692 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
6693 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006694 case glslang::EbtInt:
6695 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
6696 break;
6697 case glslang::EbtUint:
6698 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
6699 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006700 case glslang::EbtInt64:
6701 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
6702 break;
6703 case glslang::EbtUint64:
6704 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
6705 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006706 case glslang::EbtFloat:
6707 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
6708 break;
6709 case glslang::EbtDouble:
6710 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
6711 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006712 case glslang::EbtFloat16:
6713 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
6714 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006715 case glslang::EbtBool:
6716 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
6717 break;
6718 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006719 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06006720 break;
6721 }
6722 ++nextConst;
6723 }
6724 } else {
6725 // we have a non-aggregate (scalar) constant
6726 bool zero = nextConst >= consts.size();
6727 spv::Id scalar = 0;
6728 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006729 case glslang::EbtInt8:
6730 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
6731 break;
6732 case glslang::EbtUint8:
6733 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
6734 break;
6735 case glslang::EbtInt16:
6736 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
6737 break;
6738 case glslang::EbtUint16:
6739 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
6740 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006741 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07006742 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006743 break;
6744 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07006745 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006746 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006747 case glslang::EbtInt64:
6748 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
6749 break;
6750 case glslang::EbtUint64:
6751 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
6752 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006753 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07006754 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006755 break;
6756 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07006757 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006758 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006759 case glslang::EbtFloat16:
6760 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
6761 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006762 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07006763 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006764 break;
6765 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006766 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06006767 break;
6768 }
6769 ++nextConst;
6770 return scalar;
6771 }
6772
6773 return builder.makeCompositeConstant(typeId, spvConsts);
6774}
6775
John Kessenich7c1aa102015-10-15 13:29:11 -06006776// Return true if the node is a constant or symbol whose reading has no
6777// non-trivial observable cost or effect.
6778bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
6779{
6780 // don't know what this is
6781 if (node == nullptr)
6782 return false;
6783
6784 // a constant is safe
6785 if (node->getAsConstantUnion() != nullptr)
6786 return true;
6787
6788 // not a symbol means non-trivial
6789 if (node->getAsSymbolNode() == nullptr)
6790 return false;
6791
6792 // a symbol, depends on what's being read
6793 switch (node->getType().getQualifier().storage) {
6794 case glslang::EvqTemporary:
6795 case glslang::EvqGlobal:
6796 case glslang::EvqIn:
6797 case glslang::EvqInOut:
6798 case glslang::EvqConst:
6799 case glslang::EvqConstReadOnly:
6800 case glslang::EvqUniform:
6801 return true;
6802 default:
6803 return false;
6804 }
qining25262b32016-05-06 17:25:16 -04006805}
John Kessenich7c1aa102015-10-15 13:29:11 -06006806
6807// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06006808// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06006809// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06006810// Return true if trivial.
6811bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
6812{
6813 if (node == nullptr)
6814 return false;
6815
John Kessenich84cc15f2017-05-24 16:44:47 -06006816 // count non scalars as trivial, as well as anything coming from HLSL
6817 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06006818 return true;
6819
John Kessenich7c1aa102015-10-15 13:29:11 -06006820 // symbols and constants are trivial
6821 if (isTrivialLeaf(node))
6822 return true;
6823
6824 // otherwise, it needs to be a simple operation or one or two leaf nodes
6825
6826 // not a simple operation
6827 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
6828 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
6829 if (binaryNode == nullptr && unaryNode == nullptr)
6830 return false;
6831
6832 // not on leaf nodes
6833 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
6834 return false;
6835
6836 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
6837 return false;
6838 }
6839
6840 switch (node->getAsOperator()->getOp()) {
6841 case glslang::EOpLogicalNot:
6842 case glslang::EOpConvIntToBool:
6843 case glslang::EOpConvUintToBool:
6844 case glslang::EOpConvFloatToBool:
6845 case glslang::EOpConvDoubleToBool:
6846 case glslang::EOpEqual:
6847 case glslang::EOpNotEqual:
6848 case glslang::EOpLessThan:
6849 case glslang::EOpGreaterThan:
6850 case glslang::EOpLessThanEqual:
6851 case glslang::EOpGreaterThanEqual:
6852 case glslang::EOpIndexDirect:
6853 case glslang::EOpIndexDirectStruct:
6854 case glslang::EOpLogicalXor:
6855 case glslang::EOpAny:
6856 case glslang::EOpAll:
6857 return true;
6858 default:
6859 return false;
6860 }
6861}
6862
6863// Emit short-circuiting code, where 'right' is never evaluated unless
6864// the left side is true (for &&) or false (for ||).
6865spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
6866{
6867 spv::Id boolTypeId = builder.makeBoolType();
6868
6869 // emit left operand
6870 builder.clearAccessChain();
6871 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006872 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006873
6874 // Operands to accumulate OpPhi operands
6875 std::vector<spv::Id> phiOperands;
6876 // accumulate left operand's phi information
6877 phiOperands.push_back(leftId);
6878 phiOperands.push_back(builder.getBuildPoint()->getId());
6879
6880 // Make the two kinds of operation symmetric with a "!"
6881 // || => emit "if (! left) result = right"
6882 // && => emit "if ( left) result = right"
6883 //
6884 // TODO: this runtime "not" for || could be avoided by adding functionality
6885 // to 'builder' to have an "else" without an "then"
6886 if (op == glslang::EOpLogicalOr)
6887 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
6888
6889 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08006890 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06006891
6892 // emit right operand as the "then" part of the "if"
6893 builder.clearAccessChain();
6894 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006895 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006896
6897 // accumulate left operand's phi information
6898 phiOperands.push_back(rightId);
6899 phiOperands.push_back(builder.getBuildPoint()->getId());
6900
6901 // finish the "if"
6902 ifBuilder.makeEndIf();
6903
6904 // phi together the two results
6905 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
6906}
6907
Frank Henigman541f7bb2018-01-16 00:18:26 -05006908#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08006909// Return type Id of the imported set of extended instructions corresponds to the name.
6910// Import this set if it has not been imported yet.
6911spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
6912{
6913 if (extBuiltinMap.find(name) != extBuiltinMap.end())
6914 return extBuiltinMap[name];
6915 else {
Rex Xu51596642016-09-21 18:56:12 +08006916 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08006917 spv::Id extBuiltins = builder.import(name);
6918 extBuiltinMap[name] = extBuiltins;
6919 return extBuiltins;
6920 }
6921}
Frank Henigman541f7bb2018-01-16 00:18:26 -05006922#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006923
John Kessenich140f3df2015-06-26 16:58:36 -06006924}; // end anonymous namespace
6925
6926namespace glslang {
6927
John Kessenich68d78fd2015-07-12 19:28:10 -06006928void GetSpirvVersion(std::string& version)
6929{
John Kessenich9e55f632015-07-15 10:03:39 -06006930 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06006931 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07006932 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06006933 version = buf;
6934}
6935
John Kessenicha372a3e2017-11-02 22:32:14 -06006936// For low-order part of the generator's magic number. Bump up
6937// when there is a change in the style (e.g., if SSA form changes,
6938// or a different instruction sequence to do something gets used).
6939int GetSpirvGeneratorVersion()
6940{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07006941 // return 1; // start
6942 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07006943 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07006944 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07006945 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06006946 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
6947 // versions 4 and 6 each generate OpArrayLength as it has long been done
6948 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06006949}
6950
John Kessenich140f3df2015-06-26 16:58:36 -06006951// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006952void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06006953{
6954 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06006955 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006956 if (out.fail())
6957 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06006958 for (int i = 0; i < (int)spirv.size(); ++i) {
6959 unsigned int word = spirv[i];
6960 out.write((const char*)&word, 4);
6961 }
6962 out.close();
6963}
6964
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006965// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08006966void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006967{
6968 std::ofstream out;
6969 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006970 if (out.fail())
6971 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07006972 out << "\t// " <<
6973 glslang::GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
6974 std::endl;
Flavio15017db2017-02-15 14:29:33 -08006975 if (varName != nullptr) {
6976 out << "\t #pragma once" << std::endl;
6977 out << "const uint32_t " << varName << "[] = {" << std::endl;
6978 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006979 const int WORDS_PER_LINE = 8;
6980 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
6981 out << "\t";
6982 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
6983 const unsigned int word = spirv[i + j];
6984 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
6985 if (i + j + 1 < (int)spirv.size()) {
6986 out << ",";
6987 }
6988 }
6989 out << std::endl;
6990 }
Flavio15017db2017-02-15 14:29:33 -08006991 if (varName != nullptr) {
6992 out << "};";
6993 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006994 out.close();
6995}
6996
John Kessenich140f3df2015-06-26 16:58:36 -06006997//
6998// Set up the glslang traversal
6999//
John Kessenich121853f2017-05-31 17:11:16 -06007000void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06007001{
Lei Zhang17535f72016-05-04 15:55:59 -04007002 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06007003 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04007004}
7005
John Kesseniche7df8e02018-08-22 17:12:46 -06007006#if ENABLE_OPT
7007
7008// Apply the SPIRV-Tools validator to generated SPIR-V.
7009void SpirvToolsLegalize(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
7010 spv::SpvBuildLogger* logger, const SpvOptions* options)
7011{
7012 spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
7013
7014 spvtools::Optimizer optimizer(target_env);
7015 optimizer.SetMessageConsumer(
7016 [](spv_message_level_t level, const char *source, const spv_position_t &position, const char *message) {
7017 auto &out = std::cerr;
7018 switch (level)
7019 {
7020 case SPV_MSG_FATAL:
7021 case SPV_MSG_INTERNAL_ERROR:
7022 case SPV_MSG_ERROR:
7023 out << "error: ";
7024 break;
7025 case SPV_MSG_WARNING:
7026 out << "warning: ";
7027 break;
7028 case SPV_MSG_INFO:
7029 case SPV_MSG_DEBUG:
7030 out << "info: ";
7031 break;
7032 default:
7033 break;
7034 }
7035 if (source)
7036 {
7037 out << source << ":";
7038 }
7039 out << position.line << ":" << position.column << ":" << position.index << ":";
7040 if (message)
7041 {
7042 out << " " << message;
7043 }
7044 out << std::endl;
7045 });
7046
7047 optimizer.RegisterPass(CreateMergeReturnPass());
7048 optimizer.RegisterPass(CreateInlineExhaustivePass());
7049 optimizer.RegisterPass(CreateEliminateDeadFunctionsPass());
7050 optimizer.RegisterPass(CreateScalarReplacementPass());
7051 optimizer.RegisterPass(CreateLocalAccessChainConvertPass());
7052 optimizer.RegisterPass(CreateLocalSingleBlockLoadStoreElimPass());
7053 optimizer.RegisterPass(CreateLocalSingleStoreElimPass());
7054 optimizer.RegisterPass(CreateSimplificationPass());
7055 optimizer.RegisterPass(CreateAggressiveDCEPass());
7056 optimizer.RegisterPass(CreateVectorDCEPass());
7057 optimizer.RegisterPass(CreateDeadInsertElimPass());
7058 optimizer.RegisterPass(CreateAggressiveDCEPass());
7059 optimizer.RegisterPass(CreateDeadBranchElimPass());
7060 optimizer.RegisterPass(CreateBlockMergePass());
7061 optimizer.RegisterPass(CreateLocalMultiStoreElimPass());
7062 optimizer.RegisterPass(CreateIfConversionPass());
7063 optimizer.RegisterPass(CreateSimplificationPass());
7064 optimizer.RegisterPass(CreateAggressiveDCEPass());
7065 optimizer.RegisterPass(CreateVectorDCEPass());
7066 optimizer.RegisterPass(CreateDeadInsertElimPass());
7067 if (options->optimizeSize) {
7068 optimizer.RegisterPass(CreateRedundancyEliminationPass());
7069 // TODO(greg-lunarg): Add this when AMD driver issues are resolved
7070 // optimizer.RegisterPass(CreateCommonUniformElimPass());
7071 }
7072 optimizer.RegisterPass(CreateAggressiveDCEPass());
7073 optimizer.RegisterPass(CreateCFGCleanupPass());
7074
7075 optimizer.Run(spirv.data(), spirv.size(), &spirv);
7076}
7077
7078#endif
7079
John Kessenich121853f2017-05-31 17:11:16 -06007080void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
7081 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04007082{
John Kessenich140f3df2015-06-26 16:58:36 -06007083 TIntermNode* root = intermediate.getTreeRoot();
7084
7085 if (root == 0)
7086 return;
7087
John Kessenich121853f2017-05-31 17:11:16 -06007088 glslang::SpvOptions defaultOptions;
7089 if (options == nullptr)
7090 options = &defaultOptions;
7091
John Kessenich140f3df2015-06-26 16:58:36 -06007092 glslang::GetThreadPoolAllocator().push();
7093
John Kessenich2b5ea9f2018-01-31 18:35:56 -07007094 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06007095 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07007096 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06007097 it.dumpSpv(spirv);
7098
GregFfb03a552018-03-29 11:49:14 -06007099#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06007100 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
7101 // eg. forward and remove memory writes of opaque types.
John Kesseniche7df8e02018-08-22 17:12:46 -06007102 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) &&
GregFcd1f1692017-09-21 18:40:22 -06007103 !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06007104 SpirvToolsLegalize(intermediate, spirv, logger, options);
GregFcd1f1692017-09-21 18:40:22 -06007105 }
7106#endif
7107
John Kessenich140f3df2015-06-26 16:58:36 -06007108 glslang::GetThreadPoolAllocator().pop();
7109}
7110
7111}; // end namespace glslang