blob: c3e794011ec7d50444f48ec3d796b66de7d40909 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
3// Copyright (C) 2015-2016 Google, Inc.
John Kessenich66011cb2018-03-06 16:12:04 -07004// Copyright (C) 2017 ARM Limited.
John Kessenich140f3df2015-06-26 16:58:36 -06005//
John Kessenich927608b2017-01-06 12:34:14 -07006// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06007//
John Kessenich927608b2017-01-06 12:34:14 -07008// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions
10// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060011//
12// Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//
15// Redistributions in binary form must reproduce the above
16// copyright notice, this list of conditions and the following
17// disclaimer in the documentation and/or other materials provided
18// with the distribution.
19//
20// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21// contributors may be used to endorse or promote products derived
22// from this software without specific prior written permission.
23//
John Kessenich927608b2017-01-06 12:34:14 -070024// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060036
37//
John Kessenich140f3df2015-06-26 16:58:36 -060038// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080046 #include "GLSL.std.450.h"
47 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070048 #include "GLSL.ext.EXT.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080050 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080051#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080052#ifdef NV_EXTENSIONS
53 #include "GLSL.ext.NV.h"
54#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060055}
John Kessenich140f3df2015-06-26 16:58:36 -060056
GregFfb03a552018-03-29 11:49:14 -060057#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -060058 #include "spirv-tools/optimizer.hpp"
59 #include "message.h"
GregFcd1f1692017-09-21 18:40:22 -060060#endif
61
GregFfb03a552018-03-29 11:49:14 -060062#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -060063using namespace spvtools;
64#endif
65
John Kessenich140f3df2015-06-26 16:58:36 -060066// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020067#include "../glslang/MachineIndependent/localintermediate.h"
68#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060069#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050070#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060071
John Kessenich140f3df2015-06-26 16:58:36 -060072#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050073#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040074#include <list>
75#include <map>
76#include <stack>
77#include <string>
78#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060079
80namespace {
81
qining4c912612016-04-01 10:35:16 -040082namespace {
83class SpecConstantOpModeGuard {
84public:
85 SpecConstantOpModeGuard(spv::Builder* builder)
86 : builder_(builder) {
87 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040088 }
89 ~SpecConstantOpModeGuard() {
90 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
91 : builder_->setToNormalCodeGenMode();
92 }
qining40887662016-04-03 22:20:42 -040093 void turnOnSpecConstantOpMode() {
94 builder_->setToSpecConstCodeGenMode();
95 }
qining4c912612016-04-01 10:35:16 -040096
97private:
98 spv::Builder* builder_;
99 bool previous_flag_;
100};
John Kessenichead86222018-03-28 18:01:20 -0600101
102struct OpDecorations {
103 spv::Decoration precision;
104 spv::Decoration noContraction;
John Kessenich5611c6d2018-04-05 11:25:02 -0600105 spv::Decoration nonUniform;
John Kessenichead86222018-03-28 18:01:20 -0600106};
107
108} // namespace
qining4c912612016-04-01 10:35:16 -0400109
John Kessenich140f3df2015-06-26 16:58:36 -0600110//
111// The main holder of information for translating glslang to SPIR-V.
112//
113// Derives from the AST walking base class.
114//
115class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
116public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700117 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
118 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700119 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600120
121 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
122 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
123 void visitConstantUnion(glslang::TIntermConstantUnion*);
124 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
125 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
126 void visitSymbol(glslang::TIntermSymbol* symbol);
127 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
128 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
129 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
130
John Kessenichfca82622016-11-26 13:23:20 -0700131 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700132 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600133
134protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700135 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
136 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
137
Rex Xu17ff3432016-10-14 17:41:45 +0800138 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800139 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600140 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100141 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700142 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700143 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
144 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenicha2858d92018-01-31 08:11:18 -0700145 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, unsigned int& dependencyLength) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600146 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600147 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich140f3df2015-06-26 16:58:36 -0600148 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
149 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600150 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
151 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
152 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600153 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kessenichead86222018-03-28 18:01:20 -0600154 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
155 bool lastBufferBlockMember);
John Kessenich0e737842017-03-24 18:38:16 -0600156 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600157 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
158 glslang::TLayoutPacking, const glslang::TQualifier&);
159 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
160 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700161 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700162 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800163 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600164 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700165 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700166 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
167 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700168 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
169 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100170 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600171
John Kessenich6fccb3c2016-09-19 16:01:41 -0600172 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600173 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600174 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600175 void makeFunctions(const glslang::TIntermSequence&);
176 void makeGlobalInitializers(const glslang::TIntermSequence&);
177 void visitFunctions(const glslang::TIntermSequence&);
178 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800179 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600180 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
181 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600182 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
183
John Kessenichead86222018-03-28 18:01:20 -0600184 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
185 glslang::TBasicType typeProxy, bool reduceComparison = true);
186 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
187 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
188 glslang::TBasicType typeProxy);
189 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
190 glslang::TBasicType typeProxy);
191 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
192 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600193 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600194 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800195 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 +0800196 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800197 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700198 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600199 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 +0800200 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600201 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
qining08408382016-03-21 09:51:37 -0400202 spv::Id createSpvConstant(const glslang::TIntermTyped&);
203 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600204 bool isTrivialLeaf(const glslang::TIntermTyped* node);
205 bool isTrivial(const glslang::TIntermTyped* node);
206 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500207#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800208 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500209#endif
John Kessenich66011cb2018-03-06 16:12:04 -0700210 void addPre13Extension(const char* ext)
211 {
212 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
213 builder.addExtension(ext);
214 }
John Kessenich140f3df2015-06-26 16:58:36 -0600215
John Kessenich121853f2017-05-31 17:11:16 -0600216 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600217 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600218 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700219 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600220 int sequenceDepth;
221
Lei Zhang17535f72016-05-04 15:55:59 -0400222 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400223
John Kessenich140f3df2015-06-26 16:58:36 -0600224 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
225 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700226 bool inEntryPoint;
227 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700228 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 -0700229 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600230 const glslang::TIntermediate* glslangIntermediate;
231 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800232 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600233
John Kessenich2f273362015-07-18 22:34:27 -0600234 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600235 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600236 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700237 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700238 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
239 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600240 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700241 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
John Kessenich140f3df2015-06-26 16:58:36 -0600242};
243
244//
245// Helper functions for translating glslang representations to SPIR-V enumerants.
246//
247
248// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700249spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600250{
John Kessenich66e2faf2016-03-12 18:34:36 -0700251 switch (source) {
252 case glslang::EShSourceGlsl:
253 switch (profile) {
254 case ENoProfile:
255 case ECoreProfile:
256 case ECompatibilityProfile:
257 return spv::SourceLanguageGLSL;
258 case EEsProfile:
259 return spv::SourceLanguageESSL;
260 default:
261 return spv::SourceLanguageUnknown;
262 }
263 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600264 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600265 default:
266 return spv::SourceLanguageUnknown;
267 }
268}
269
270// Translate glslang language (stage) to SPIR-V execution model.
271spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
272{
273 switch (stage) {
274 case EShLangVertex: return spv::ExecutionModelVertex;
275 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
276 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
277 case EShLangGeometry: return spv::ExecutionModelGeometry;
278 case EShLangFragment: return spv::ExecutionModelFragment;
279 case EShLangCompute: return spv::ExecutionModelGLCompute;
280 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700281 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600282 return spv::ExecutionModelFragment;
283 }
284}
285
John Kessenich140f3df2015-06-26 16:58:36 -0600286// Translate glslang sampler type to SPIR-V dimensionality.
287spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
288{
289 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700290 case glslang::Esd1D: return spv::Dim1D;
291 case glslang::Esd2D: return spv::Dim2D;
292 case glslang::Esd3D: return spv::Dim3D;
293 case glslang::EsdCube: return spv::DimCube;
294 case glslang::EsdRect: return spv::DimRect;
295 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700296 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600297 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700298 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600299 return spv::Dim2D;
300 }
301}
302
John Kessenichf6640762016-08-01 19:44:00 -0600303// Translate glslang precision to SPIR-V precision decorations.
304spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600305{
John Kessenichf6640762016-08-01 19:44:00 -0600306 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700307 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600308 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600309 default:
310 return spv::NoPrecision;
311 }
312}
313
John Kessenichf6640762016-08-01 19:44:00 -0600314// Translate glslang type to SPIR-V precision decorations.
315spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
316{
317 return TranslatePrecisionDecoration(type.getQualifier().precision);
318}
319
John Kessenich140f3df2015-06-26 16:58:36 -0600320// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600321spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600322{
323 if (type.getBasicType() == glslang::EbtBlock) {
324 switch (type.getQualifier().storage) {
325 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600326 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600327 case glslang::EvqVaryingIn: return spv::DecorationBlock;
328 case glslang::EvqVaryingOut: return spv::DecorationBlock;
329 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700330 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600331 break;
332 }
333 }
334
John Kessenich4016e382016-07-15 11:53:56 -0600335 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600336}
337
Rex Xu1da878f2016-02-21 20:59:01 +0800338// Translate glslang type to SPIR-V memory decorations.
339void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
340{
341 if (qualifier.coherent)
342 memory.push_back(spv::DecorationCoherent);
John Kessenich14b85d32018-06-04 15:36:03 -0600343 if (qualifier.volatil) {
Rex Xu1da878f2016-02-21 20:59:01 +0800344 memory.push_back(spv::DecorationVolatile);
John Kessenich14b85d32018-06-04 15:36:03 -0600345 memory.push_back(spv::DecorationCoherent);
346 }
Rex Xu1da878f2016-02-21 20:59:01 +0800347 if (qualifier.restrict)
348 memory.push_back(spv::DecorationRestrict);
349 if (qualifier.readonly)
350 memory.push_back(spv::DecorationNonWritable);
351 if (qualifier.writeonly)
352 memory.push_back(spv::DecorationNonReadable);
353}
354
John Kessenich140f3df2015-06-26 16:58:36 -0600355// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700356spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600357{
358 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700359 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600360 case glslang::ElmRowMajor:
361 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700362 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600363 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700364 default:
365 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600366 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600367 }
368 } else {
369 switch (type.getBasicType()) {
370 default:
John Kessenich4016e382016-07-15 11:53:56 -0600371 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600372 break;
373 case glslang::EbtBlock:
374 switch (type.getQualifier().storage) {
375 case glslang::EvqUniform:
376 case glslang::EvqBuffer:
377 switch (type.getQualifier().layoutPacking) {
378 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600379 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
380 default:
John Kessenich4016e382016-07-15 11:53:56 -0600381 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600382 }
383 case glslang::EvqVaryingIn:
384 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700385 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600386 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600387 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700388 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600389 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600390 }
391 }
392 }
393}
394
395// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600396// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700397// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800398spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600399{
Rex Xubbceed72016-05-21 09:40:44 +0800400 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700401 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600402 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800403 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700404 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700405 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600406 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800407#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800408 else if (qualifier.explicitInterp) {
409 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800410 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800411 }
Rex Xu9d93a232016-05-05 12:30:44 +0800412#endif
Rex Xubbceed72016-05-21 09:40:44 +0800413 else
John Kessenich4016e382016-07-15 11:53:56 -0600414 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800415}
416
417// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600418// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800419// should be applied.
420spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
421{
422 if (qualifier.patch)
423 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700424 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600425 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700426 else if (qualifier.sample) {
427 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600428 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700429 } else
John Kessenich4016e382016-07-15 11:53:56 -0600430 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600431}
432
John Kessenich92187592016-02-01 13:45:25 -0700433// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700434spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600435{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700436 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600437 return spv::DecorationInvariant;
438 else
John Kessenich4016e382016-07-15 11:53:56 -0600439 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600440}
441
qining9220dbb2016-05-04 17:34:38 -0400442// If glslang type is noContraction, return SPIR-V NoContraction decoration.
443spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
444{
445 if (qualifier.noContraction)
446 return spv::DecorationNoContraction;
447 else
John Kessenich4016e382016-07-15 11:53:56 -0600448 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400449}
450
John Kessenich5611c6d2018-04-05 11:25:02 -0600451// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
452spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
453{
454 if (qualifier.isNonUniform()) {
455 builder.addExtension("SPV_EXT_descriptor_indexing");
456 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
457 return spv::DecorationNonUniformEXT;
458 } else
459 return spv::DecorationMax;
460}
461
David Netoa901ffe2016-06-08 14:11:40 +0100462// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
463// associated capabilities when required. For some built-in variables, a capability
464// is generated only when using the variable in an executable instruction, but not when
465// just declaring a struct member variable with it. This is true for PointSize,
466// ClipDistance, and CullDistance.
467spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600468{
469 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700470 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600471 // Defer adding the capability until the built-in is actually used.
472 if (! memberDeclaration) {
473 switch (glslangIntermediate->getStage()) {
474 case EShLangGeometry:
475 builder.addCapability(spv::CapabilityGeometryPointSize);
476 break;
477 case EShLangTessControl:
478 case EShLangTessEvaluation:
479 builder.addCapability(spv::CapabilityTessellationPointSize);
480 break;
481 default:
482 break;
483 }
John Kessenich92187592016-02-01 13:45:25 -0700484 }
485 return spv::BuiltInPointSize;
486
John Kessenichebb50532016-05-16 19:22:05 -0600487 // These *Distance capabilities logically belong here, but if the member is declared and
488 // then never used, consumers of SPIR-V prefer the capability not be declared.
489 // They are now generated when used, rather than here when declared.
490 // Potentially, the specification should be more clear what the minimum
491 // use needed is to trigger the capability.
492 //
John Kessenich92187592016-02-01 13:45:25 -0700493 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100494 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800495 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700496 return spv::BuiltInClipDistance;
497
498 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100499 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800500 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700501 return spv::BuiltInCullDistance;
502
503 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600504 builder.addCapability(spv::CapabilityMultiViewport);
505 if (glslangIntermediate->getStage() == EShLangVertex ||
506 glslangIntermediate->getStage() == EShLangTessControl ||
507 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800508
John Kessenichba6a3c22017-09-13 13:22:50 -0600509 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
510 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800511 }
John Kessenich92187592016-02-01 13:45:25 -0700512 return spv::BuiltInViewportIndex;
513
John Kessenich5e801132016-02-15 11:09:46 -0700514 case glslang::EbvSampleId:
515 builder.addCapability(spv::CapabilitySampleRateShading);
516 return spv::BuiltInSampleId;
517
518 case glslang::EbvSamplePosition:
519 builder.addCapability(spv::CapabilitySampleRateShading);
520 return spv::BuiltInSamplePosition;
521
522 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700523 return spv::BuiltInSampleMask;
524
John Kessenich78a45572016-07-08 14:05:15 -0600525 case glslang::EbvLayer:
John Kessenichba6a3c22017-09-13 13:22:50 -0600526 builder.addCapability(spv::CapabilityGeometry);
527 if (glslangIntermediate->getStage() == EShLangVertex ||
528 glslangIntermediate->getStage() == EShLangTessControl ||
529 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800530
John Kessenichba6a3c22017-09-13 13:22:50 -0600531 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
532 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800533 }
John Kessenich78a45572016-07-08 14:05:15 -0600534 return spv::BuiltInLayer;
535
John Kessenich140f3df2015-06-26 16:58:36 -0600536 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600537 case glslang::EbvVertexId: return spv::BuiltInVertexId;
538 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700539 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
540 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800541
John Kessenichda581a22015-10-14 14:10:30 -0600542 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700543 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800544 builder.addCapability(spv::CapabilityDrawParameters);
545 return spv::BuiltInBaseVertex;
546
John Kessenichda581a22015-10-14 14:10:30 -0600547 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700548 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800549 builder.addCapability(spv::CapabilityDrawParameters);
550 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200551
John Kessenichda581a22015-10-14 14:10:30 -0600552 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700553 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800554 builder.addCapability(spv::CapabilityDrawParameters);
555 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200556
557 case glslang::EbvPrimitiveId:
558 if (glslangIntermediate->getStage() == EShLangFragment)
559 builder.addCapability(spv::CapabilityGeometry);
560 return spv::BuiltInPrimitiveId;
561
Rex Xu37cdcee2017-06-29 17:46:34 +0800562 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800563 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
564 builder.addCapability(spv::CapabilityStencilExportEXT);
565 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800566
John Kessenich140f3df2015-06-26 16:58:36 -0600567 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600568 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
569 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
570 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
571 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
572 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
573 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
574 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600575 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
576 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
577 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
578 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
579 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
580 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
581 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
582 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800583
Rex Xu574ab042016-04-14 16:53:07 +0800584 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800585 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800586 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
587 return spv::BuiltInSubgroupSize;
588
Rex Xu574ab042016-04-14 16:53:07 +0800589 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800590 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800591 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
592 return spv::BuiltInSubgroupLocalInvocationId;
593
Rex Xu574ab042016-04-14 16:53:07 +0800594 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800595 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
596 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
597 return spv::BuiltInSubgroupEqMaskKHR;
598
Rex Xu574ab042016-04-14 16:53:07 +0800599 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800600 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
601 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
602 return spv::BuiltInSubgroupGeMaskKHR;
603
Rex Xu574ab042016-04-14 16:53:07 +0800604 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800605 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
606 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
607 return spv::BuiltInSubgroupGtMaskKHR;
608
Rex Xu574ab042016-04-14 16:53:07 +0800609 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800610 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
611 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
612 return spv::BuiltInSubgroupLeMaskKHR;
613
Rex Xu574ab042016-04-14 16:53:07 +0800614 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800615 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
616 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
617 return spv::BuiltInSubgroupLtMaskKHR;
618
John Kessenich66011cb2018-03-06 16:12:04 -0700619 case glslang::EbvNumSubgroups:
620 builder.addCapability(spv::CapabilityGroupNonUniform);
621 return spv::BuiltInNumSubgroups;
622
623 case glslang::EbvSubgroupID:
624 builder.addCapability(spv::CapabilityGroupNonUniform);
625 return spv::BuiltInSubgroupId;
626
627 case glslang::EbvSubgroupSize2:
628 builder.addCapability(spv::CapabilityGroupNonUniform);
629 return spv::BuiltInSubgroupSize;
630
631 case glslang::EbvSubgroupInvocation2:
632 builder.addCapability(spv::CapabilityGroupNonUniform);
633 return spv::BuiltInSubgroupLocalInvocationId;
634
635 case glslang::EbvSubgroupEqMask2:
636 builder.addCapability(spv::CapabilityGroupNonUniform);
637 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
638 return spv::BuiltInSubgroupEqMask;
639
640 case glslang::EbvSubgroupGeMask2:
641 builder.addCapability(spv::CapabilityGroupNonUniform);
642 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
643 return spv::BuiltInSubgroupGeMask;
644
645 case glslang::EbvSubgroupGtMask2:
646 builder.addCapability(spv::CapabilityGroupNonUniform);
647 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
648 return spv::BuiltInSubgroupGtMask;
649
650 case glslang::EbvSubgroupLeMask2:
651 builder.addCapability(spv::CapabilityGroupNonUniform);
652 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
653 return spv::BuiltInSubgroupLeMask;
654
655 case glslang::EbvSubgroupLtMask2:
656 builder.addCapability(spv::CapabilityGroupNonUniform);
657 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
658 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800659#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800660 case glslang::EbvBaryCoordNoPersp:
661 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
662 return spv::BuiltInBaryCoordNoPerspAMD;
663
664 case glslang::EbvBaryCoordNoPerspCentroid:
665 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
666 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
667
668 case glslang::EbvBaryCoordNoPerspSample:
669 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
670 return spv::BuiltInBaryCoordNoPerspSampleAMD;
671
672 case glslang::EbvBaryCoordSmooth:
673 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
674 return spv::BuiltInBaryCoordSmoothAMD;
675
676 case glslang::EbvBaryCoordSmoothCentroid:
677 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
678 return spv::BuiltInBaryCoordSmoothCentroidAMD;
679
680 case glslang::EbvBaryCoordSmoothSample:
681 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
682 return spv::BuiltInBaryCoordSmoothSampleAMD;
683
684 case glslang::EbvBaryCoordPullModel:
685 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
686 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800687#endif
chaoc771d89f2017-01-13 01:10:53 -0800688
John Kessenich6c8aaac2017-02-27 01:20:51 -0700689 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700690 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700691 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700692 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700693
694 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700695 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700696 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700697 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700698
chaoc771d89f2017-01-13 01:10:53 -0800699#ifdef NV_EXTENSIONS
700 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800701 if (!memberDeclaration) {
702 builder.addExtension(spv::E_SPV_NV_viewport_array2);
703 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
704 }
chaoc771d89f2017-01-13 01:10:53 -0800705 return spv::BuiltInViewportMaskNV;
706 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800707 if (!memberDeclaration) {
708 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
709 builder.addCapability(spv::CapabilityShaderStereoViewNV);
710 }
chaoc771d89f2017-01-13 01:10:53 -0800711 return spv::BuiltInSecondaryPositionNV;
712 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800713 if (!memberDeclaration) {
714 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
715 builder.addCapability(spv::CapabilityShaderStereoViewNV);
716 }
chaoc771d89f2017-01-13 01:10:53 -0800717 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800718 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800719 if (!memberDeclaration) {
720 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
721 builder.addCapability(spv::CapabilityPerViewAttributesNV);
722 }
chaocdf3956c2017-02-14 14:52:34 -0800723 return spv::BuiltInPositionPerViewNV;
724 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800725 if (!memberDeclaration) {
726 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
727 builder.addCapability(spv::CapabilityPerViewAttributesNV);
728 }
chaocdf3956c2017-02-14 14:52:34 -0800729 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700730 case glslang::EbvFragFullyCoveredNV:
731 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
732 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
733 return spv::BuiltInFullyCoveredEXT;
chaoc771d89f2017-01-13 01:10:53 -0800734#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800735 default:
736 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600737 }
738}
739
Rex Xufc618912015-09-09 16:42:49 +0800740// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700741spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800742{
743 assert(type.getBasicType() == glslang::EbtSampler);
744
John Kessenich5d0fa972016-02-15 11:57:00 -0700745 // Check for capabilities
746 switch (type.getQualifier().layoutFormat) {
747 case glslang::ElfRg32f:
748 case glslang::ElfRg16f:
749 case glslang::ElfR11fG11fB10f:
750 case glslang::ElfR16f:
751 case glslang::ElfRgba16:
752 case glslang::ElfRgb10A2:
753 case glslang::ElfRg16:
754 case glslang::ElfRg8:
755 case glslang::ElfR16:
756 case glslang::ElfR8:
757 case glslang::ElfRgba16Snorm:
758 case glslang::ElfRg16Snorm:
759 case glslang::ElfRg8Snorm:
760 case glslang::ElfR16Snorm:
761 case glslang::ElfR8Snorm:
762
763 case glslang::ElfRg32i:
764 case glslang::ElfRg16i:
765 case glslang::ElfRg8i:
766 case glslang::ElfR16i:
767 case glslang::ElfR8i:
768
769 case glslang::ElfRgb10a2ui:
770 case glslang::ElfRg32ui:
771 case glslang::ElfRg16ui:
772 case glslang::ElfRg8ui:
773 case glslang::ElfR16ui:
774 case glslang::ElfR8ui:
775 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
776 break;
777
778 default:
779 break;
780 }
781
782 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800783 switch (type.getQualifier().layoutFormat) {
784 case glslang::ElfNone: return spv::ImageFormatUnknown;
785 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
786 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
787 case glslang::ElfR32f: return spv::ImageFormatR32f;
788 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
789 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
790 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
791 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
792 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
793 case glslang::ElfR16f: return spv::ImageFormatR16f;
794 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
795 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
796 case glslang::ElfRg16: return spv::ImageFormatRg16;
797 case glslang::ElfRg8: return spv::ImageFormatRg8;
798 case glslang::ElfR16: return spv::ImageFormatR16;
799 case glslang::ElfR8: return spv::ImageFormatR8;
800 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
801 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
802 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
803 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
804 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
805 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
806 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
807 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
808 case glslang::ElfR32i: return spv::ImageFormatR32i;
809 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
810 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
811 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
812 case glslang::ElfR16i: return spv::ImageFormatR16i;
813 case glslang::ElfR8i: return spv::ImageFormatR8i;
814 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
815 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
816 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
817 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
818 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
819 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
820 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
821 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
822 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
823 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600824 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800825 }
826}
827
John Kesseniche18fd202018-01-30 11:01:39 -0700828spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +0800829{
John Kesseniche18fd202018-01-30 11:01:39 -0700830 if (selectionNode.getFlatten())
831 return spv::SelectionControlFlattenMask;
832 if (selectionNode.getDontFlatten())
833 return spv::SelectionControlDontFlattenMask;
834 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +0800835}
836
John Kesseniche18fd202018-01-30 11:01:39 -0700837spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -0600838{
John Kesseniche18fd202018-01-30 11:01:39 -0700839 if (switchNode.getFlatten())
840 return spv::SelectionControlFlattenMask;
841 if (switchNode.getDontFlatten())
842 return spv::SelectionControlDontFlattenMask;
843 return spv::SelectionControlMaskNone;
844}
845
John Kessenicha2858d92018-01-31 08:11:18 -0700846// return a non-0 dependency if the dependency argument must be set
847spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
848 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -0700849{
850 spv::LoopControlMask control = spv::LoopControlMaskNone;
851
852 if (loopNode.getDontUnroll())
853 control = control | spv::LoopControlDontUnrollMask;
854 if (loopNode.getUnroll())
855 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -0700856 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -0700857 control = control | spv::LoopControlDependencyInfiniteMask;
858 else if (loopNode.getLoopDependency() > 0) {
859 control = control | spv::LoopControlDependencyLengthMask;
860 dependencyLength = loopNode.getLoopDependency();
861 }
John Kesseniche18fd202018-01-30 11:01:39 -0700862
863 return control;
steve-lunargf1709e72017-05-02 20:14:50 -0600864}
865
John Kessenicha5c5fb62017-05-05 05:09:58 -0600866// Translate glslang type to SPIR-V storage class.
867spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
868{
869 if (type.getQualifier().isPipeInput())
870 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600871 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -0600872 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600873
874 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
875 type.getQualifier().storage == glslang::EvqUniform) {
876 if (type.getBasicType() == glslang::EbtAtomicUint)
877 return spv::StorageClassAtomicCounter;
878 if (type.containsOpaque())
879 return spv::StorageClassUniformConstant;
880 }
881
882 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -0700883 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -0600884 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600885 }
886
887 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600888 if (type.getQualifier().layoutPushConstant)
889 return spv::StorageClassPushConstant;
890 if (type.getBasicType() == glslang::EbtBlock)
891 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600892 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600893 }
John Kessenichbed4e4f2017-09-08 02:38:07 -0600894
895 switch (type.getQualifier().storage) {
896 case glslang::EvqShared: return spv::StorageClassWorkgroup;
897 case glslang::EvqGlobal: return spv::StorageClassPrivate;
898 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
899 case glslang::EvqTemporary: return spv::StorageClassFunction;
900 default:
901 assert(0);
902 break;
903 }
904
905 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600906}
907
John Kessenich5611c6d2018-04-05 11:25:02 -0600908// Add capabilities pertaining to how an array is indexed.
909void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
910 const glslang::TType& indexType)
911{
912 if (indexType.getQualifier().isNonUniform()) {
913 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -0500914 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -0600915 if (baseType.getBasicType() == glslang::EbtSampler) {
916 if (baseType.getQualifier().hasAttachment())
917 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
918 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
919 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
920 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
921 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
922 else if (baseType.isImage())
923 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
924 else if (baseType.isTexture())
925 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
926 } else if (baseType.getBasicType() == glslang::EbtBlock) {
927 if (baseType.getQualifier().storage == glslang::EvqBuffer)
928 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
929 else if (baseType.getQualifier().storage == glslang::EvqUniform)
930 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
931 }
932 } else {
933 // assume a dynamically uniform index
934 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -0500935 if (baseType.getQualifier().hasAttachment()) {
936 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -0600937 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -0500938 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
939 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -0600940 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -0500941 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
942 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -0600943 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -0500944 }
John Kessenich5611c6d2018-04-05 11:25:02 -0600945 }
946 }
947}
948
qining25262b32016-05-06 17:25:16 -0400949// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700950// descriptor set.
951bool IsDescriptorResource(const glslang::TType& type)
952{
John Kessenichf7497e22016-03-08 21:36:22 -0700953 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700954 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700955 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700956
957 // non block...
958 // basically samplerXXX/subpass/sampler/texture are all included
959 // if they are the global-scope-class, not the function parameter
960 // (or local, if they ever exist) class.
961 if (type.getBasicType() == glslang::EbtSampler)
962 return type.getQualifier().isUniformOrBuffer();
963
964 // None of the above.
965 return false;
966}
967
John Kesseniche0b6cad2015-12-24 10:30:13 -0700968void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
969{
970 if (child.layoutMatrix == glslang::ElmNone)
971 child.layoutMatrix = parent.layoutMatrix;
972
973 if (parent.invariant)
974 child.invariant = true;
975 if (parent.nopersp)
976 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800977#ifdef AMD_EXTENSIONS
978 if (parent.explicitInterp)
979 child.explicitInterp = true;
980#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700981 if (parent.flat)
982 child.flat = true;
983 if (parent.centroid)
984 child.centroid = true;
985 if (parent.patch)
986 child.patch = true;
987 if (parent.sample)
988 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800989 if (parent.coherent)
990 child.coherent = true;
991 if (parent.volatil)
992 child.volatil = true;
993 if (parent.restrict)
994 child.restrict = true;
995 if (parent.readonly)
996 child.readonly = true;
997 if (parent.writeonly)
998 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700999}
1000
John Kessenichf2b7f332016-09-01 17:05:23 -06001001bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001002{
John Kessenich7b9fa252016-01-21 18:56:57 -07001003 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001004 // - struct members might inherit from a struct declaration
1005 // (note that non-block structs don't explicitly inherit,
1006 // only implicitly, meaning no decoration involved)
1007 // - affect decorations on the struct members
1008 // (note smooth does not, and expecting something like volatile
1009 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001010 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001011 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001012}
1013
John Kessenich140f3df2015-06-26 16:58:36 -06001014//
1015// Implement the TGlslangToSpvTraverser class.
1016//
1017
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001018TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001019 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1020 : TIntermTraverser(true, false, true),
1021 options(options),
1022 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001023 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001024 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001025 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001026 glslangIntermediate(glslangIntermediate)
1027{
1028 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1029
1030 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001031 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1032 glslangIntermediate->getVersion());
1033
John Kessenich121853f2017-05-31 17:11:16 -06001034 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001035 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001036 builder.setSourceFile(glslangIntermediate->getSourceFile());
1037
1038 // Set the source shader's text. If for SPV version 1.0, include
1039 // a preamble in comments stating the OpModuleProcessed instructions.
1040 // Otherwise, emit those as actual instructions.
1041 std::string text;
1042 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1043 for (int p = 0; p < (int)processes.size(); ++p) {
1044 if (glslangIntermediate->getSpv().spv < 0x00010100) {
1045 text.append("// OpModuleProcessed ");
1046 text.append(processes[p]);
1047 text.append("\n");
1048 } else
1049 builder.addModuleProcessed(processes[p]);
1050 }
1051 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
1052 text.append("#line 1\n");
1053 text.append(glslangIntermediate->getSourceText());
1054 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -06001055 }
John Kessenich140f3df2015-06-26 16:58:36 -06001056 stdBuiltins = builder.import("GLSL.std.450");
1057 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -06001058 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1059 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001060
1061 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001062 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1063 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001064 builder.addSourceExtension(it->c_str());
1065
1066 // Add the top-level modes for this shader.
1067
John Kessenich92187592016-02-01 13:45:25 -07001068 if (glslangIntermediate->getXfbMode()) {
1069 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001070 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001071 }
John Kessenich140f3df2015-06-26 16:58:36 -06001072
1073 unsigned int mode;
1074 switch (glslangIntermediate->getStage()) {
1075 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001076 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001077 break;
1078
steve-lunarge7412492017-03-23 11:56:07 -06001079 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001080 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001081 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001082
steve-lunarge7412492017-03-23 11:56:07 -06001083 glslang::TLayoutGeometry primitive;
1084
1085 if (glslangIntermediate->getStage() == EShLangTessControl) {
1086 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1087 primitive = glslangIntermediate->getOutputPrimitive();
1088 } else {
1089 primitive = glslangIntermediate->getInputPrimitive();
1090 }
1091
1092 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001093 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1094 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1095 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001096 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001097 }
John Kessenich4016e382016-07-15 11:53:56 -06001098 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001099 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1100
John Kesseniche6903322015-10-13 16:29:02 -06001101 switch (glslangIntermediate->getVertexSpacing()) {
1102 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1103 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1104 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001105 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001106 }
John Kessenich4016e382016-07-15 11:53:56 -06001107 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001108 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1109
1110 switch (glslangIntermediate->getVertexOrder()) {
1111 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1112 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001113 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001114 }
John Kessenich4016e382016-07-15 11:53:56 -06001115 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001116 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1117
1118 if (glslangIntermediate->getPointMode())
1119 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001120 break;
1121
1122 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001123 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001124 switch (glslangIntermediate->getInputPrimitive()) {
1125 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1126 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1127 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001128 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001129 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001130 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001131 }
John Kessenich4016e382016-07-15 11:53:56 -06001132 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001133 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001134
John Kessenich140f3df2015-06-26 16:58:36 -06001135 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1136
1137 switch (glslangIntermediate->getOutputPrimitive()) {
1138 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1139 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1140 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001141 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001142 }
John Kessenich4016e382016-07-15 11:53:56 -06001143 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001144 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1145 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1146 break;
1147
1148 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001149 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001150 if (glslangIntermediate->getPixelCenterInteger())
1151 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001152
John Kessenich140f3df2015-06-26 16:58:36 -06001153 if (glslangIntermediate->getOriginUpperLeft())
1154 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001155 else
1156 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001157
1158 if (glslangIntermediate->getEarlyFragmentTests())
1159 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1160
chaocc1204522017-06-30 17:14:30 -07001161 if (glslangIntermediate->getPostDepthCoverage()) {
1162 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1163 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1164 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1165 }
1166
John Kesseniche6903322015-10-13 16:29:02 -06001167 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001168 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1169 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001170 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001171 }
John Kessenich4016e382016-07-15 11:53:56 -06001172 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001173 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1174
1175 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1176 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001177 break;
1178
1179 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001180 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001181 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1182 glslangIntermediate->getLocalSize(1),
1183 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001184 break;
1185
1186 default:
1187 break;
1188 }
John Kessenich140f3df2015-06-26 16:58:36 -06001189}
1190
John Kessenichfca82622016-11-26 13:23:20 -07001191// Finish creating SPV, after the traversal is complete.
1192void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001193{
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
qiningda397332016-03-09 19:54:03 -05001203 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001204}
1205
John Kessenichfca82622016-11-26 13:23:20 -07001206// Write the SPV into 'out'.
1207void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001208{
John Kessenichfca82622016-11-26 13:23:20 -07001209 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001210}
1211
1212//
1213// Implement the traversal functions.
1214//
1215// Return true from interior nodes to have the external traversal
1216// continue on to children. Return false if children were
1217// already processed.
1218//
1219
1220//
qining25262b32016-05-06 17:25:16 -04001221// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001222// - uniform/input reads
1223// - output writes
1224// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1225// - something simple that degenerates into the last bullet
1226//
1227void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1228{
qining75d1d802016-04-06 14:42:01 -04001229 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1230 if (symbol->getType().getQualifier().isSpecConstant())
1231 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1232
John Kessenich140f3df2015-06-26 16:58:36 -06001233 // getSymbolId() will set up all the IO decorations on the first call.
1234 // Formal function parameters were mapped during makeFunctions().
1235 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001236
1237 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1238 if (builder.isPointer(id)) {
1239 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001240 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1241 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1242 iOSet.insert(id);
1243 }
John Kessenich7ba63412015-12-20 17:37:07 -07001244 }
1245
1246 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001247 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001248 // Prepare to generate code for the access
1249
1250 // L-value chains will be computed left to right. We're on the symbol now,
1251 // which is the left-most part of the access chain, so now is "clear" time,
1252 // followed by setting the base.
1253 builder.clearAccessChain();
1254
1255 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001256 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001257 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001258 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001259 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001260 // These are also pure R-values.
1261 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001262 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001263 builder.setAccessChainRValue(id);
1264 else
1265 builder.setAccessChainLValue(id);
1266 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001267
1268 // Process linkage-only nodes for any special additional interface work.
1269 if (linkageOnly) {
1270 if (glslangIntermediate->getHlslFunctionality1()) {
1271 // Map implicit counter buffers to their originating buffers, which should have been
1272 // seen by now, given earlier pruning of unused counters, and preservation of order
1273 // of declaration.
1274 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1275 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1276 // Save possible originating buffers for counter buffers, keyed by
1277 // making the potential counter-buffer name.
1278 std::string keyName = symbol->getName().c_str();
1279 keyName = glslangIntermediate->addCounterBufferName(keyName);
1280 counterOriginator[keyName] = symbol;
1281 } else {
1282 // Handle a counter buffer, by finding the saved originating buffer.
1283 std::string keyName = symbol->getName().c_str();
1284 auto it = counterOriginator.find(keyName);
1285 if (it != counterOriginator.end()) {
1286 id = getSymbolId(it->second);
1287 if (id != spv::NoResult) {
1288 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001289 if (counterId != spv::NoResult) {
1290 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001291 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001292 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001293 }
1294 }
1295 }
1296 }
1297 }
1298 }
John Kessenich140f3df2015-06-26 16:58:36 -06001299}
1300
1301bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1302{
John Kesseniche485c7a2017-05-31 18:50:53 -06001303 builder.setLine(node->getLoc().line);
1304
qining40887662016-04-03 22:20:42 -04001305 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1306 if (node->getType().getQualifier().isSpecConstant())
1307 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1308
John Kessenich140f3df2015-06-26 16:58:36 -06001309 // First, handle special cases
1310 switch (node->getOp()) {
1311 case glslang::EOpAssign:
1312 case glslang::EOpAddAssign:
1313 case glslang::EOpSubAssign:
1314 case glslang::EOpMulAssign:
1315 case glslang::EOpVectorTimesMatrixAssign:
1316 case glslang::EOpVectorTimesScalarAssign:
1317 case glslang::EOpMatrixTimesScalarAssign:
1318 case glslang::EOpMatrixTimesMatrixAssign:
1319 case glslang::EOpDivAssign:
1320 case glslang::EOpModAssign:
1321 case glslang::EOpAndAssign:
1322 case glslang::EOpInclusiveOrAssign:
1323 case glslang::EOpExclusiveOrAssign:
1324 case glslang::EOpLeftShiftAssign:
1325 case glslang::EOpRightShiftAssign:
1326 // A bin-op assign "a += b" means the same thing as "a = a + b"
1327 // where a is evaluated before b. For a simple assignment, GLSL
1328 // says to evaluate the left before the right. So, always, left
1329 // node then right node.
1330 {
1331 // get the left l-value, save it away
1332 builder.clearAccessChain();
1333 node->getLeft()->traverse(this);
1334 spv::Builder::AccessChain lValue = builder.getAccessChain();
1335
1336 // evaluate the right
1337 builder.clearAccessChain();
1338 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001339 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001340
1341 if (node->getOp() != glslang::EOpAssign) {
1342 // the left is also an r-value
1343 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001344 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001345
1346 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001347 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001348 TranslateNoContractionDecoration(node->getType().getQualifier()),
1349 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001350 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001351 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1352 node->getType().getBasicType());
1353
1354 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001355 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001356 }
1357
1358 // store the result
1359 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001360 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001361
1362 // assignments are expressions having an rValue after they are evaluated...
1363 builder.clearAccessChain();
1364 builder.setAccessChainRValue(rValue);
1365 }
1366 return false;
1367 case glslang::EOpIndexDirect:
1368 case glslang::EOpIndexDirectStruct:
1369 {
1370 // Get the left part of the access chain.
1371 node->getLeft()->traverse(this);
1372
1373 // Add the next element in the chain
1374
David Netoa901ffe2016-06-08 14:11:40 +01001375 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001376 if (! node->getLeft()->getType().isArray() &&
1377 node->getLeft()->getType().isVector() &&
1378 node->getOp() == glslang::EOpIndexDirect) {
1379 // This is essentially a hard-coded vector swizzle of size 1,
1380 // so short circuit the access-chain stuff with a swizzle.
1381 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001382 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001383 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001384 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001385 int spvIndex = glslangIndex;
1386 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1387 node->getOp() == glslang::EOpIndexDirectStruct)
1388 {
1389 // This may be, e.g., an anonymous block-member selection, which generally need
1390 // index remapping due to hidden members in anonymous blocks.
1391 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1392 assert(remapper.size() > 0);
1393 spvIndex = remapper[glslangIndex];
1394 }
John Kessenichebb50532016-05-16 19:22:05 -06001395
David Netoa901ffe2016-06-08 14:11:40 +01001396 // normal case for indexing array or structure or block
1397 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1398
1399 // Add capabilities here for accessing PointSize and clip/cull distance.
1400 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001401 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001402 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001403 }
1404 }
1405 return false;
1406 case glslang::EOpIndexIndirect:
1407 {
1408 // Structure or array or vector indirection.
1409 // Will use native SPIR-V access-chain for struct and array indirection;
1410 // matrices are arrays of vectors, so will also work for a matrix.
1411 // Will use the access chain's 'component' for variable index into a vector.
1412
1413 // This adapter is building access chains left to right.
1414 // Set up the access chain to the left.
1415 node->getLeft()->traverse(this);
1416
1417 // save it so that computing the right side doesn't trash it
1418 spv::Builder::AccessChain partial = builder.getAccessChain();
1419
1420 // compute the next index in the chain
1421 builder.clearAccessChain();
1422 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001423 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001424
John Kessenich5611c6d2018-04-05 11:25:02 -06001425 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1426
John Kessenich140f3df2015-06-26 16:58:36 -06001427 // restore the saved access chain
1428 builder.setAccessChain(partial);
1429
1430 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001431 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001432 else
John Kessenichfa668da2015-09-13 14:46:30 -06001433 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001434 }
1435 return false;
1436 case glslang::EOpVectorSwizzle:
1437 {
1438 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001439 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001440 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001441 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001442 }
1443 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001444 case glslang::EOpMatrixSwizzle:
1445 logger->missingFunctionality("matrix swizzle");
1446 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001447 case glslang::EOpLogicalOr:
1448 case glslang::EOpLogicalAnd:
1449 {
1450
1451 // These may require short circuiting, but can sometimes be done as straight
1452 // binary operations. The right operand must be short circuited if it has
1453 // side effects, and should probably be if it is complex.
1454 if (isTrivial(node->getRight()->getAsTyped()))
1455 break; // handle below as a normal binary operation
1456 // otherwise, we need to do dynamic short circuiting on the right operand
1457 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1458 builder.clearAccessChain();
1459 builder.setAccessChainRValue(result);
1460 }
1461 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001462 default:
1463 break;
1464 }
1465
1466 // Assume generic binary op...
1467
John Kessenich32cfd492016-02-02 12:37:46 -07001468 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001469 builder.clearAccessChain();
1470 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001471 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001472
John Kessenich32cfd492016-02-02 12:37:46 -07001473 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001474 builder.clearAccessChain();
1475 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001476 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001477
John Kessenich32cfd492016-02-02 12:37:46 -07001478 // get result
John Kessenichead86222018-03-28 18:01:20 -06001479 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001480 TranslateNoContractionDecoration(node->getType().getQualifier()),
1481 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001482 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001483 convertGlslangToSpvType(node->getType()), left, right,
1484 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001485
John Kessenich50e57562015-12-21 21:21:11 -07001486 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001487 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001488 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001489 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001490 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001491 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001492 return false;
1493 }
John Kessenich140f3df2015-06-26 16:58:36 -06001494}
1495
1496bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1497{
John Kesseniche485c7a2017-05-31 18:50:53 -06001498 builder.setLine(node->getLoc().line);
1499
qining40887662016-04-03 22:20:42 -04001500 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1501 if (node->getType().getQualifier().isSpecConstant())
1502 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1503
John Kessenichfc51d282015-08-19 13:34:18 -06001504 spv::Id result = spv::NoResult;
1505
1506 // try texturing first
1507 result = createImageTextureFunctionCall(node);
1508 if (result != spv::NoResult) {
1509 builder.clearAccessChain();
1510 builder.setAccessChainRValue(result);
1511
1512 return false; // done with this node
1513 }
1514
1515 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001516
1517 if (node->getOp() == glslang::EOpArrayLength) {
1518 // Quite special; won't want to evaluate the operand.
1519
John Kessenich5611c6d2018-04-05 11:25:02 -06001520 // Currently, the front-end does not allow .length() on an array until it is sized,
1521 // except for the last block membeor of an SSBO.
1522 // TODO: If this changes, link-time sized arrays might show up here, and need their
1523 // size extracted.
1524
John Kessenichc9a80832015-09-12 12:17:44 -06001525 // Normal .length() would have been constant folded by the front-end.
1526 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001527 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001528
John Kessenichc9a80832015-09-12 12:17:44 -06001529 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1530 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001531 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1532 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001533
1534 builder.clearAccessChain();
1535 builder.setAccessChainRValue(length);
1536
1537 return false;
1538 }
1539
John Kessenichfc51d282015-08-19 13:34:18 -06001540 // Start by evaluating the operand
1541
John Kessenich8c8505c2016-07-26 12:50:38 -06001542 // Does it need a swizzle inversion? If so, evaluation is inverted;
1543 // operate first on the swizzle base, then apply the swizzle.
1544 spv::Id invertedType = spv::NoType;
1545 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1546 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1547 invertedType = getInvertedSwizzleType(*node->getOperand());
1548
John Kessenich140f3df2015-06-26 16:58:36 -06001549 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001550 if (invertedType != spv::NoType)
1551 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1552 else
1553 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001554
Rex Xufc618912015-09-09 16:42:49 +08001555 spv::Id operand = spv::NoResult;
1556
1557 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1558 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001559 node->getOp() == glslang::EOpAtomicCounter ||
1560 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001561 operand = builder.accessChainGetLValue(); // Special case l-value operands
1562 else
John Kessenich32cfd492016-02-02 12:37:46 -07001563 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001564
John Kessenichead86222018-03-28 18:01:20 -06001565 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001566 TranslateNoContractionDecoration(node->getType().getQualifier()),
1567 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001568
1569 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001570 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001571 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001572
1573 // if not, then possibly an operation
1574 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001575 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001576
1577 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001578 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001579 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001580 builder.addDecoration(result, decorations.nonUniform);
1581 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001582
John Kessenich140f3df2015-06-26 16:58:36 -06001583 builder.clearAccessChain();
1584 builder.setAccessChainRValue(result);
1585
1586 return false; // done with this node
1587 }
1588
1589 // it must be a special case, check...
1590 switch (node->getOp()) {
1591 case glslang::EOpPostIncrement:
1592 case glslang::EOpPostDecrement:
1593 case glslang::EOpPreIncrement:
1594 case glslang::EOpPreDecrement:
1595 {
1596 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001597 spv::Id one = 0;
1598 if (node->getBasicType() == glslang::EbtFloat)
1599 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001600 else if (node->getBasicType() == glslang::EbtDouble)
1601 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001602 else if (node->getBasicType() == glslang::EbtFloat16)
1603 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001604 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1605 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001606 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1607 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001608 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1609 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001610 else
1611 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001612 glslang::TOperator op;
1613 if (node->getOp() == glslang::EOpPreIncrement ||
1614 node->getOp() == glslang::EOpPostIncrement)
1615 op = glslang::EOpAdd;
1616 else
1617 op = glslang::EOpSub;
1618
John Kessenichead86222018-03-28 18:01:20 -06001619 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001620 convertGlslangToSpvType(node->getType()), operand, one,
1621 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001622 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001623
1624 // The result of operation is always stored, but conditionally the
1625 // consumed result. The consumed result is always an r-value.
1626 builder.accessChainStore(result);
1627 builder.clearAccessChain();
1628 if (node->getOp() == glslang::EOpPreIncrement ||
1629 node->getOp() == glslang::EOpPreDecrement)
1630 builder.setAccessChainRValue(result);
1631 else
1632 builder.setAccessChainRValue(operand);
1633 }
1634
1635 return false;
1636
1637 case glslang::EOpEmitStreamVertex:
1638 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1639 return false;
1640 case glslang::EOpEndStreamPrimitive:
1641 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1642 return false;
1643
1644 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001645 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001646 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001647 }
John Kessenich140f3df2015-06-26 16:58:36 -06001648}
1649
1650bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1651{
qining27e04a02016-04-14 16:40:20 -04001652 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1653 if (node->getType().getQualifier().isSpecConstant())
1654 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1655
John Kessenichfc51d282015-08-19 13:34:18 -06001656 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001657 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1658 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001659
1660 // try texturing
1661 result = createImageTextureFunctionCall(node);
1662 if (result != spv::NoResult) {
1663 builder.clearAccessChain();
1664 builder.setAccessChainRValue(result);
1665
1666 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001667#ifdef AMD_EXTENSIONS
1668 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1669#else
John Kessenich56bab042015-09-16 10:54:31 -06001670 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001671#endif
Rex Xufc618912015-09-09 16:42:49 +08001672 // "imageStore" is a special case, which has no result
1673 return false;
1674 }
John Kessenichfc51d282015-08-19 13:34:18 -06001675
John Kessenich140f3df2015-06-26 16:58:36 -06001676 glslang::TOperator binOp = glslang::EOpNull;
1677 bool reduceComparison = true;
1678 bool isMatrix = false;
1679 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001680 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001681
1682 assert(node->getOp());
1683
John Kessenichf6640762016-08-01 19:44:00 -06001684 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001685
1686 switch (node->getOp()) {
1687 case glslang::EOpSequence:
1688 {
1689 if (preVisit)
1690 ++sequenceDepth;
1691 else
1692 --sequenceDepth;
1693
1694 if (sequenceDepth == 1) {
1695 // If this is the parent node of all the functions, we want to see them
1696 // early, so all call points have actual SPIR-V functions to reference.
1697 // In all cases, still let the traverser visit the children for us.
1698 makeFunctions(node->getAsAggregate()->getSequence());
1699
John Kessenich6fccb3c2016-09-19 16:01:41 -06001700 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001701 // anything else gets there, so visit out of order, doing them all now.
1702 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1703
John Kessenich6a60c2f2016-12-08 21:01:59 -07001704 // 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 -06001705 // so do them manually.
1706 visitFunctions(node->getAsAggregate()->getSequence());
1707
1708 return false;
1709 }
1710
1711 return true;
1712 }
1713 case glslang::EOpLinkerObjects:
1714 {
1715 if (visit == glslang::EvPreVisit)
1716 linkageOnly = true;
1717 else
1718 linkageOnly = false;
1719
1720 return true;
1721 }
1722 case glslang::EOpComma:
1723 {
1724 // processing from left to right naturally leaves the right-most
1725 // lying around in the access chain
1726 glslang::TIntermSequence& glslangOperands = node->getSequence();
1727 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1728 glslangOperands[i]->traverse(this);
1729
1730 return false;
1731 }
1732 case glslang::EOpFunction:
1733 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001734 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001735 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001736 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001737 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001738 } else {
1739 handleFunctionEntry(node);
1740 }
1741 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001742 if (inEntryPoint)
1743 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001744 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001745 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001746 }
1747
1748 return true;
1749 case glslang::EOpParameters:
1750 // Parameters will have been consumed by EOpFunction processing, but not
1751 // the body, so we still visited the function node's children, making this
1752 // child redundant.
1753 return false;
1754 case glslang::EOpFunctionCall:
1755 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001756 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001757 if (node->isUserDefined())
1758 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001759 // 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 -07001760 if (result) {
1761 builder.clearAccessChain();
1762 builder.setAccessChainRValue(result);
1763 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001764 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001765
1766 return false;
1767 }
1768 case glslang::EOpConstructMat2x2:
1769 case glslang::EOpConstructMat2x3:
1770 case glslang::EOpConstructMat2x4:
1771 case glslang::EOpConstructMat3x2:
1772 case glslang::EOpConstructMat3x3:
1773 case glslang::EOpConstructMat3x4:
1774 case glslang::EOpConstructMat4x2:
1775 case glslang::EOpConstructMat4x3:
1776 case glslang::EOpConstructMat4x4:
1777 case glslang::EOpConstructDMat2x2:
1778 case glslang::EOpConstructDMat2x3:
1779 case glslang::EOpConstructDMat2x4:
1780 case glslang::EOpConstructDMat3x2:
1781 case glslang::EOpConstructDMat3x3:
1782 case glslang::EOpConstructDMat3x4:
1783 case glslang::EOpConstructDMat4x2:
1784 case glslang::EOpConstructDMat4x3:
1785 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001786 case glslang::EOpConstructIMat2x2:
1787 case glslang::EOpConstructIMat2x3:
1788 case glslang::EOpConstructIMat2x4:
1789 case glslang::EOpConstructIMat3x2:
1790 case glslang::EOpConstructIMat3x3:
1791 case glslang::EOpConstructIMat3x4:
1792 case glslang::EOpConstructIMat4x2:
1793 case glslang::EOpConstructIMat4x3:
1794 case glslang::EOpConstructIMat4x4:
1795 case glslang::EOpConstructUMat2x2:
1796 case glslang::EOpConstructUMat2x3:
1797 case glslang::EOpConstructUMat2x4:
1798 case glslang::EOpConstructUMat3x2:
1799 case glslang::EOpConstructUMat3x3:
1800 case glslang::EOpConstructUMat3x4:
1801 case glslang::EOpConstructUMat4x2:
1802 case glslang::EOpConstructUMat4x3:
1803 case glslang::EOpConstructUMat4x4:
1804 case glslang::EOpConstructBMat2x2:
1805 case glslang::EOpConstructBMat2x3:
1806 case glslang::EOpConstructBMat2x4:
1807 case glslang::EOpConstructBMat3x2:
1808 case glslang::EOpConstructBMat3x3:
1809 case glslang::EOpConstructBMat3x4:
1810 case glslang::EOpConstructBMat4x2:
1811 case glslang::EOpConstructBMat4x3:
1812 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001813 case glslang::EOpConstructF16Mat2x2:
1814 case glslang::EOpConstructF16Mat2x3:
1815 case glslang::EOpConstructF16Mat2x4:
1816 case glslang::EOpConstructF16Mat3x2:
1817 case glslang::EOpConstructF16Mat3x3:
1818 case glslang::EOpConstructF16Mat3x4:
1819 case glslang::EOpConstructF16Mat4x2:
1820 case glslang::EOpConstructF16Mat4x3:
1821 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06001822 isMatrix = true;
1823 // fall through
1824 case glslang::EOpConstructFloat:
1825 case glslang::EOpConstructVec2:
1826 case glslang::EOpConstructVec3:
1827 case glslang::EOpConstructVec4:
1828 case glslang::EOpConstructDouble:
1829 case glslang::EOpConstructDVec2:
1830 case glslang::EOpConstructDVec3:
1831 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001832 case glslang::EOpConstructFloat16:
1833 case glslang::EOpConstructF16Vec2:
1834 case glslang::EOpConstructF16Vec3:
1835 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001836 case glslang::EOpConstructBool:
1837 case glslang::EOpConstructBVec2:
1838 case glslang::EOpConstructBVec3:
1839 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07001840 case glslang::EOpConstructInt8:
1841 case glslang::EOpConstructI8Vec2:
1842 case glslang::EOpConstructI8Vec3:
1843 case glslang::EOpConstructI8Vec4:
1844 case glslang::EOpConstructUint8:
1845 case glslang::EOpConstructU8Vec2:
1846 case glslang::EOpConstructU8Vec3:
1847 case glslang::EOpConstructU8Vec4:
1848 case glslang::EOpConstructInt16:
1849 case glslang::EOpConstructI16Vec2:
1850 case glslang::EOpConstructI16Vec3:
1851 case glslang::EOpConstructI16Vec4:
1852 case glslang::EOpConstructUint16:
1853 case glslang::EOpConstructU16Vec2:
1854 case glslang::EOpConstructU16Vec3:
1855 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001856 case glslang::EOpConstructInt:
1857 case glslang::EOpConstructIVec2:
1858 case glslang::EOpConstructIVec3:
1859 case glslang::EOpConstructIVec4:
1860 case glslang::EOpConstructUint:
1861 case glslang::EOpConstructUVec2:
1862 case glslang::EOpConstructUVec3:
1863 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001864 case glslang::EOpConstructInt64:
1865 case glslang::EOpConstructI64Vec2:
1866 case glslang::EOpConstructI64Vec3:
1867 case glslang::EOpConstructI64Vec4:
1868 case glslang::EOpConstructUint64:
1869 case glslang::EOpConstructU64Vec2:
1870 case glslang::EOpConstructU64Vec3:
1871 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001872 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001873 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001874 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001875 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001876 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001877 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001878 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001879 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001880 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001881 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001882 std::vector<spv::Id> constituents;
1883 for (int c = 0; c < (int)arguments.size(); ++c)
1884 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001885 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001886 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001887 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001888 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001889 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001890
1891 builder.clearAccessChain();
1892 builder.setAccessChainRValue(constructed);
1893
1894 return false;
1895 }
1896
1897 // These six are component-wise compares with component-wise results.
1898 // Forward on to createBinaryOperation(), requesting a vector result.
1899 case glslang::EOpLessThan:
1900 case glslang::EOpGreaterThan:
1901 case glslang::EOpLessThanEqual:
1902 case glslang::EOpGreaterThanEqual:
1903 case glslang::EOpVectorEqual:
1904 case glslang::EOpVectorNotEqual:
1905 {
1906 // Map the operation to a binary
1907 binOp = node->getOp();
1908 reduceComparison = false;
1909 switch (node->getOp()) {
1910 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1911 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1912 default: binOp = node->getOp(); break;
1913 }
1914
1915 break;
1916 }
1917 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001918 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001919 binOp = glslang::EOpMul;
1920 break;
1921 case glslang::EOpOuterProduct:
1922 // two vectors multiplied to make a matrix
1923 binOp = glslang::EOpOuterProduct;
1924 break;
1925 case glslang::EOpDot:
1926 {
qining25262b32016-05-06 17:25:16 -04001927 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001928 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001929 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001930 binOp = glslang::EOpMul;
1931 break;
1932 }
1933 case glslang::EOpMod:
1934 // when an aggregate, this is the floating-point mod built-in function,
1935 // which can be emitted by the one in createBinaryOperation()
1936 binOp = glslang::EOpMod;
1937 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001938 case glslang::EOpEmitVertex:
1939 case glslang::EOpEndPrimitive:
1940 case glslang::EOpBarrier:
1941 case glslang::EOpMemoryBarrier:
1942 case glslang::EOpMemoryBarrierAtomicCounter:
1943 case glslang::EOpMemoryBarrierBuffer:
1944 case glslang::EOpMemoryBarrierImage:
1945 case glslang::EOpMemoryBarrierShared:
1946 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07001947 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001948 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07001949 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001950 case glslang::EOpWorkgroupMemoryBarrier:
1951 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07001952 case glslang::EOpSubgroupBarrier:
1953 case glslang::EOpSubgroupMemoryBarrier:
1954 case glslang::EOpSubgroupMemoryBarrierBuffer:
1955 case glslang::EOpSubgroupMemoryBarrierImage:
1956 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06001957 noReturnValue = true;
1958 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1959 break;
1960
John Kessenich426394d2015-07-23 10:22:48 -06001961 case glslang::EOpAtomicAdd:
1962 case glslang::EOpAtomicMin:
1963 case glslang::EOpAtomicMax:
1964 case glslang::EOpAtomicAnd:
1965 case glslang::EOpAtomicOr:
1966 case glslang::EOpAtomicXor:
1967 case glslang::EOpAtomicExchange:
1968 case glslang::EOpAtomicCompSwap:
1969 atomic = true;
1970 break;
1971
John Kessenich0d0c6d32017-07-23 16:08:26 -06001972 case glslang::EOpAtomicCounterAdd:
1973 case glslang::EOpAtomicCounterSubtract:
1974 case glslang::EOpAtomicCounterMin:
1975 case glslang::EOpAtomicCounterMax:
1976 case glslang::EOpAtomicCounterAnd:
1977 case glslang::EOpAtomicCounterOr:
1978 case glslang::EOpAtomicCounterXor:
1979 case glslang::EOpAtomicCounterExchange:
1980 case glslang::EOpAtomicCounterCompSwap:
1981 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1982 builder.addCapability(spv::CapabilityAtomicStorageOps);
1983 atomic = true;
1984 break;
1985
John Kessenich140f3df2015-06-26 16:58:36 -06001986 default:
1987 break;
1988 }
1989
1990 //
1991 // See if it maps to a regular operation.
1992 //
John Kessenich140f3df2015-06-26 16:58:36 -06001993 if (binOp != glslang::EOpNull) {
1994 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1995 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1996 assert(left && right);
1997
1998 builder.clearAccessChain();
1999 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002000 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002001
2002 builder.clearAccessChain();
2003 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002004 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002005
John Kesseniche485c7a2017-05-31 18:50:53 -06002006 builder.setLine(node->getLoc().line);
John Kessenichead86222018-03-28 18:01:20 -06002007 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002008 TranslateNoContractionDecoration(node->getType().getQualifier()),
2009 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002010 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002011 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002012 left->getType().getBasicType(), reduceComparison);
2013
2014 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002015 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002016 builder.clearAccessChain();
2017 builder.setAccessChainRValue(result);
2018
2019 return false;
2020 }
2021
John Kessenich426394d2015-07-23 10:22:48 -06002022 //
2023 // Create the list of operands.
2024 //
John Kessenich140f3df2015-06-26 16:58:36 -06002025 glslang::TIntermSequence& glslangOperands = node->getSequence();
2026 std::vector<spv::Id> operands;
2027 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002028 // special case l-value operands; there are just a few
2029 bool lvalue = false;
2030 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002031 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002032 case glslang::EOpModf:
2033 if (arg == 1)
2034 lvalue = true;
2035 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002036 case glslang::EOpInterpolateAtSample:
2037 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002038#ifdef AMD_EXTENSIONS
2039 case glslang::EOpInterpolateAtVertex:
2040#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002041 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002042 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002043
2044 // Does it need a swizzle inversion? If so, evaluation is inverted;
2045 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002046 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002047 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2048 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2049 }
Rex Xu7a26c172015-12-08 17:12:09 +08002050 break;
Rex Xud4782c12015-09-06 16:30:11 +08002051 case glslang::EOpAtomicAdd:
2052 case glslang::EOpAtomicMin:
2053 case glslang::EOpAtomicMax:
2054 case glslang::EOpAtomicAnd:
2055 case glslang::EOpAtomicOr:
2056 case glslang::EOpAtomicXor:
2057 case glslang::EOpAtomicExchange:
2058 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002059 case glslang::EOpAtomicCounterAdd:
2060 case glslang::EOpAtomicCounterSubtract:
2061 case glslang::EOpAtomicCounterMin:
2062 case glslang::EOpAtomicCounterMax:
2063 case glslang::EOpAtomicCounterAnd:
2064 case glslang::EOpAtomicCounterOr:
2065 case glslang::EOpAtomicCounterXor:
2066 case glslang::EOpAtomicCounterExchange:
2067 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002068 if (arg == 0)
2069 lvalue = true;
2070 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002071 case glslang::EOpAddCarry:
2072 case glslang::EOpSubBorrow:
2073 if (arg == 2)
2074 lvalue = true;
2075 break;
2076 case glslang::EOpUMulExtended:
2077 case glslang::EOpIMulExtended:
2078 if (arg >= 2)
2079 lvalue = true;
2080 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002081 default:
2082 break;
2083 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002084 builder.clearAccessChain();
2085 if (invertedType != spv::NoType && arg == 0)
2086 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2087 else
2088 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002089 if (lvalue)
2090 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002091 else {
2092 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07002093 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002094 }
John Kessenich140f3df2015-06-26 16:58:36 -06002095 }
John Kessenich426394d2015-07-23 10:22:48 -06002096
John Kesseniche485c7a2017-05-31 18:50:53 -06002097 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06002098 if (atomic) {
2099 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002100 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002101 } else {
2102 // Pass through to generic operations.
2103 switch (glslangOperands.size()) {
2104 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002105 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002106 break;
2107 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002108 {
2109 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002110 TranslateNoContractionDecoration(node->getType().getQualifier()),
2111 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002112 result = createUnaryOperation(
2113 node->getOp(), decorations,
2114 resultType(), operands.front(),
2115 glslangOperands[0]->getAsTyped()->getBasicType());
2116 }
John Kessenich426394d2015-07-23 10:22:48 -06002117 break;
2118 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002119 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002120 break;
2121 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002122 if (invertedType)
2123 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002124 }
2125
2126 if (noReturnValue)
2127 return false;
2128
2129 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002130 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002131 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002132 } else {
2133 builder.clearAccessChain();
2134 builder.setAccessChainRValue(result);
2135 return false;
2136 }
2137}
2138
John Kessenich433e9ff2017-01-26 20:31:11 -07002139// This path handles both if-then-else and ?:
2140// The if-then-else has a node type of void, while
2141// ?: has either a void or a non-void node type
2142//
2143// Leaving the result, when not void:
2144// GLSL only has r-values as the result of a :?, but
2145// if we have an l-value, that can be more efficient if it will
2146// become the base of a complex r-value expression, because the
2147// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002148bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2149{
John Kessenich4bee5312018-02-20 21:29:05 -07002150 // See if it simple and safe, or required, to execute both sides.
2151 // Crucially, side effects must be either semantically required or avoided,
2152 // and there are performance trade-offs.
2153 // Return true if required or a good idea (and safe) to execute both sides,
2154 // false otherwise.
2155 const auto bothSidesPolicy = [&]() -> bool {
2156 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002157 if (node->getTrueBlock() == nullptr ||
2158 node->getFalseBlock() == nullptr)
2159 return false;
2160
John Kessenich4bee5312018-02-20 21:29:05 -07002161 // required? (unless we write additional code to look for side effects
2162 // and make performance trade-offs if none are present)
2163 if (!node->getShortCircuit())
2164 return true;
2165
2166 // if not required to execute both, decide based on performance/practicality...
2167
2168 // see if OpSelect can handle it
2169 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2170 node->getBasicType() == glslang::EbtVoid)
2171 return false;
2172
John Kessenich433e9ff2017-01-26 20:31:11 -07002173 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2174 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2175
2176 // return true if a single operand to ? : is okay for OpSelect
2177 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002178 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002179 };
2180
2181 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2182 operandOkay(node->getFalseBlock()->getAsTyped());
2183 };
2184
John Kessenich4bee5312018-02-20 21:29:05 -07002185 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2186 // emit the condition before doing anything with selection
2187 node->getCondition()->traverse(this);
2188 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2189
2190 // Find a way of executing both sides and selecting the right result.
2191 const auto executeBothSides = [&]() -> void {
2192 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002193 node->getTrueBlock()->traverse(this);
2194 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2195 node->getFalseBlock()->traverse(this);
2196 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2197
John Kesseniche485c7a2017-05-31 18:50:53 -06002198 builder.setLine(node->getLoc().line);
2199
John Kessenich4bee5312018-02-20 21:29:05 -07002200 // done if void
2201 if (node->getBasicType() == glslang::EbtVoid)
2202 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002203
John Kessenich4bee5312018-02-20 21:29:05 -07002204 // emit code to select between trueValue and falseValue
2205
2206 // see if OpSelect can handle it
2207 if (node->getType().isScalar() || node->getType().isVector()) {
2208 // Emit OpSelect for this selection.
2209
2210 // smear condition to vector, if necessary (AST is always scalar)
2211 if (builder.isVector(trueValue))
2212 condition = builder.smearScalar(spv::NoPrecision, condition,
2213 builder.makeVectorType(builder.makeBoolType(),
2214 builder.getNumComponents(trueValue)));
2215
2216 // OpSelect
2217 result = builder.createTriOp(spv::OpSelect,
2218 convertGlslangToSpvType(node->getType()), condition,
2219 trueValue, falseValue);
2220
2221 builder.clearAccessChain();
2222 builder.setAccessChainRValue(result);
2223 } else {
2224 // We need control flow to select the result.
2225 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2226 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2227
2228 // Selection control:
2229 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2230
2231 // make an "if" based on the value created by the condition
2232 spv::Builder::If ifBuilder(condition, control, builder);
2233
2234 // emit the "then" statement
2235 builder.createStore(trueValue, result);
2236 ifBuilder.makeBeginElse();
2237 // emit the "else" statement
2238 builder.createStore(falseValue, result);
2239
2240 // finish off the control flow
2241 ifBuilder.makeEndIf();
2242
2243 builder.clearAccessChain();
2244 builder.setAccessChainLValue(result);
2245 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002246 };
2247
John Kessenich4bee5312018-02-20 21:29:05 -07002248 // Execute the one side needed, as per the condition
2249 const auto executeOneSide = [&]() {
2250 // Always emit control flow.
2251 if (node->getBasicType() != glslang::EbtVoid)
2252 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002253
John Kessenich4bee5312018-02-20 21:29:05 -07002254 // Selection control:
2255 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2256
2257 // make an "if" based on the value created by the condition
2258 spv::Builder::If ifBuilder(condition, control, builder);
2259
2260 // emit the "then" statement
2261 if (node->getTrueBlock() != nullptr) {
2262 node->getTrueBlock()->traverse(this);
2263 if (result != spv::NoResult)
2264 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2265 }
2266
2267 if (node->getFalseBlock() != nullptr) {
2268 ifBuilder.makeBeginElse();
2269 // emit the "else" statement
2270 node->getFalseBlock()->traverse(this);
2271 if (result != spv::NoResult)
2272 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2273 }
2274
2275 // finish off the control flow
2276 ifBuilder.makeEndIf();
2277
2278 if (result != spv::NoResult) {
2279 builder.clearAccessChain();
2280 builder.setAccessChainLValue(result);
2281 }
2282 };
2283
2284 // Try for OpSelect (or a requirement to execute both sides)
2285 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002286 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2287 if (node->getType().getQualifier().isSpecConstant())
2288 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002289 executeBothSides();
2290 } else
2291 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002292
2293 return false;
2294}
2295
2296bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2297{
2298 // emit and get the condition before doing anything with switch
2299 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002300 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002301
Rex Xu57e65922017-07-04 23:23:40 +08002302 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002303 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002304
John Kessenich140f3df2015-06-26 16:58:36 -06002305 // browse the children to sort out code segments
2306 int defaultSegment = -1;
2307 std::vector<TIntermNode*> codeSegments;
2308 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2309 std::vector<int> caseValues;
2310 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2311 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2312 TIntermNode* child = *c;
2313 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002314 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002315 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002316 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002317 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2318 } else
2319 codeSegments.push_back(child);
2320 }
2321
qining25262b32016-05-06 17:25:16 -04002322 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002323 // statements between the last case and the end of the switch statement
2324 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2325 (int)codeSegments.size() == defaultSegment)
2326 codeSegments.push_back(nullptr);
2327
2328 // make the switch statement
2329 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002330 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002331
2332 // emit all the code in the segments
2333 breakForLoop.push(false);
2334 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2335 builder.nextSwitchSegment(segmentBlocks, s);
2336 if (codeSegments[s])
2337 codeSegments[s]->traverse(this);
2338 else
2339 builder.addSwitchBreak();
2340 }
2341 breakForLoop.pop();
2342
2343 builder.endSwitch(segmentBlocks);
2344
2345 return false;
2346}
2347
2348void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2349{
2350 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002351 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002352
2353 builder.clearAccessChain();
2354 builder.setAccessChainRValue(constant);
2355}
2356
2357bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2358{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002359 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002360 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002361
2362 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002363 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2364 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002365
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002366 // Spec requires back edges to target header blocks, and every header block
2367 // must dominate its merge block. Make a header block first to ensure these
2368 // conditions are met. By definition, it will contain OpLoopMerge, followed
2369 // by a block-ending branch. But we don't want to put any other body/test
2370 // instructions in it, since the body/test may have arbitrary instructions,
2371 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002372 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002373 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002374 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002375 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002376 spv::Block& test = builder.makeNewBlock();
2377 builder.createBranch(&test);
2378
2379 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002380 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002381 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002382 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2383
2384 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002385 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002386 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002387 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002388 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002389 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002390
2391 builder.setBuildPoint(&blocks.continue_target);
2392 if (node->getTerminal())
2393 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002394 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002395 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002396 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002397 builder.createBranch(&blocks.body);
2398
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002399 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002400 builder.setBuildPoint(&blocks.body);
2401 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002402 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002403 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002404 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002405
2406 builder.setBuildPoint(&blocks.continue_target);
2407 if (node->getTerminal())
2408 node->getTerminal()->traverse(this);
2409 if (node->getTest()) {
2410 node->getTest()->traverse(this);
2411 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002412 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002413 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002414 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002415 // TODO: unless there was a break/return/discard instruction
2416 // somewhere in the body, this is an infinite loop, so we should
2417 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002418 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002419 }
John Kessenich140f3df2015-06-26 16:58:36 -06002420 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002421 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002422 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002423 return false;
2424}
2425
2426bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2427{
2428 if (node->getExpression())
2429 node->getExpression()->traverse(this);
2430
John Kesseniche485c7a2017-05-31 18:50:53 -06002431 builder.setLine(node->getLoc().line);
2432
John Kessenich140f3df2015-06-26 16:58:36 -06002433 switch (node->getFlowOp()) {
2434 case glslang::EOpKill:
2435 builder.makeDiscard();
2436 break;
2437 case glslang::EOpBreak:
2438 if (breakForLoop.top())
2439 builder.createLoopExit();
2440 else
2441 builder.addSwitchBreak();
2442 break;
2443 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002444 builder.createLoopContinue();
2445 break;
2446 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002447 if (node->getExpression()) {
2448 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2449 spv::Id returnId = accessChainLoad(glslangReturnType);
2450 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2451 builder.clearAccessChain();
2452 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2453 builder.setAccessChainLValue(copyId);
2454 multiTypeStore(glslangReturnType, returnId);
2455 returnId = builder.createLoad(copyId);
2456 }
2457 builder.makeReturn(false, returnId);
2458 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002459 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002460
2461 builder.clearAccessChain();
2462 break;
2463
2464 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002465 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002466 break;
2467 }
2468
2469 return false;
2470}
2471
2472spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2473{
qining25262b32016-05-06 17:25:16 -04002474 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002475 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002476 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002477 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002478 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002479 }
2480
2481 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002482 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002483 spv::Id spvType = convertGlslangToSpvType(node->getType());
2484
Rex Xucabbb782017-03-24 13:41:14 +08002485 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2486 node->getType().containsBasicType(glslang::EbtInt16) ||
2487 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002488 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002489 switch (storageClass) {
2490 case spv::StorageClassInput:
2491 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002492 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002493 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002494 break;
2495 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07002496 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002497 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06002498 break;
2499 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07002500 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002501 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2502 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06002503 else
2504 builder.addCapability(spv::CapabilityStorageUniform16);
2505 break;
2506 case spv::StorageClassStorageBuffer:
2507 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
2508 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2509 break;
2510 default:
2511 break;
Rex Xuf89ad982017-04-07 23:22:33 +08002512 }
2513 }
Rex Xuf89ad982017-04-07 23:22:33 +08002514
John Kessenich312dcfb2018-07-03 13:19:51 -06002515 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
2516 node->getType().containsBasicType(glslang::EbtUint8);
2517 if (contains8BitType) {
2518 if (storageClass == spv::StorageClassPushConstant) {
2519 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2520 builder.addCapability(spv::CapabilityStoragePushConstant8);
2521 } else if (storageClass == spv::StorageClassUniform) {
2522 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2523 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
2524 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2525 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
2526 }
2527 }
2528
John Kessenich140f3df2015-06-26 16:58:36 -06002529 const char* name = node->getName().c_str();
2530 if (glslang::IsAnonymous(name))
2531 name = "";
2532
2533 return builder.createVariable(storageClass, spvType, name);
2534}
2535
2536// Return type Id of the sampled type.
2537spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2538{
2539 switch (sampler.type) {
2540 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08002541#ifdef AMD_EXTENSIONS
2542 case glslang::EbtFloat16:
2543 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
2544 builder.addCapability(spv::CapabilityFloat16ImageAMD);
2545 return builder.makeFloatType(16);
2546#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002547 case glslang::EbtInt: return builder.makeIntType(32);
2548 case glslang::EbtUint: return builder.makeUintType(32);
2549 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002550 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002551 return builder.makeFloatType(32);
2552 }
2553}
2554
John Kessenich8c8505c2016-07-26 12:50:38 -06002555// If node is a swizzle operation, return the type that should be used if
2556// the swizzle base is first consumed by another operation, before the swizzle
2557// is applied.
2558spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2559{
John Kessenichecba76f2017-01-06 00:34:48 -07002560 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002561 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2562 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2563 else
2564 return spv::NoType;
2565}
2566
2567// When inverting a swizzle with a parent op, this function
2568// will apply the swizzle operation to a completed parent operation.
2569spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2570{
2571 std::vector<unsigned> swizzle;
2572 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2573 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2574}
2575
John Kessenich8c8505c2016-07-26 12:50:38 -06002576// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2577void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2578{
2579 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2580 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2581 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2582}
2583
John Kessenich3ac051e2015-12-20 11:29:16 -07002584// Convert from a glslang type to an SPV type, by calling into a
2585// recursive version of this function. This establishes the inherited
2586// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002587spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2588{
John Kessenichead86222018-03-28 18:01:20 -06002589 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false);
John Kessenich31ed4832015-09-09 17:51:38 -06002590}
2591
2592// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002593// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002594// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06002595spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
2596 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier, bool lastBufferBlockMember)
John Kessenich31ed4832015-09-09 17:51:38 -06002597{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002598 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002599
2600 switch (type.getBasicType()) {
2601 case glslang::EbtVoid:
2602 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002603 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002604 break;
2605 case glslang::EbtFloat:
2606 spvType = builder.makeFloatType(32);
2607 break;
2608 case glslang::EbtDouble:
2609 spvType = builder.makeFloatType(64);
2610 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002611 case glslang::EbtFloat16:
John Kessenich66011cb2018-03-06 16:12:04 -07002612 builder.addCapability(spv::CapabilityFloat16);
2613#if AMD_EXTENSIONS
2614 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2615 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
2616#endif
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002617 spvType = builder.makeFloatType(16);
2618 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002619 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002620 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2621 // a 32-bit int where non-0 means true.
2622 if (explicitLayout != glslang::ElpNone)
2623 spvType = builder.makeUintType(32);
2624 else
2625 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002626 break;
John Kessenich66011cb2018-03-06 16:12:04 -07002627 case glslang::EbtInt8:
2628 builder.addCapability(spv::CapabilityInt8);
2629 spvType = builder.makeIntType(8);
2630 break;
2631 case glslang::EbtUint8:
2632 builder.addCapability(spv::CapabilityInt8);
2633 spvType = builder.makeUintType(8);
2634 break;
2635 case glslang::EbtInt16:
2636 builder.addCapability(spv::CapabilityInt16);
2637#ifdef AMD_EXTENSIONS
2638 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2639 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2640#endif
2641 spvType = builder.makeIntType(16);
2642 break;
2643 case glslang::EbtUint16:
2644 builder.addCapability(spv::CapabilityInt16);
2645#ifdef AMD_EXTENSIONS
2646 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2647 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2648#endif
2649 spvType = builder.makeUintType(16);
2650 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002651 case glslang::EbtInt:
2652 spvType = builder.makeIntType(32);
2653 break;
2654 case glslang::EbtUint:
2655 spvType = builder.makeUintType(32);
2656 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002657 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002658 spvType = builder.makeIntType(64);
2659 break;
2660 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002661 spvType = builder.makeUintType(64);
2662 break;
John Kessenich426394d2015-07-23 10:22:48 -06002663 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002664 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002665 spvType = builder.makeUintType(32);
2666 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002667 case glslang::EbtSampler:
2668 {
2669 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002670 if (sampler.sampler) {
2671 // pure sampler
2672 spvType = builder.makeSamplerType();
2673 } else {
2674 // an image is present, make its type
2675 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2676 sampler.image ? 2 : 1, TranslateImageFormat(type));
2677 if (sampler.combined) {
2678 // already has both image and sampler, make the combined type
2679 spvType = builder.makeSampledImageType(spvType);
2680 }
John Kessenich55e7d112015-11-15 21:33:39 -07002681 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002682 }
John Kessenich140f3df2015-06-26 16:58:36 -06002683 break;
2684 case glslang::EbtStruct:
2685 case glslang::EbtBlock:
2686 {
2687 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002688 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002689
2690 // Try to share structs for different layouts, but not yet for other
2691 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002692 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002693 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002694 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002695 break;
2696
2697 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002698 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002699 memberRemapper[glslangMembers].resize(glslangMembers->size());
2700 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002701 }
2702 break;
2703 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002704 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002705 break;
2706 }
2707
2708 if (type.isMatrix())
2709 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2710 else {
2711 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2712 if (type.getVectorSize() > 1)
2713 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2714 }
2715
2716 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002717 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2718
John Kessenichc9a80832015-09-12 12:17:44 -06002719 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002720 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002721 // We need to decorate array strides for types needing explicit layout, except blocks.
2722 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002723 // Use a dummy glslang type for querying internal strides of
2724 // arrays of arrays, but using just a one-dimensional array.
2725 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06002726 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
2727 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07002728
2729 // Will compute the higher-order strides here, rather than making a whole
2730 // pile of types and doing repetitive recursion on their contents.
2731 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2732 }
John Kessenichf8842e52016-01-04 19:22:56 -07002733
2734 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002735 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002736 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002737 if (stride > 0)
2738 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002739 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002740 }
2741 } else {
2742 // single-dimensional array, and don't yet have stride
2743
John Kessenichf8842e52016-01-04 19:22:56 -07002744 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002745 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2746 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002747 }
John Kessenich31ed4832015-09-09 17:51:38 -06002748
John Kessenichead86222018-03-28 18:01:20 -06002749 // Do the outer dimension, which might not be known for a runtime-sized array.
2750 // (Unsized arrays that survive through linking will be runtime-sized arrays)
2751 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07002752 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06002753 else {
2754 if (!lastBufferBlockMember) {
2755 builder.addExtension("SPV_EXT_descriptor_indexing");
2756 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
2757 }
John Kessenichead86222018-03-28 18:01:20 -06002758 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06002759 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002760 if (stride > 0)
2761 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002762 }
2763
2764 return spvType;
2765}
2766
John Kessenich0e737842017-03-24 18:38:16 -06002767// TODO: this functionality should exist at a higher level, in creating the AST
2768//
2769// Identify interface members that don't have their required extension turned on.
2770//
2771bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2772{
2773 auto& extensions = glslangIntermediate->getRequestedExtensions();
2774
Rex Xubcf291a2017-03-29 23:01:36 +08002775 if (member.getFieldName() == "gl_ViewportMask" &&
2776 extensions.find("GL_NV_viewport_array2") == extensions.end())
2777 return true;
2778 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2779 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2780 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002781 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2782 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2783 return true;
2784 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2785 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2786 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002787 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2788 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2789 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002790
2791 return false;
2792};
2793
John Kessenich6090df02016-06-30 21:18:02 -06002794// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2795// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2796// Mutually recursive with convertGlslangToSpvType().
2797spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2798 const glslang::TTypeList* glslangMembers,
2799 glslang::TLayoutPacking explicitLayout,
2800 const glslang::TQualifier& qualifier)
2801{
2802 // Create a vector of struct types for SPIR-V to consume
2803 std::vector<spv::Id> spvMembers;
2804 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 -06002805 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2806 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2807 if (glslangMember.hiddenMember()) {
2808 ++memberDelta;
2809 if (type.getBasicType() == glslang::EbtBlock)
2810 memberRemapper[glslangMembers][i] = -1;
2811 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002812 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002813 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002814 if (filterMember(glslangMember))
2815 continue;
2816 }
John Kessenich6090df02016-06-30 21:18:02 -06002817 // modify just this child's view of the qualifier
2818 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2819 InheritQualifiers(memberQualifier, qualifier);
2820
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002821 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002822 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002823 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002824
2825 // recurse
John Kessenichead86222018-03-28 18:01:20 -06002826 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
2827 i == (int)glslangMembers->size() - 1;
2828 spvMembers.push_back(
2829 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember));
John Kessenich6090df02016-06-30 21:18:02 -06002830 }
2831 }
2832
2833 // Make the SPIR-V type
2834 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002835 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002836 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2837
2838 // Decorate it
2839 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2840
2841 return spvType;
2842}
2843
2844void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2845 const glslang::TTypeList* glslangMembers,
2846 glslang::TLayoutPacking explicitLayout,
2847 const glslang::TQualifier& qualifier,
2848 spv::Id spvType)
2849{
2850 // Name and decorate the non-hidden members
2851 int offset = -1;
2852 int locationOffset = 0; // for use within the members of this struct
2853 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2854 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2855 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002856 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002857 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002858 if (filterMember(glslangMember))
2859 continue;
2860 }
John Kessenich6090df02016-06-30 21:18:02 -06002861
2862 // modify just this child's view of the qualifier
2863 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2864 InheritQualifiers(memberQualifier, qualifier);
2865
2866 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07002867 if (member < 0)
2868 continue;
2869
2870 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2871 builder.addMemberDecoration(spvType, member,
2872 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2873 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2874 // Add interpolation and auxiliary storage decorations only to
2875 // top-level members of Input and Output storage classes
2876 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2877 type.getQualifier().storage == glslang::EvqVaryingOut) {
2878 if (type.getBasicType() == glslang::EbtBlock ||
2879 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
2880 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2881 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002882 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002883 }
2884 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002885
John Kessenich5d610ee2018-03-07 18:05:55 -07002886 if (type.getBasicType() == glslang::EbtBlock &&
2887 qualifier.storage == glslang::EvqBuffer) {
2888 // Add memory decorations only to top-level members of shader storage block
2889 std::vector<spv::Decoration> memory;
2890 TranslateMemoryDecoration(memberQualifier, memory);
2891 for (unsigned int i = 0; i < memory.size(); ++i)
2892 builder.addMemberDecoration(spvType, member, memory[i]);
2893 }
John Kessenich6090df02016-06-30 21:18:02 -06002894
John Kessenich5d610ee2018-03-07 18:05:55 -07002895 // Location assignment was already completed correctly by the front end,
2896 // just track whether a member needs to be decorated.
2897 // Ignore member locations if the container is an array, as that's
2898 // ill-specified and decisions have been made to not allow this.
2899 if (! type.isArray() && memberQualifier.hasLocation())
2900 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002901
John Kessenich5d610ee2018-03-07 18:05:55 -07002902 if (qualifier.hasLocation()) // track for upcoming inheritance
2903 locationOffset += glslangIntermediate->computeTypeLocationSize(
2904 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06002905
John Kessenich5d610ee2018-03-07 18:05:55 -07002906 // component, XFB, others
2907 if (glslangMember.getQualifier().hasComponent())
2908 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
2909 glslangMember.getQualifier().layoutComponent);
2910 if (glslangMember.getQualifier().hasXfbOffset())
2911 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
2912 glslangMember.getQualifier().layoutXfbOffset);
2913 else if (explicitLayout != glslang::ElpNone) {
2914 // figure out what to do with offset, which is accumulating
2915 int nextOffset;
2916 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2917 if (offset >= 0)
2918 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2919 offset = nextOffset;
2920 }
John Kessenich6090df02016-06-30 21:18:02 -06002921
John Kessenich5d610ee2018-03-07 18:05:55 -07002922 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2923 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
2924 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06002925
John Kessenich5d610ee2018-03-07 18:05:55 -07002926 // built-in variable decorations
2927 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
2928 if (builtIn != spv::BuiltInMax)
2929 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002930
John Kessenich5611c6d2018-04-05 11:25:02 -06002931 // nonuniform
2932 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
2933
John Kessenichead86222018-03-28 18:01:20 -06002934 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
2935 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
2936 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
2937 memberQualifier.semanticName);
2938 }
2939
chaoc771d89f2017-01-13 01:10:53 -08002940#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07002941 if (builtIn == spv::BuiltInLayer) {
2942 // SPV_NV_viewport_array2 extension
2943 if (glslangMember.getQualifier().layoutViewportRelative){
2944 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2945 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2946 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08002947 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002948 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2949 builder.addMemberDecoration(spvType, member,
2950 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
2951 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2952 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2953 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08002954 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002955 }
2956 if (glslangMember.getQualifier().layoutPassthrough) {
2957 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2958 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2959 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2960 }
chaoc771d89f2017-01-13 01:10:53 -08002961#endif
John Kessenich6090df02016-06-30 21:18:02 -06002962 }
2963
2964 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07002965 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2966 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002967 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2968 builder.addCapability(spv::CapabilityGeometryStreams);
2969 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2970 }
John Kessenich6090df02016-06-30 21:18:02 -06002971}
2972
John Kessenich6c292d32016-02-15 20:58:50 -07002973// Turn the expression forming the array size into an id.
2974// This is not quite trivial, because of specialization constants.
2975// Sometimes, a raw constant is turned into an Id, and sometimes
2976// a specialization constant expression is.
2977spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2978{
2979 // First, see if this is sized with a node, meaning a specialization constant:
2980 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2981 if (specNode != nullptr) {
2982 builder.clearAccessChain();
2983 specNode->traverse(this);
2984 return accessChainLoad(specNode->getAsTyped()->getType());
2985 }
qining25262b32016-05-06 17:25:16 -04002986
John Kessenich6c292d32016-02-15 20:58:50 -07002987 // Otherwise, need a compile-time (front end) size, get it:
2988 int size = arraySizes.getDimSize(dim);
2989 assert(size > 0);
2990 return builder.makeUintConstant(size);
2991}
2992
John Kessenich103bef92016-02-08 21:38:15 -07002993// Wrap the builder's accessChainLoad to:
2994// - localize handling of RelaxedPrecision
2995// - use the SPIR-V inferred type instead of another conversion of the glslang type
2996// (avoids unnecessary work and possible type punning for structures)
2997// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002998spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2999{
John Kessenich103bef92016-02-08 21:38:15 -07003000 spv::Id nominalTypeId = builder.accessChainGetInferredType();
John Kessenich5611c6d2018-04-05 11:25:02 -06003001 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
3002 TranslateNonUniformDecoration(type.getQualifier()), nominalTypeId);
John Kessenich103bef92016-02-08 21:38:15 -07003003
3004 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003005 if (type.getBasicType() == glslang::EbtBool) {
3006 if (builder.isScalarType(nominalTypeId)) {
3007 // Conversion for bool
3008 spv::Id boolType = builder.makeBoolType();
3009 if (nominalTypeId != boolType)
3010 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3011 } else if (builder.isVectorType(nominalTypeId)) {
3012 // Conversion for bvec
3013 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3014 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3015 if (nominalTypeId != bvecType)
3016 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3017 }
3018 }
John Kessenich103bef92016-02-08 21:38:15 -07003019
3020 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003021}
3022
Rex Xu27253232016-02-23 17:51:09 +08003023// Wrap the builder's accessChainStore to:
3024// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003025//
3026// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003027void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3028{
3029 // Need to convert to abstract types when necessary
3030 if (type.getBasicType() == glslang::EbtBool) {
3031 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3032
3033 if (builder.isScalarType(nominalTypeId)) {
3034 // Conversion for bool
3035 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003036 if (nominalTypeId != boolType) {
3037 // keep these outside arguments, for determinant order-of-evaluation
3038 spv::Id one = builder.makeUintConstant(1);
3039 spv::Id zero = builder.makeUintConstant(0);
3040 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3041 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003042 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003043 } else if (builder.isVectorType(nominalTypeId)) {
3044 // Conversion for bvec
3045 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3046 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003047 if (nominalTypeId != bvecType) {
3048 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003049 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3050 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3051 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003052 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003053 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3054 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003055 }
3056 }
3057
3058 builder.accessChainStore(rvalue);
3059}
3060
John Kessenich4bf71552016-09-02 11:20:21 -06003061// For storing when types match at the glslang level, but not might match at the
3062// SPIR-V level.
3063//
3064// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003065// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003066// as in a member-decorated way.
3067//
3068// NOTE: This function can handle any store request; if it's not special it
3069// simplifies to a simple OpStore.
3070//
3071// Implicitly uses the existing builder.accessChain as the storage target.
3072void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3073{
John Kessenichb3e24e42016-09-11 12:33:43 -06003074 // we only do the complex path here if it's an aggregate
3075 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003076 accessChainStore(type, rValue);
3077 return;
3078 }
3079
John Kessenichb3e24e42016-09-11 12:33:43 -06003080 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003081 spv::Id rType = builder.getTypeId(rValue);
3082 spv::Id lValue = builder.accessChainGetLValue();
3083 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3084 if (lType == rType) {
3085 accessChainStore(type, rValue);
3086 return;
3087 }
3088
John Kessenichb3e24e42016-09-11 12:33:43 -06003089 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003090 // where the two types were the same type in GLSL. This requires member
3091 // by member copy, recursively.
3092
John Kessenichb3e24e42016-09-11 12:33:43 -06003093 // If an array, copy element by element.
3094 if (type.isArray()) {
3095 glslang::TType glslangElementType(type, 0);
3096 spv::Id elementRType = builder.getContainedTypeId(rType);
3097 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3098 // get the source member
3099 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003100
John Kessenichb3e24e42016-09-11 12:33:43 -06003101 // set up the target storage
3102 builder.clearAccessChain();
3103 builder.setAccessChainLValue(lValue);
3104 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06003105
John Kessenichb3e24e42016-09-11 12:33:43 -06003106 // store the member
3107 multiTypeStore(glslangElementType, elementRValue);
3108 }
3109 } else {
3110 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003111
John Kessenichb3e24e42016-09-11 12:33:43 -06003112 // loop over structure members
3113 const glslang::TTypeList& members = *type.getStruct();
3114 for (int m = 0; m < (int)members.size(); ++m) {
3115 const glslang::TType& glslangMemberType = *members[m].type;
3116
3117 // get the source member
3118 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3119 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3120
3121 // set up the target storage
3122 builder.clearAccessChain();
3123 builder.setAccessChainLValue(lValue);
3124 builder.accessChainPush(builder.makeIntConstant(m));
3125
3126 // store the member
3127 multiTypeStore(glslangMemberType, memberRValue);
3128 }
John Kessenich4bf71552016-09-02 11:20:21 -06003129 }
3130}
3131
John Kessenichf85e8062015-12-19 13:57:10 -07003132// Decide whether or not this type should be
3133// decorated with offsets and strides, and if so
3134// whether std140 or std430 rules should be applied.
3135glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003136{
John Kessenichf85e8062015-12-19 13:57:10 -07003137 // has to be a block
3138 if (type.getBasicType() != glslang::EbtBlock)
3139 return glslang::ElpNone;
3140
3141 // has to be a uniform or buffer block
3142 if (type.getQualifier().storage != glslang::EvqUniform &&
3143 type.getQualifier().storage != glslang::EvqBuffer)
3144 return glslang::ElpNone;
3145
3146 // return the layout to use
3147 switch (type.getQualifier().layoutPacking) {
3148 case glslang::ElpStd140:
3149 case glslang::ElpStd430:
3150 return type.getQualifier().layoutPacking;
3151 default:
3152 return glslang::ElpNone;
3153 }
John Kessenich31ed4832015-09-09 17:51:38 -06003154}
3155
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003156// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003157int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003158{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003159 int size;
John Kessenich49987892015-12-29 17:11:44 -07003160 int stride;
3161 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003162
3163 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003164}
3165
John Kessenich49987892015-12-29 17:11:44 -07003166// 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 -07003167// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003168int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003169{
John Kessenich49987892015-12-29 17:11:44 -07003170 glslang::TType elementType;
3171 elementType.shallowCopy(matrixType);
3172 elementType.clearArraySizes();
3173
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003174 int size;
John Kessenich49987892015-12-29 17:11:44 -07003175 int stride;
3176 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
3177
3178 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003179}
3180
John Kessenich5e4b1242015-08-06 22:53:06 -06003181// Given a member type of a struct, realign the current offset for it, and compute
3182// the next (not yet aligned) offset for the next member, which will get aligned
3183// on the next call.
3184// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3185// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3186// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003187void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003188 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003189{
3190 // this will get a positive value when deemed necessary
3191 nextOffset = -1;
3192
John Kessenich5e4b1242015-08-06 22:53:06 -06003193 // override anything in currentOffset with user-set offset
3194 if (memberType.getQualifier().hasOffset())
3195 currentOffset = memberType.getQualifier().layoutOffset;
3196
3197 // It could be that current linker usage in glslang updated all the layoutOffset,
3198 // in which case the following code does not matter. But, that's not quite right
3199 // once cross-compilation unit GLSL validation is done, as the original user
3200 // settings are needed in layoutOffset, and then the following will come into play.
3201
John Kessenichf85e8062015-12-19 13:57:10 -07003202 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003203 if (! memberType.getQualifier().hasOffset())
3204 currentOffset = -1;
3205
3206 return;
3207 }
3208
John Kessenichf85e8062015-12-19 13:57:10 -07003209 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003210 if (currentOffset < 0)
3211 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003212
John Kessenich5e4b1242015-08-06 22:53:06 -06003213 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3214 // but possibly not yet correctly aligned.
3215
3216 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003217 int dummyStride;
3218 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003219
3220 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003221 // TODO: make this consistent in early phases of code:
3222 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3223 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3224 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06003225 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003226 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003227 int dummySize;
3228 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3229 if (componentAlignment <= 4)
3230 memberAlignment = componentAlignment;
3231 }
3232
3233 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003234 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003235
3236 // Bump up to vec4 if there is a bad straddle
3237 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
3238 glslang::RoundToPow2(currentOffset, 16);
3239
John Kessenich5e4b1242015-08-06 22:53:06 -06003240 nextOffset = currentOffset + memberSize;
3241}
3242
David Netoa901ffe2016-06-08 14:11:40 +01003243void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003244{
David Netoa901ffe2016-06-08 14:11:40 +01003245 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3246 switch (glslangBuiltIn)
3247 {
3248 case glslang::EbvClipDistance:
3249 case glslang::EbvCullDistance:
3250 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003251#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003252 case glslang::EbvViewportMaskNV:
3253 case glslang::EbvSecondaryPositionNV:
3254 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003255 case glslang::EbvPositionPerViewNV:
3256 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08003257#endif
David Netoa901ffe2016-06-08 14:11:40 +01003258 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3259 // Alternately, we could just call this for any glslang built-in, since the
3260 // capability already guards against duplicates.
3261 TranslateBuiltInDecoration(glslangBuiltIn, false);
3262 break;
3263 default:
3264 // Capabilities were already generated when the struct was declared.
3265 break;
3266 }
John Kessenichebb50532016-05-16 19:22:05 -06003267}
3268
John Kessenich6fccb3c2016-09-19 16:01:41 -06003269bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003270{
John Kessenicheee9d532016-09-19 18:09:30 -06003271 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003272}
3273
John Kessenichd41993d2017-09-10 15:21:05 -06003274// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003275// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3276// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003277bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003278{
John Kessenich6a14f782017-12-04 02:48:10 -07003279 assert(qualifier == glslang::EvqIn ||
3280 qualifier == glslang::EvqOut ||
3281 qualifier == glslang::EvqInOut ||
3282 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003283 return qualifier != glslang::EvqConstReadOnly;
3284}
3285
3286// Is parameter pass-by-original?
3287bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3288 bool implicitThisParam)
3289{
3290 if (implicitThisParam) // implicit this
3291 return true;
3292 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003293 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003294 return paramType.containsOpaque() || // sampler, etc.
3295 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3296}
3297
John Kessenich140f3df2015-06-26 16:58:36 -06003298// Make all the functions, skeletally, without actually visiting their bodies.
3299void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3300{
John Kessenichfad62972017-07-18 02:35:46 -06003301 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
3302 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3303 if (paramPrecision != spv::NoPrecision)
3304 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06003305 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06003306 };
3307
John Kessenich140f3df2015-06-26 16:58:36 -06003308 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3309 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003310 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003311 continue;
3312
3313 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003314 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003315 //
qining25262b32016-05-06 17:25:16 -04003316 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003317 // function. What it is an address of varies:
3318 //
John Kessenich4bf71552016-09-02 11:20:21 -06003319 // - "in" parameters not marked as "const" can be written to without modifying the calling
3320 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003321 //
3322 // - "const in" parameters can just be the r-value, as no writes need occur.
3323 //
John Kessenich4bf71552016-09-02 11:20:21 -06003324 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3325 // 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 -06003326
3327 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003328 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003329 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3330
John Kessenichfad62972017-07-18 02:35:46 -06003331 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3332 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003333
John Kessenichfad62972017-07-18 02:35:46 -06003334 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003335 for (int p = 0; p < (int)parameters.size(); ++p) {
3336 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3337 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003338 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003339 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003340 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003341 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3342 else
John Kessenich4bf71552016-09-02 11:20:21 -06003343 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003344 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003345 paramTypes.push_back(typeId);
3346 }
3347
3348 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003349 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3350 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003351 glslFunction->getName().c_str(), paramTypes,
3352 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003353 if (implicitThis)
3354 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003355
3356 // Track function to emit/call later
3357 functionMap[glslFunction->getName().c_str()] = function;
3358
3359 // Set the parameter id's
3360 for (int p = 0; p < (int)parameters.size(); ++p) {
3361 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3362 // give a name too
3363 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3364 }
3365 }
3366}
3367
3368// Process all the initializers, while skipping the functions and link objects
3369void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3370{
3371 builder.setBuildPoint(shaderEntry->getLastBlock());
3372 for (int i = 0; i < (int)initializers.size(); ++i) {
3373 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3374 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3375
3376 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003377 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003378 initializer->traverse(this);
3379 }
3380 }
3381}
3382
3383// Process all the functions, while skipping initializers.
3384void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3385{
3386 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3387 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003388 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003389 node->traverse(this);
3390 }
3391}
3392
3393void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3394{
qining25262b32016-05-06 17:25:16 -04003395 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003396 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003397 currentFunction = functionMap[node->getName().c_str()];
3398 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003399 builder.setBuildPoint(functionBlock);
3400}
3401
Rex Xu04db3f52015-09-16 11:44:02 +08003402void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003403{
Rex Xufc618912015-09-09 16:42:49 +08003404 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003405
3406 glslang::TSampler sampler = {};
3407 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003408#ifdef AMD_EXTENSIONS
3409 bool f16ShadowCompare = false;
3410#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003411 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003412 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3413 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003414#ifdef AMD_EXTENSIONS
3415 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3416#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003417 }
3418
John Kessenich140f3df2015-06-26 16:58:36 -06003419 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3420 builder.clearAccessChain();
3421 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003422
3423 // Special case l-value operands
3424 bool lvalue = false;
3425 switch (node.getOp()) {
3426 case glslang::EOpImageAtomicAdd:
3427 case glslang::EOpImageAtomicMin:
3428 case glslang::EOpImageAtomicMax:
3429 case glslang::EOpImageAtomicAnd:
3430 case glslang::EOpImageAtomicOr:
3431 case glslang::EOpImageAtomicXor:
3432 case glslang::EOpImageAtomicExchange:
3433 case glslang::EOpImageAtomicCompSwap:
3434 if (i == 0)
3435 lvalue = true;
3436 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003437 case glslang::EOpSparseImageLoad:
3438 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3439 lvalue = true;
3440 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003441#ifdef AMD_EXTENSIONS
3442 case glslang::EOpSparseTexture:
3443 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3444 lvalue = true;
3445 break;
3446 case glslang::EOpSparseTextureClamp:
3447 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3448 lvalue = true;
3449 break;
3450 case glslang::EOpSparseTextureLod:
3451 case glslang::EOpSparseTextureOffset:
3452 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
3453 lvalue = true;
3454 break;
3455#else
Rex Xu48edadf2015-12-31 16:11:41 +08003456 case glslang::EOpSparseTexture:
3457 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3458 lvalue = true;
3459 break;
3460 case glslang::EOpSparseTextureClamp:
3461 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3462 lvalue = true;
3463 break;
3464 case glslang::EOpSparseTextureLod:
3465 case glslang::EOpSparseTextureOffset:
3466 if (i == 3)
3467 lvalue = true;
3468 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003469#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003470 case glslang::EOpSparseTextureFetch:
3471 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3472 lvalue = true;
3473 break;
3474 case glslang::EOpSparseTextureFetchOffset:
3475 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3476 lvalue = true;
3477 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003478#ifdef AMD_EXTENSIONS
3479 case glslang::EOpSparseTextureLodOffset:
3480 case glslang::EOpSparseTextureGrad:
3481 case glslang::EOpSparseTextureOffsetClamp:
3482 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
3483 lvalue = true;
3484 break;
3485 case glslang::EOpSparseTextureGradOffset:
3486 case glslang::EOpSparseTextureGradClamp:
3487 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
3488 lvalue = true;
3489 break;
3490 case glslang::EOpSparseTextureGradOffsetClamp:
3491 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
3492 lvalue = true;
3493 break;
3494#else
Rex Xu48edadf2015-12-31 16:11:41 +08003495 case glslang::EOpSparseTextureLodOffset:
3496 case glslang::EOpSparseTextureGrad:
3497 case glslang::EOpSparseTextureOffsetClamp:
3498 if (i == 4)
3499 lvalue = true;
3500 break;
3501 case glslang::EOpSparseTextureGradOffset:
3502 case glslang::EOpSparseTextureGradClamp:
3503 if (i == 5)
3504 lvalue = true;
3505 break;
3506 case glslang::EOpSparseTextureGradOffsetClamp:
3507 if (i == 6)
3508 lvalue = true;
3509 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003510#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08003511 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003512 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3513 lvalue = true;
3514 break;
3515 case glslang::EOpSparseTextureGatherOffset:
3516 case glslang::EOpSparseTextureGatherOffsets:
3517 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3518 lvalue = true;
3519 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003520#ifdef AMD_EXTENSIONS
3521 case glslang::EOpSparseTextureGatherLod:
3522 if (i == 3)
3523 lvalue = true;
3524 break;
3525 case glslang::EOpSparseTextureGatherLodOffset:
3526 case glslang::EOpSparseTextureGatherLodOffsets:
3527 if (i == 4)
3528 lvalue = true;
3529 break;
Rex Xu129799a2017-07-05 17:23:28 +08003530 case glslang::EOpSparseImageLoadLod:
3531 if (i == 3)
3532 lvalue = true;
3533 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003534#endif
Rex Xufc618912015-09-09 16:42:49 +08003535 default:
3536 break;
3537 }
3538
Rex Xu6b86d492015-09-16 17:48:22 +08003539 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003540 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003541 else
John Kessenich32cfd492016-02-02 12:37:46 -07003542 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003543 }
3544}
3545
John Kessenichfc51d282015-08-19 13:34:18 -06003546void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003547{
John Kessenichfc51d282015-08-19 13:34:18 -06003548 builder.clearAccessChain();
3549 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003550 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003551}
John Kessenich140f3df2015-06-26 16:58:36 -06003552
John Kessenichfc51d282015-08-19 13:34:18 -06003553spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3554{
John Kesseniche485c7a2017-05-31 18:50:53 -06003555 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003556 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003557
3558 builder.setLine(node->getLoc().line);
3559
John Kessenichfc51d282015-08-19 13:34:18 -06003560 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003561 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3562 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08003563#ifdef AMD_EXTENSIONS
3564 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
3565 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
3566 : false;
3567#endif
3568
John Kessenichfc51d282015-08-19 13:34:18 -06003569 std::vector<spv::Id> arguments;
3570 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003571 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003572 else
3573 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003574 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003575
3576 spv::Builder::TextureParameters params = { };
3577 params.sampler = arguments[0];
3578
Rex Xu04db3f52015-09-16 11:44:02 +08003579 glslang::TCrackedTextureOp cracked;
3580 node->crackTexture(sampler, cracked);
3581
amhagan05506bb2017-06-13 16:53:02 -04003582 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003583
John Kessenichfc51d282015-08-19 13:34:18 -06003584 // Check for queries
3585 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003586 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3587 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003588 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003589
John Kessenichfc51d282015-08-19 13:34:18 -06003590 switch (node->getOp()) {
3591 case glslang::EOpImageQuerySize:
3592 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003593 if (arguments.size() > 1) {
3594 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003595 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003596 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003597 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003598 case glslang::EOpImageQuerySamples:
3599 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003600 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003601 case glslang::EOpTextureQueryLod:
3602 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003603 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003604 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003605 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003606 case glslang::EOpSparseTexelsResident:
3607 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003608 default:
3609 assert(0);
3610 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003611 }
John Kessenich140f3df2015-06-26 16:58:36 -06003612 }
3613
LoopDawg4425f242018-02-18 11:40:01 -07003614 int components = node->getType().getVectorSize();
3615
3616 if (node->getOp() == glslang::EOpTextureFetch) {
3617 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3618 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3619 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3620 // here around e.g. which ones return scalars or other types.
3621 components = 4;
3622 }
3623
3624 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3625
3626 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3627
Rex Xufc618912015-09-09 16:42:49 +08003628 // Check for image functions other than queries
3629 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003630 std::vector<spv::Id> operands;
3631 auto opIt = arguments.begin();
3632 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003633
3634 // Handle subpass operations
3635 // TODO: GLSL should change to have the "MS" only on the type rather than the
3636 // built-in function.
3637 if (cracked.subpass) {
3638 // add on the (0,0) coordinate
3639 spv::Id zero = builder.makeIntConstant(0);
3640 std::vector<spv::Id> comps;
3641 comps.push_back(zero);
3642 comps.push_back(zero);
3643 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3644 if (sampler.ms) {
3645 operands.push_back(spv::ImageOperandsSampleMask);
3646 operands.push_back(*(opIt++));
3647 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003648 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3649 builder.setPrecision(result, precision);
3650 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003651 }
3652
John Kessenich56bab042015-09-16 10:54:31 -06003653 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003654#ifdef AMD_EXTENSIONS
3655 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3656#else
John Kessenich56bab042015-09-16 10:54:31 -06003657 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003658#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003659 if (sampler.ms) {
3660 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003661 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003662#ifdef AMD_EXTENSIONS
3663 } else if (cracked.lod) {
3664 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3665 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3666
3667 operands.push_back(spv::ImageOperandsLodMask);
3668 operands.push_back(*opIt);
3669#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003670 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003671 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3672 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003673
St0fFa1184dd2018-04-09 21:08:14 +02003674 std::vector<spv::Id> result( 1, builder.createOp(spv::OpImageRead, resultType(), operands) );
LoopDawg4425f242018-02-18 11:40:01 -07003675 builder.setPrecision(result[0], precision);
3676
3677 // If needed, add a conversion constructor to the proper size.
3678 if (components != node->getType().getVectorSize())
3679 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3680
3681 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08003682#ifdef AMD_EXTENSIONS
3683 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3684#else
John Kessenich56bab042015-09-16 10:54:31 -06003685 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003686#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003687 if (sampler.ms) {
3688 operands.push_back(*(opIt + 1));
3689 operands.push_back(spv::ImageOperandsSampleMask);
3690 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003691#ifdef AMD_EXTENSIONS
3692 } else if (cracked.lod) {
3693 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3694 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3695
3696 operands.push_back(*(opIt + 1));
3697 operands.push_back(spv::ImageOperandsLodMask);
3698 operands.push_back(*opIt);
3699#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003700 } else
3701 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003702 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003703 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3704 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003705 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003706#ifdef AMD_EXTENSIONS
3707 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3708#else
Rex Xu5eafa472016-02-19 22:24:03 +08003709 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003710#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003711 builder.addCapability(spv::CapabilitySparseResidency);
3712 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3713 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3714
3715 if (sampler.ms) {
3716 operands.push_back(spv::ImageOperandsSampleMask);
3717 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003718#ifdef AMD_EXTENSIONS
3719 } else if (cracked.lod) {
3720 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3721 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3722
3723 operands.push_back(spv::ImageOperandsLodMask);
3724 operands.push_back(*opIt++);
3725#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003726 }
3727
3728 // Create the return type that was a special structure
3729 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003730 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003731 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3732 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3733
3734 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3735
3736 // Decode the return type
3737 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3738 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003739 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003740 // Process image atomic operations
3741
3742 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3743 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003744 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003745
John Kessenich8c8505c2016-07-26 12:50:38 -06003746 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003747 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003748
3749 std::vector<spv::Id> operands;
3750 operands.push_back(pointer);
3751 for (; opIt != arguments.end(); ++opIt)
3752 operands.push_back(*opIt);
3753
John Kessenich8c8505c2016-07-26 12:50:38 -06003754 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003755 }
3756 }
3757
amhagan05506bb2017-06-13 16:53:02 -04003758#ifdef AMD_EXTENSIONS
3759 // Check for fragment mask functions other than queries
3760 if (cracked.fragMask) {
3761 assert(sampler.ms);
3762
3763 auto opIt = arguments.begin();
3764 std::vector<spv::Id> operands;
3765
3766 // Extract the image if necessary
3767 if (builder.isSampledImage(params.sampler))
3768 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3769
3770 operands.push_back(params.sampler);
3771 ++opIt;
3772
3773 if (sampler.isSubpass()) {
3774 // add on the (0,0) coordinate
3775 spv::Id zero = builder.makeIntConstant(0);
3776 std::vector<spv::Id> comps;
3777 comps.push_back(zero);
3778 comps.push_back(zero);
3779 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3780 }
3781
3782 for (; opIt != arguments.end(); ++opIt)
3783 operands.push_back(*opIt);
3784
3785 spv::Op fragMaskOp = spv::OpNop;
3786 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3787 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3788 else if (node->getOp() == glslang::EOpFragmentFetch)
3789 fragMaskOp = spv::OpFragmentFetchAMD;
3790
3791 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3792 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3793 return builder.createOp(fragMaskOp, resultType(), operands);
3794 }
3795#endif
3796
Rex Xufc618912015-09-09 16:42:49 +08003797 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003798 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003799 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3800
John Kessenichfc51d282015-08-19 13:34:18 -06003801 // check for bias argument
3802 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003803#ifdef AMD_EXTENSIONS
3804 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3805#else
Rex Xu71519fe2015-11-11 15:35:47 +08003806 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003807#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003808 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003809#ifdef AMD_EXTENSIONS
3810 if (cracked.gather)
3811 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08003812
3813 if (f16ShadowCompare)
3814 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003815#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003816 if (cracked.offset)
3817 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003818#ifdef AMD_EXTENSIONS
3819 else if (cracked.offsets)
3820 ++nonBiasArgCount;
3821#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003822 if (cracked.grad)
3823 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003824 if (cracked.lodClamp)
3825 ++nonBiasArgCount;
3826 if (sparse)
3827 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003828
3829 if ((int)arguments.size() > nonBiasArgCount)
3830 bias = true;
3831 }
3832
John Kessenicha5c33d62016-06-02 23:45:21 -06003833 // See if the sampler param should really be just the SPV image part
3834 if (cracked.fetch) {
3835 // a fetch needs to have the image extracted first
3836 if (builder.isSampledImage(params.sampler))
3837 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3838 }
3839
Rex Xu225e0fc2016-11-17 17:47:59 +08003840#ifdef AMD_EXTENSIONS
3841 if (cracked.gather) {
3842 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3843 if (bias || cracked.lod ||
3844 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3845 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003846 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003847 }
3848 }
3849#endif
3850
John Kessenichfc51d282015-08-19 13:34:18 -06003851 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003852
John Kessenichfc51d282015-08-19 13:34:18 -06003853 params.coords = arguments[1];
3854 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003855 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003856
3857 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08003858#ifdef AMD_EXTENSIONS
3859 if (cubeCompare || f16ShadowCompare) {
3860#else
Rex Xu48edadf2015-12-31 16:11:41 +08003861 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08003862#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003863 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003864 ++extraArgs;
3865 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003866 params.Dref = arguments[2];
3867 ++extraArgs;
3868 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003869 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003870 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003871 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003872 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003873 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003874 dRefComp = builder.getNumComponents(params.coords) - 1;
3875 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003876 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3877 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003878
3879 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003880 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003881 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003882 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003883 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3884 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3885 noImplicitLod = true;
3886 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003887
3888 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003889 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003890 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003891 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003892 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003893
3894 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003895 if (cracked.grad) {
3896 params.gradX = arguments[2 + extraArgs];
3897 params.gradY = arguments[3 + extraArgs];
3898 extraArgs += 2;
3899 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003900
3901 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003902 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003903 params.offset = arguments[2 + extraArgs];
3904 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003905 } else if (cracked.offsets) {
3906 params.offsets = arguments[2 + extraArgs];
3907 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003908 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003909
3910 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003911 if (cracked.lodClamp) {
3912 params.lodClamp = arguments[2 + extraArgs];
3913 ++extraArgs;
3914 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003915
3916 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003917 if (sparse) {
3918 params.texelOut = arguments[2 + extraArgs];
3919 ++extraArgs;
3920 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003921
John Kessenich76d4dfc2016-06-16 12:43:23 -06003922 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003923 if (cracked.gather && ! sampler.shadow) {
3924 // default component is 0, if missing, otherwise an argument
3925 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003926 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003927 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003928 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003929 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003930 }
3931
3932 // bias
3933 if (bias) {
3934 params.bias = arguments[2 + extraArgs];
3935 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003936 }
John Kessenichfc51d282015-08-19 13:34:18 -06003937
John Kessenich65336482016-06-16 14:06:26 -06003938 // projective component (might not to move)
3939 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3940 // are divided by the last component of P."
3941 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3942 // unused components will appear after all used components."
3943 if (cracked.proj) {
3944 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3945 int projTargetComp;
3946 switch (sampler.dim) {
3947 case glslang::Esd1D: projTargetComp = 1; break;
3948 case glslang::Esd2D: projTargetComp = 2; break;
3949 case glslang::EsdRect: projTargetComp = 2; break;
3950 default: projTargetComp = projSourceComp; break;
3951 }
3952 // copy the projective coordinate if we have to
3953 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003954 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003955 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3956 projSourceComp);
3957 params.coords = builder.createCompositeInsert(projComp, params.coords,
3958 builder.getTypeId(params.coords), projTargetComp);
3959 }
3960 }
3961
St0fFa1184dd2018-04-09 21:08:14 +02003962 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07003963 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02003964 );
LoopDawg4425f242018-02-18 11:40:01 -07003965
3966 if (components != node->getType().getVectorSize())
3967 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3968
3969 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06003970}
3971
3972spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3973{
3974 // Grab the function's pointer from the previously created function
3975 spv::Function* function = functionMap[node->getName().c_str()];
3976 if (! function)
3977 return 0;
3978
3979 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3980 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3981
3982 // See comments in makeFunctions() for details about the semantics for parameter passing.
3983 //
3984 // These imply we need a four step process:
3985 // 1. Evaluate the arguments
3986 // 2. Allocate and make copies of in, out, and inout arguments
3987 // 3. Make the call
3988 // 4. Copy back the results
3989
John Kessenichd3ed90b2018-05-04 11:43:03 -06003990 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06003991 std::vector<spv::Builder::AccessChain> lValues;
3992 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003993 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003994 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06003995 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003996 // build l-value
3997 builder.clearAccessChain();
3998 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06003999 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004000 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004001 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004002 // save l-value
4003 lValues.push_back(builder.getAccessChain());
4004 } else {
4005 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004006 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004007 }
4008 }
4009
4010 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4011 // copy the original into that space.
4012 //
4013 // Also, build up the list of actual arguments to pass in for the call
4014 int lValueCount = 0;
4015 int rValueCount = 0;
4016 std::vector<spv::Id> spvArgs;
4017 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4018 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004019 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004020 builder.setAccessChain(lValues[lValueCount]);
4021 arg = builder.accessChainGetLValue();
4022 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004023 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004024 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004025 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004026 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4027 // need to copy the input into output space
4028 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004029 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004030 builder.clearAccessChain();
4031 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004032 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004033 }
4034 ++lValueCount;
4035 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004036 // process r-value, which involves a copy for a type mismatch
4037 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4038 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4039 builder.clearAccessChain();
4040 builder.setAccessChainLValue(argCopy);
4041 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4042 arg = builder.createLoad(argCopy);
4043 } else
4044 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004045 ++rValueCount;
4046 }
4047 spvArgs.push_back(arg);
4048 }
4049
4050 // 3. Make the call.
4051 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004052 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004053
4054 // 4. Copy back out an "out" arguments.
4055 lValueCount = 0;
4056 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004057 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004058 ++lValueCount;
4059 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004060 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4061 spv::Id copy = builder.createLoad(spvArgs[a]);
4062 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004063 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004064 }
4065 ++lValueCount;
4066 }
4067 }
4068
4069 return result;
4070}
4071
4072// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004073spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004074 spv::Id typeId, spv::Id left, spv::Id right,
4075 glslang::TBasicType typeProxy, bool reduceComparison)
4076{
John Kessenich66011cb2018-03-06 16:12:04 -07004077 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4078 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004079 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004080
4081 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004082 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004083 bool comparison = false;
4084
4085 switch (op) {
4086 case glslang::EOpAdd:
4087 case glslang::EOpAddAssign:
4088 if (isFloat)
4089 binOp = spv::OpFAdd;
4090 else
4091 binOp = spv::OpIAdd;
4092 break;
4093 case glslang::EOpSub:
4094 case glslang::EOpSubAssign:
4095 if (isFloat)
4096 binOp = spv::OpFSub;
4097 else
4098 binOp = spv::OpISub;
4099 break;
4100 case glslang::EOpMul:
4101 case glslang::EOpMulAssign:
4102 if (isFloat)
4103 binOp = spv::OpFMul;
4104 else
4105 binOp = spv::OpIMul;
4106 break;
4107 case glslang::EOpVectorTimesScalar:
4108 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004109 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004110 if (builder.isVector(right))
4111 std::swap(left, right);
4112 assert(builder.isScalar(right));
4113 needMatchingVectors = false;
4114 binOp = spv::OpVectorTimesScalar;
4115 } else
4116 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004117 break;
4118 case glslang::EOpVectorTimesMatrix:
4119 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004120 binOp = spv::OpVectorTimesMatrix;
4121 break;
4122 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004123 binOp = spv::OpMatrixTimesVector;
4124 break;
4125 case glslang::EOpMatrixTimesScalar:
4126 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004127 binOp = spv::OpMatrixTimesScalar;
4128 break;
4129 case glslang::EOpMatrixTimesMatrix:
4130 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004131 binOp = spv::OpMatrixTimesMatrix;
4132 break;
4133 case glslang::EOpOuterProduct:
4134 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004135 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004136 break;
4137
4138 case glslang::EOpDiv:
4139 case glslang::EOpDivAssign:
4140 if (isFloat)
4141 binOp = spv::OpFDiv;
4142 else if (isUnsigned)
4143 binOp = spv::OpUDiv;
4144 else
4145 binOp = spv::OpSDiv;
4146 break;
4147 case glslang::EOpMod:
4148 case glslang::EOpModAssign:
4149 if (isFloat)
4150 binOp = spv::OpFMod;
4151 else if (isUnsigned)
4152 binOp = spv::OpUMod;
4153 else
4154 binOp = spv::OpSMod;
4155 break;
4156 case glslang::EOpRightShift:
4157 case glslang::EOpRightShiftAssign:
4158 if (isUnsigned)
4159 binOp = spv::OpShiftRightLogical;
4160 else
4161 binOp = spv::OpShiftRightArithmetic;
4162 break;
4163 case glslang::EOpLeftShift:
4164 case glslang::EOpLeftShiftAssign:
4165 binOp = spv::OpShiftLeftLogical;
4166 break;
4167 case glslang::EOpAnd:
4168 case glslang::EOpAndAssign:
4169 binOp = spv::OpBitwiseAnd;
4170 break;
4171 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004172 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004173 binOp = spv::OpLogicalAnd;
4174 break;
4175 case glslang::EOpInclusiveOr:
4176 case glslang::EOpInclusiveOrAssign:
4177 binOp = spv::OpBitwiseOr;
4178 break;
4179 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004180 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004181 binOp = spv::OpLogicalOr;
4182 break;
4183 case glslang::EOpExclusiveOr:
4184 case glslang::EOpExclusiveOrAssign:
4185 binOp = spv::OpBitwiseXor;
4186 break;
4187 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004188 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004189 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004190 break;
4191
4192 case glslang::EOpLessThan:
4193 case glslang::EOpGreaterThan:
4194 case glslang::EOpLessThanEqual:
4195 case glslang::EOpGreaterThanEqual:
4196 case glslang::EOpEqual:
4197 case glslang::EOpNotEqual:
4198 case glslang::EOpVectorEqual:
4199 case glslang::EOpVectorNotEqual:
4200 comparison = true;
4201 break;
4202 default:
4203 break;
4204 }
4205
John Kessenich7c1aa102015-10-15 13:29:11 -06004206 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004207 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004208 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07004209 if (builder.isMatrix(left) || builder.isMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004210 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004211
4212 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004213 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004214 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004215
qining25262b32016-05-06 17:25:16 -04004216 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004217 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004218 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004219 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004220 }
4221
4222 if (! comparison)
4223 return 0;
4224
John Kessenich7c1aa102015-10-15 13:29:11 -06004225 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004226
John Kessenich4583b612016-08-07 19:14:22 -06004227 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004228 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4229 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004230 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004231 return result;
4232 }
John Kessenich140f3df2015-06-26 16:58:36 -06004233
4234 switch (op) {
4235 case glslang::EOpLessThan:
4236 if (isFloat)
4237 binOp = spv::OpFOrdLessThan;
4238 else if (isUnsigned)
4239 binOp = spv::OpULessThan;
4240 else
4241 binOp = spv::OpSLessThan;
4242 break;
4243 case glslang::EOpGreaterThan:
4244 if (isFloat)
4245 binOp = spv::OpFOrdGreaterThan;
4246 else if (isUnsigned)
4247 binOp = spv::OpUGreaterThan;
4248 else
4249 binOp = spv::OpSGreaterThan;
4250 break;
4251 case glslang::EOpLessThanEqual:
4252 if (isFloat)
4253 binOp = spv::OpFOrdLessThanEqual;
4254 else if (isUnsigned)
4255 binOp = spv::OpULessThanEqual;
4256 else
4257 binOp = spv::OpSLessThanEqual;
4258 break;
4259 case glslang::EOpGreaterThanEqual:
4260 if (isFloat)
4261 binOp = spv::OpFOrdGreaterThanEqual;
4262 else if (isUnsigned)
4263 binOp = spv::OpUGreaterThanEqual;
4264 else
4265 binOp = spv::OpSGreaterThanEqual;
4266 break;
4267 case glslang::EOpEqual:
4268 case glslang::EOpVectorEqual:
4269 if (isFloat)
4270 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004271 else if (isBool)
4272 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004273 else
4274 binOp = spv::OpIEqual;
4275 break;
4276 case glslang::EOpNotEqual:
4277 case glslang::EOpVectorNotEqual:
4278 if (isFloat)
4279 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004280 else if (isBool)
4281 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004282 else
4283 binOp = spv::OpINotEqual;
4284 break;
4285 default:
4286 break;
4287 }
4288
qining25262b32016-05-06 17:25:16 -04004289 if (binOp != spv::OpNop) {
4290 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004291 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004292 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004293 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004294 }
John Kessenich140f3df2015-06-26 16:58:36 -06004295
4296 return 0;
4297}
4298
John Kessenich04bb8a02015-12-12 12:28:14 -07004299//
4300// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
4301// These can be any of:
4302//
4303// matrix * scalar
4304// scalar * matrix
4305// matrix * matrix linear algebraic
4306// matrix * vector
4307// vector * matrix
4308// matrix * matrix componentwise
4309// matrix op matrix op in {+, -, /}
4310// matrix op scalar op in {+, -, /}
4311// scalar op matrix op in {+, -, /}
4312//
John Kessenichead86222018-03-28 18:01:20 -06004313spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4314 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07004315{
4316 bool firstClass = true;
4317
4318 // First, handle first-class matrix operations (* and matrix/scalar)
4319 switch (op) {
4320 case spv::OpFDiv:
4321 if (builder.isMatrix(left) && builder.isScalar(right)) {
4322 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01004323 spv::Id resultType = builder.getTypeId(right);
4324 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07004325 op = spv::OpMatrixTimesScalar;
4326 } else
4327 firstClass = false;
4328 break;
4329 case spv::OpMatrixTimesScalar:
4330 if (builder.isMatrix(right))
4331 std::swap(left, right);
4332 assert(builder.isScalar(right));
4333 break;
4334 case spv::OpVectorTimesMatrix:
4335 assert(builder.isVector(left));
4336 assert(builder.isMatrix(right));
4337 break;
4338 case spv::OpMatrixTimesVector:
4339 assert(builder.isMatrix(left));
4340 assert(builder.isVector(right));
4341 break;
4342 case spv::OpMatrixTimesMatrix:
4343 assert(builder.isMatrix(left));
4344 assert(builder.isMatrix(right));
4345 break;
4346 default:
4347 firstClass = false;
4348 break;
4349 }
4350
qining25262b32016-05-06 17:25:16 -04004351 if (firstClass) {
4352 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004353 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004354 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004355 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004356 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004357
LoopDawg592860c2016-06-09 08:57:35 -06004358 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004359 // The result type of all of them is the same type as the (a) matrix operand.
4360 // The algorithm is to:
4361 // - break the matrix(es) into vectors
4362 // - smear any scalar to a vector
4363 // - do vector operations
4364 // - make a matrix out the vector results
4365 switch (op) {
4366 case spv::OpFAdd:
4367 case spv::OpFSub:
4368 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004369 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004370 case spv::OpFMul:
4371 {
4372 // one time set up...
4373 bool leftMat = builder.isMatrix(left);
4374 bool rightMat = builder.isMatrix(right);
4375 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4376 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4377 spv::Id scalarType = builder.getScalarTypeId(typeId);
4378 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4379 std::vector<spv::Id> results;
4380 spv::Id smearVec = spv::NoResult;
4381 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06004382 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004383 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06004384 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004385
4386 // do each vector op
4387 for (unsigned int c = 0; c < numCols; ++c) {
4388 std::vector<unsigned int> indexes;
4389 indexes.push_back(c);
4390 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4391 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004392 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06004393 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004394 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004395 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004396 }
4397
4398 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004399 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004400 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004401 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07004402 }
4403 default:
4404 assert(0);
4405 return spv::NoResult;
4406 }
4407}
4408
John Kessenichead86222018-03-28 18:01:20 -06004409spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
4410 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004411{
4412 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004413 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004414 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07004415 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4416 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004417
4418 switch (op) {
4419 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004420 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004421 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004422 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06004423 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004424 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004425 unaryOp = spv::OpSNegate;
4426 break;
4427
4428 case glslang::EOpLogicalNot:
4429 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004430 unaryOp = spv::OpLogicalNot;
4431 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004432 case glslang::EOpBitwiseNot:
4433 unaryOp = spv::OpNot;
4434 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004435
John Kessenich140f3df2015-06-26 16:58:36 -06004436 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004437 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004438 break;
4439 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004440 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004441 break;
4442 case glslang::EOpTranspose:
4443 unaryOp = spv::OpTranspose;
4444 break;
4445
4446 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004447 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004448 break;
4449 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004450 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004451 break;
4452 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004453 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004454 break;
4455 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004456 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004457 break;
4458 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004459 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004460 break;
4461 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004462 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004463 break;
4464 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004465 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004466 break;
4467 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004468 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004469 break;
4470
4471 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004472 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004473 break;
4474 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004475 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004476 break;
4477 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004478 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004479 break;
4480 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004481 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004482 break;
4483 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004484 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004485 break;
4486 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004487 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004488 break;
4489
4490 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004491 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004492 break;
4493 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004494 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004495 break;
4496
4497 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004498 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004499 break;
4500 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004501 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004502 break;
4503 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004504 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004505 break;
4506 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004507 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004508 break;
4509 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004510 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004511 break;
4512 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004513 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004514 break;
4515
4516 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004517 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004518 break;
4519 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004520 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004521 break;
4522 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004523 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004524 break;
4525 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004526 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004527 break;
4528 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004529 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004530 break;
4531 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004532 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004533 break;
4534
4535 case glslang::EOpIsNan:
4536 unaryOp = spv::OpIsNan;
4537 break;
4538 case glslang::EOpIsInf:
4539 unaryOp = spv::OpIsInf;
4540 break;
LoopDawg592860c2016-06-09 08:57:35 -06004541 case glslang::EOpIsFinite:
4542 unaryOp = spv::OpIsFinite;
4543 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004544
Rex Xucbc426e2015-12-15 16:03:10 +08004545 case glslang::EOpFloatBitsToInt:
4546 case glslang::EOpFloatBitsToUint:
4547 case glslang::EOpIntBitsToFloat:
4548 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004549 case glslang::EOpDoubleBitsToInt64:
4550 case glslang::EOpDoubleBitsToUint64:
4551 case glslang::EOpInt64BitsToDouble:
4552 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004553 case glslang::EOpFloat16BitsToInt16:
4554 case glslang::EOpFloat16BitsToUint16:
4555 case glslang::EOpInt16BitsToFloat16:
4556 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08004557 unaryOp = spv::OpBitcast;
4558 break;
4559
John Kessenich140f3df2015-06-26 16:58:36 -06004560 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004561 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004562 break;
4563 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004564 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004565 break;
4566 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004567 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004568 break;
4569 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004570 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004571 break;
4572 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004573 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004574 break;
4575 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004576 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004577 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004578 case glslang::EOpPackSnorm4x8:
4579 libCall = spv::GLSLstd450PackSnorm4x8;
4580 break;
4581 case glslang::EOpUnpackSnorm4x8:
4582 libCall = spv::GLSLstd450UnpackSnorm4x8;
4583 break;
4584 case glslang::EOpPackUnorm4x8:
4585 libCall = spv::GLSLstd450PackUnorm4x8;
4586 break;
4587 case glslang::EOpUnpackUnorm4x8:
4588 libCall = spv::GLSLstd450UnpackUnorm4x8;
4589 break;
4590 case glslang::EOpPackDouble2x32:
4591 libCall = spv::GLSLstd450PackDouble2x32;
4592 break;
4593 case glslang::EOpUnpackDouble2x32:
4594 libCall = spv::GLSLstd450UnpackDouble2x32;
4595 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004596
Rex Xu8ff43de2016-04-22 16:51:45 +08004597 case glslang::EOpPackInt2x32:
4598 case glslang::EOpUnpackInt2x32:
4599 case glslang::EOpPackUint2x32:
4600 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07004601 case glslang::EOpPack16:
4602 case glslang::EOpPack32:
4603 case glslang::EOpPack64:
4604 case glslang::EOpUnpack32:
4605 case glslang::EOpUnpack16:
4606 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08004607 case glslang::EOpPackInt2x16:
4608 case glslang::EOpUnpackInt2x16:
4609 case glslang::EOpPackUint2x16:
4610 case glslang::EOpUnpackUint2x16:
4611 case glslang::EOpPackInt4x16:
4612 case glslang::EOpUnpackInt4x16:
4613 case glslang::EOpPackUint4x16:
4614 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004615 case glslang::EOpPackFloat2x16:
4616 case glslang::EOpUnpackFloat2x16:
4617 unaryOp = spv::OpBitcast;
4618 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004619
John Kessenich140f3df2015-06-26 16:58:36 -06004620 case glslang::EOpDPdx:
4621 unaryOp = spv::OpDPdx;
4622 break;
4623 case glslang::EOpDPdy:
4624 unaryOp = spv::OpDPdy;
4625 break;
4626 case glslang::EOpFwidth:
4627 unaryOp = spv::OpFwidth;
4628 break;
4629 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004630 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004631 unaryOp = spv::OpDPdxFine;
4632 break;
4633 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004634 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004635 unaryOp = spv::OpDPdyFine;
4636 break;
4637 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004638 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004639 unaryOp = spv::OpFwidthFine;
4640 break;
4641 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004642 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004643 unaryOp = spv::OpDPdxCoarse;
4644 break;
4645 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004646 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004647 unaryOp = spv::OpDPdyCoarse;
4648 break;
4649 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004650 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004651 unaryOp = spv::OpFwidthCoarse;
4652 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004653 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08004654#ifdef AMD_EXTENSIONS
4655 if (typeProxy == glslang::EbtFloat16)
4656 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
4657#endif
John Kessenich92187592016-02-01 13:45:25 -07004658 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004659 libCall = spv::GLSLstd450InterpolateAtCentroid;
4660 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004661 case glslang::EOpAny:
4662 unaryOp = spv::OpAny;
4663 break;
4664 case glslang::EOpAll:
4665 unaryOp = spv::OpAll;
4666 break;
4667
4668 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004669 if (isFloat)
4670 libCall = spv::GLSLstd450FAbs;
4671 else
4672 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004673 break;
4674 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004675 if (isFloat)
4676 libCall = spv::GLSLstd450FSign;
4677 else
4678 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004679 break;
4680
John Kessenichfc51d282015-08-19 13:34:18 -06004681 case glslang::EOpAtomicCounterIncrement:
4682 case glslang::EOpAtomicCounterDecrement:
4683 case glslang::EOpAtomicCounter:
4684 {
4685 // Handle all of the atomics in one place, in createAtomicOperation()
4686 std::vector<spv::Id> operands;
4687 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06004688 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004689 }
4690
John Kessenichfc51d282015-08-19 13:34:18 -06004691 case glslang::EOpBitFieldReverse:
4692 unaryOp = spv::OpBitReverse;
4693 break;
4694 case glslang::EOpBitCount:
4695 unaryOp = spv::OpBitCount;
4696 break;
4697 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004698 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004699 break;
4700 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004701 if (isUnsigned)
4702 libCall = spv::GLSLstd450FindUMsb;
4703 else
4704 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004705 break;
4706
Rex Xu574ab042016-04-14 16:53:07 +08004707 case glslang::EOpBallot:
4708 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004709 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004710 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004711 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004712#ifdef AMD_EXTENSIONS
4713 case glslang::EOpMinInvocations:
4714 case glslang::EOpMaxInvocations:
4715 case glslang::EOpAddInvocations:
4716 case glslang::EOpMinInvocationsNonUniform:
4717 case glslang::EOpMaxInvocationsNonUniform:
4718 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004719 case glslang::EOpMinInvocationsInclusiveScan:
4720 case glslang::EOpMaxInvocationsInclusiveScan:
4721 case glslang::EOpAddInvocationsInclusiveScan:
4722 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4723 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4724 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4725 case glslang::EOpMinInvocationsExclusiveScan:
4726 case glslang::EOpMaxInvocationsExclusiveScan:
4727 case glslang::EOpAddInvocationsExclusiveScan:
4728 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4729 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4730 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004731#endif
Rex Xu51596642016-09-21 18:56:12 +08004732 {
4733 std::vector<spv::Id> operands;
4734 operands.push_back(operand);
4735 return createInvocationsOperation(op, typeId, operands, typeProxy);
4736 }
John Kessenich66011cb2018-03-06 16:12:04 -07004737 case glslang::EOpSubgroupAll:
4738 case glslang::EOpSubgroupAny:
4739 case glslang::EOpSubgroupAllEqual:
4740 case glslang::EOpSubgroupBroadcastFirst:
4741 case glslang::EOpSubgroupBallot:
4742 case glslang::EOpSubgroupInverseBallot:
4743 case glslang::EOpSubgroupBallotBitCount:
4744 case glslang::EOpSubgroupBallotInclusiveBitCount:
4745 case glslang::EOpSubgroupBallotExclusiveBitCount:
4746 case glslang::EOpSubgroupBallotFindLSB:
4747 case glslang::EOpSubgroupBallotFindMSB:
4748 case glslang::EOpSubgroupAdd:
4749 case glslang::EOpSubgroupMul:
4750 case glslang::EOpSubgroupMin:
4751 case glslang::EOpSubgroupMax:
4752 case glslang::EOpSubgroupAnd:
4753 case glslang::EOpSubgroupOr:
4754 case glslang::EOpSubgroupXor:
4755 case glslang::EOpSubgroupInclusiveAdd:
4756 case glslang::EOpSubgroupInclusiveMul:
4757 case glslang::EOpSubgroupInclusiveMin:
4758 case glslang::EOpSubgroupInclusiveMax:
4759 case glslang::EOpSubgroupInclusiveAnd:
4760 case glslang::EOpSubgroupInclusiveOr:
4761 case glslang::EOpSubgroupInclusiveXor:
4762 case glslang::EOpSubgroupExclusiveAdd:
4763 case glslang::EOpSubgroupExclusiveMul:
4764 case glslang::EOpSubgroupExclusiveMin:
4765 case glslang::EOpSubgroupExclusiveMax:
4766 case glslang::EOpSubgroupExclusiveAnd:
4767 case glslang::EOpSubgroupExclusiveOr:
4768 case glslang::EOpSubgroupExclusiveXor:
4769 case glslang::EOpSubgroupQuadSwapHorizontal:
4770 case glslang::EOpSubgroupQuadSwapVertical:
4771 case glslang::EOpSubgroupQuadSwapDiagonal: {
4772 std::vector<spv::Id> operands;
4773 operands.push_back(operand);
4774 return createSubgroupOperation(op, typeId, operands, typeProxy);
4775 }
Rex Xu9d93a232016-05-05 12:30:44 +08004776#ifdef AMD_EXTENSIONS
4777 case glslang::EOpMbcnt:
4778 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4779 libCall = spv::MbcntAMD;
4780 break;
4781
4782 case glslang::EOpCubeFaceIndex:
4783 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4784 libCall = spv::CubeFaceIndexAMD;
4785 break;
4786
4787 case glslang::EOpCubeFaceCoord:
4788 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4789 libCall = spv::CubeFaceCoordAMD;
4790 break;
4791#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05004792#ifdef NV_EXTENSIONS
4793 case glslang::EOpSubgroupPartition:
4794 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
4795 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
4796 unaryOp = spv::OpGroupNonUniformPartitionNV;
4797 break;
4798#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004799 default:
4800 return 0;
4801 }
4802
4803 spv::Id id;
4804 if (libCall >= 0) {
4805 std::vector<spv::Id> args;
4806 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004807 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004808 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004809 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004810 }
John Kessenich140f3df2015-06-26 16:58:36 -06004811
John Kessenichead86222018-03-28 18:01:20 -06004812 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004813 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004814 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004815}
4816
John Kessenich7a53f762016-01-20 11:19:27 -07004817// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06004818spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4819 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07004820{
4821 // Handle unary operations vector by vector.
4822 // The result type is the same type as the original type.
4823 // The algorithm is to:
4824 // - break the matrix into vectors
4825 // - apply the operation to each vector
4826 // - make a matrix out the vector results
4827
4828 // get the types sorted out
4829 int numCols = builder.getNumColumns(operand);
4830 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004831 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4832 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004833 std::vector<spv::Id> results;
4834
4835 // do each vector op
4836 for (int c = 0; c < numCols; ++c) {
4837 std::vector<unsigned int> indexes;
4838 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004839 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4840 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06004841 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004842 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004843 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004844 }
4845
4846 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004847 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004848 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004849 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07004850}
4851
John Kessenichad7645f2018-06-04 19:11:25 -06004852// For converting integers where both the bitwidth and the signedness could
4853// change, but only do the width change here. The caller is still responsible
4854// for the signedness conversion.
4855spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07004856{
John Kessenichad7645f2018-06-04 19:11:25 -06004857 // Get the result type width, based on the type to convert to.
4858 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07004859 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06004860 case glslang::EOpConvInt16ToUint8:
4861 case glslang::EOpConvIntToUint8:
4862 case glslang::EOpConvInt64ToUint8:
4863 case glslang::EOpConvUint16ToInt8:
4864 case glslang::EOpConvUintToInt8:
4865 case glslang::EOpConvUint64ToInt8:
4866 width = 8;
4867 break;
John Kessenich66011cb2018-03-06 16:12:04 -07004868 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06004869 case glslang::EOpConvIntToUint16:
4870 case glslang::EOpConvInt64ToUint16:
4871 case glslang::EOpConvUint8ToInt16:
4872 case glslang::EOpConvUintToInt16:
4873 case glslang::EOpConvUint64ToInt16:
4874 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07004875 break;
4876 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06004877 case glslang::EOpConvInt16ToUint:
4878 case glslang::EOpConvInt64ToUint:
4879 case glslang::EOpConvUint8ToInt:
4880 case glslang::EOpConvUint16ToInt:
4881 case glslang::EOpConvUint64ToInt:
4882 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07004883 break;
4884 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07004885 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07004886 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07004887 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07004888 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07004889 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06004890 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07004891 break;
4892
4893 default:
4894 assert(false && "Default missing");
4895 break;
4896 }
4897
John Kessenichad7645f2018-06-04 19:11:25 -06004898 // Get the conversion operation and result type,
4899 // based on the target width, but the source type.
4900 spv::Id type = spv::NoType;
4901 spv::Op convOp = spv::OpNop;
4902 switch(op) {
4903 case glslang::EOpConvInt8ToUint16:
4904 case glslang::EOpConvInt8ToUint:
4905 case glslang::EOpConvInt8ToUint64:
4906 case glslang::EOpConvInt16ToUint8:
4907 case glslang::EOpConvInt16ToUint:
4908 case glslang::EOpConvInt16ToUint64:
4909 case glslang::EOpConvIntToUint8:
4910 case glslang::EOpConvIntToUint16:
4911 case glslang::EOpConvIntToUint64:
4912 case glslang::EOpConvInt64ToUint8:
4913 case glslang::EOpConvInt64ToUint16:
4914 case glslang::EOpConvInt64ToUint:
4915 convOp = spv::OpSConvert;
4916 type = builder.makeIntType(width);
4917 break;
4918 default:
4919 convOp = spv::OpUConvert;
4920 type = builder.makeUintType(width);
4921 break;
4922 }
4923
John Kessenich66011cb2018-03-06 16:12:04 -07004924 if (vectorSize > 0)
4925 type = builder.makeVectorType(type, vectorSize);
4926
John Kessenichad7645f2018-06-04 19:11:25 -06004927 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07004928}
4929
John Kessenichead86222018-03-28 18:01:20 -06004930spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
4931 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004932{
4933 spv::Op convOp = spv::OpNop;
4934 spv::Id zero = 0;
4935 spv::Id one = 0;
4936
4937 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4938
4939 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07004940 case glslang::EOpConvInt8ToBool:
4941 case glslang::EOpConvUint8ToBool:
4942 zero = builder.makeUint8Constant(0);
4943 zero = makeSmearedConstant(zero, vectorSize);
4944 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08004945 case glslang::EOpConvInt16ToBool:
4946 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07004947 zero = builder.makeUint16Constant(0);
4948 zero = makeSmearedConstant(zero, vectorSize);
4949 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4950 case glslang::EOpConvIntToBool:
4951 case glslang::EOpConvUintToBool:
4952 zero = builder.makeUintConstant(0);
4953 zero = makeSmearedConstant(zero, vectorSize);
4954 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4955 case glslang::EOpConvInt64ToBool:
4956 case glslang::EOpConvUint64ToBool:
4957 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004958 zero = makeSmearedConstant(zero, vectorSize);
4959 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4960
4961 case glslang::EOpConvFloatToBool:
4962 zero = builder.makeFloatConstant(0.0F);
4963 zero = makeSmearedConstant(zero, vectorSize);
4964 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4965
4966 case glslang::EOpConvDoubleToBool:
4967 zero = builder.makeDoubleConstant(0.0);
4968 zero = makeSmearedConstant(zero, vectorSize);
4969 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4970
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004971 case glslang::EOpConvFloat16ToBool:
4972 zero = builder.makeFloat16Constant(0.0F);
4973 zero = makeSmearedConstant(zero, vectorSize);
4974 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004975
John Kessenich140f3df2015-06-26 16:58:36 -06004976 case glslang::EOpConvBoolToFloat:
4977 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004978 zero = builder.makeFloatConstant(0.0F);
4979 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004980 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004981
John Kessenich140f3df2015-06-26 16:58:36 -06004982 case glslang::EOpConvBoolToDouble:
4983 convOp = spv::OpSelect;
4984 zero = builder.makeDoubleConstant(0.0);
4985 one = builder.makeDoubleConstant(1.0);
4986 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004987
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004988 case glslang::EOpConvBoolToFloat16:
4989 convOp = spv::OpSelect;
4990 zero = builder.makeFloat16Constant(0.0F);
4991 one = builder.makeFloat16Constant(1.0F);
4992 break;
John Kessenich66011cb2018-03-06 16:12:04 -07004993
4994 case glslang::EOpConvBoolToInt8:
4995 zero = builder.makeInt8Constant(0);
4996 one = builder.makeInt8Constant(1);
4997 convOp = spv::OpSelect;
4998 break;
4999
5000 case glslang::EOpConvBoolToUint8:
5001 zero = builder.makeUint8Constant(0);
5002 one = builder.makeUint8Constant(1);
5003 convOp = spv::OpSelect;
5004 break;
5005
5006 case glslang::EOpConvBoolToInt16:
5007 zero = builder.makeInt16Constant(0);
5008 one = builder.makeInt16Constant(1);
5009 convOp = spv::OpSelect;
5010 break;
5011
5012 case glslang::EOpConvBoolToUint16:
5013 zero = builder.makeUint16Constant(0);
5014 one = builder.makeUint16Constant(1);
5015 convOp = spv::OpSelect;
5016 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005017
John Kessenich140f3df2015-06-26 16:58:36 -06005018 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005019 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005020 if (op == glslang::EOpConvBoolToInt64)
5021 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005022 else
5023 zero = builder.makeIntConstant(0);
5024
5025 if (op == glslang::EOpConvBoolToInt64)
5026 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005027 else
5028 one = builder.makeIntConstant(1);
5029
John Kessenich140f3df2015-06-26 16:58:36 -06005030 convOp = spv::OpSelect;
5031 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005032
John Kessenich140f3df2015-06-26 16:58:36 -06005033 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005034 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005035 if (op == glslang::EOpConvBoolToUint64)
5036 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005037 else
5038 zero = builder.makeUintConstant(0);
5039
5040 if (op == glslang::EOpConvBoolToUint64)
5041 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005042 else
5043 one = builder.makeUintConstant(1);
5044
John Kessenich140f3df2015-06-26 16:58:36 -06005045 convOp = spv::OpSelect;
5046 break;
5047
John Kessenich66011cb2018-03-06 16:12:04 -07005048 case glslang::EOpConvInt8ToFloat16:
5049 case glslang::EOpConvInt8ToFloat:
5050 case glslang::EOpConvInt8ToDouble:
5051 case glslang::EOpConvInt16ToFloat16:
5052 case glslang::EOpConvInt16ToFloat:
5053 case glslang::EOpConvInt16ToDouble:
5054 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005055 case glslang::EOpConvIntToFloat:
5056 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005057 case glslang::EOpConvInt64ToFloat:
5058 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005059 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005060 convOp = spv::OpConvertSToF;
5061 break;
5062
John Kessenich66011cb2018-03-06 16:12:04 -07005063 case glslang::EOpConvUint8ToFloat16:
5064 case glslang::EOpConvUint8ToFloat:
5065 case glslang::EOpConvUint8ToDouble:
5066 case glslang::EOpConvUint16ToFloat16:
5067 case glslang::EOpConvUint16ToFloat:
5068 case glslang::EOpConvUint16ToDouble:
5069 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005070 case glslang::EOpConvUintToFloat:
5071 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005072 case glslang::EOpConvUint64ToFloat:
5073 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005074 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005075 convOp = spv::OpConvertUToF;
5076 break;
5077
5078 case glslang::EOpConvDoubleToFloat:
5079 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005080 case glslang::EOpConvDoubleToFloat16:
5081 case glslang::EOpConvFloat16ToDouble:
5082 case glslang::EOpConvFloatToFloat16:
5083 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005084 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005085 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005086 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005087 break;
5088
John Kessenich66011cb2018-03-06 16:12:04 -07005089 case glslang::EOpConvFloat16ToInt8:
5090 case glslang::EOpConvFloatToInt8:
5091 case glslang::EOpConvDoubleToInt8:
5092 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005093 case glslang::EOpConvFloatToInt16:
5094 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005095 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005096 case glslang::EOpConvFloatToInt:
5097 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005098 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005099 case glslang::EOpConvFloatToInt64:
5100 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005101 convOp = spv::OpConvertFToS;
5102 break;
5103
John Kessenich66011cb2018-03-06 16:12:04 -07005104 case glslang::EOpConvUint8ToInt8:
5105 case glslang::EOpConvInt8ToUint8:
5106 case glslang::EOpConvUint16ToInt16:
5107 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005108 case glslang::EOpConvUintToInt:
5109 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005110 case glslang::EOpConvUint64ToInt64:
5111 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005112 if (builder.isInSpecConstCodeGenMode()) {
5113 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005114 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5115 zero = builder.makeUint8Constant(0);
5116 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005117 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005118 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5119 zero = builder.makeUint64Constant(0);
5120 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005121 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005122 }
qining189b2032016-04-12 23:16:20 -04005123 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005124 // Use OpIAdd, instead of OpBitcast to do the conversion when
5125 // generating for OpSpecConstantOp instruction.
5126 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5127 }
5128 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005129 convOp = spv::OpBitcast;
5130 break;
5131
John Kessenich66011cb2018-03-06 16:12:04 -07005132 case glslang::EOpConvFloat16ToUint8:
5133 case glslang::EOpConvFloatToUint8:
5134 case glslang::EOpConvDoubleToUint8:
5135 case glslang::EOpConvFloat16ToUint16:
5136 case glslang::EOpConvFloatToUint16:
5137 case glslang::EOpConvDoubleToUint16:
5138 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005139 case glslang::EOpConvFloatToUint:
5140 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005141 case glslang::EOpConvFloatToUint64:
5142 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005143 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005144 convOp = spv::OpConvertFToU;
5145 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005146
John Kessenich66011cb2018-03-06 16:12:04 -07005147 case glslang::EOpConvInt8ToInt16:
5148 case glslang::EOpConvInt8ToInt:
5149 case glslang::EOpConvInt8ToInt64:
5150 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005151 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005152 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005153 case glslang::EOpConvIntToInt8:
5154 case glslang::EOpConvIntToInt16:
5155 case glslang::EOpConvIntToInt64:
5156 case glslang::EOpConvInt64ToInt8:
5157 case glslang::EOpConvInt64ToInt16:
5158 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005159 convOp = spv::OpSConvert;
5160 break;
5161
John Kessenich66011cb2018-03-06 16:12:04 -07005162 case glslang::EOpConvUint8ToUint16:
5163 case glslang::EOpConvUint8ToUint:
5164 case glslang::EOpConvUint8ToUint64:
5165 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005166 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005167 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005168 case glslang::EOpConvUintToUint8:
5169 case glslang::EOpConvUintToUint16:
5170 case glslang::EOpConvUintToUint64:
5171 case glslang::EOpConvUint64ToUint8:
5172 case glslang::EOpConvUint64ToUint16:
5173 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005174 convOp = spv::OpUConvert;
5175 break;
5176
John Kessenich66011cb2018-03-06 16:12:04 -07005177 case glslang::EOpConvInt8ToUint16:
5178 case glslang::EOpConvInt8ToUint:
5179 case glslang::EOpConvInt8ToUint64:
5180 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005181 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005182 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005183 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005184 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005185 case glslang::EOpConvIntToUint64:
5186 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005187 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005188 case glslang::EOpConvInt64ToUint:
5189 case glslang::EOpConvUint8ToInt16:
5190 case glslang::EOpConvUint8ToInt:
5191 case glslang::EOpConvUint8ToInt64:
5192 case glslang::EOpConvUint16ToInt8:
5193 case glslang::EOpConvUint16ToInt:
5194 case glslang::EOpConvUint16ToInt64:
5195 case glslang::EOpConvUintToInt8:
5196 case glslang::EOpConvUintToInt16:
5197 case glslang::EOpConvUintToInt64:
5198 case glslang::EOpConvUint64ToInt8:
5199 case glslang::EOpConvUint64ToInt16:
5200 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005201 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005202 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005203
5204 if (builder.isInSpecConstCodeGenMode()) {
5205 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005206 switch(op) {
5207 case glslang::EOpConvInt16ToUint8:
5208 case glslang::EOpConvIntToUint8:
5209 case glslang::EOpConvInt64ToUint8:
5210 case glslang::EOpConvUint16ToInt8:
5211 case glslang::EOpConvUintToInt8:
5212 case glslang::EOpConvUint64ToInt8:
5213 zero = builder.makeUint8Constant(0);
5214 break;
5215 case glslang::EOpConvInt8ToUint16:
5216 case glslang::EOpConvIntToUint16:
5217 case glslang::EOpConvInt64ToUint16:
5218 case glslang::EOpConvUint8ToInt16:
5219 case glslang::EOpConvUintToInt16:
5220 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005221 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005222 break;
5223 case glslang::EOpConvInt8ToUint:
5224 case glslang::EOpConvInt16ToUint:
5225 case glslang::EOpConvInt64ToUint:
5226 case glslang::EOpConvUint8ToInt:
5227 case glslang::EOpConvUint16ToInt:
5228 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005229 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005230 break;
5231 case glslang::EOpConvInt8ToUint64:
5232 case glslang::EOpConvInt16ToUint64:
5233 case glslang::EOpConvIntToUint64:
5234 case glslang::EOpConvUint8ToInt64:
5235 case glslang::EOpConvUint16ToInt64:
5236 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005237 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005238 break;
5239 default:
5240 assert(false && "Default missing");
5241 break;
5242 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005243 zero = makeSmearedConstant(zero, vectorSize);
5244 // Use OpIAdd, instead of OpBitcast to do the conversion when
5245 // generating for OpSpecConstantOp instruction.
5246 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5247 }
5248 // For normal run-time conversion instruction, use OpBitcast.
5249 convOp = spv::OpBitcast;
5250 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005251 default:
5252 break;
5253 }
5254
5255 spv::Id result = 0;
5256 if (convOp == spv::OpNop)
5257 return result;
5258
5259 if (convOp == spv::OpSelect) {
5260 zero = makeSmearedConstant(zero, vectorSize);
5261 one = makeSmearedConstant(one, vectorSize);
5262 result = builder.createTriOp(convOp, destType, operand, one, zero);
5263 } else
5264 result = builder.createUnaryOp(convOp, destType, operand);
5265
John Kessenichead86222018-03-28 18:01:20 -06005266 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005267 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005268 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06005269}
5270
5271spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
5272{
5273 if (vectorSize == 0)
5274 return constant;
5275
5276 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
5277 std::vector<spv::Id> components;
5278 for (int c = 0; c < vectorSize; ++c)
5279 components.push_back(constant);
5280 return builder.makeCompositeConstant(vectorTypeId, components);
5281}
5282
John Kessenich426394d2015-07-23 10:22:48 -06005283// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07005284spv::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 -06005285{
5286 spv::Op opCode = spv::OpNop;
5287
5288 switch (op) {
5289 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08005290 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005291 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06005292 opCode = spv::OpAtomicIAdd;
5293 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06005294 case glslang::EOpAtomicCounterSubtract:
5295 opCode = spv::OpAtomicISub;
5296 break;
John Kessenich426394d2015-07-23 10:22:48 -06005297 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08005298 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005299 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08005300 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06005301 break;
5302 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08005303 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005304 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08005305 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06005306 break;
5307 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08005308 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005309 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06005310 opCode = spv::OpAtomicAnd;
5311 break;
5312 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08005313 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005314 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06005315 opCode = spv::OpAtomicOr;
5316 break;
5317 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08005318 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005319 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06005320 opCode = spv::OpAtomicXor;
5321 break;
5322 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08005323 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005324 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06005325 opCode = spv::OpAtomicExchange;
5326 break;
5327 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08005328 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005329 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06005330 opCode = spv::OpAtomicCompareExchange;
5331 break;
5332 case glslang::EOpAtomicCounterIncrement:
5333 opCode = spv::OpAtomicIIncrement;
5334 break;
5335 case glslang::EOpAtomicCounterDecrement:
5336 opCode = spv::OpAtomicIDecrement;
5337 break;
5338 case glslang::EOpAtomicCounter:
5339 opCode = spv::OpAtomicLoad;
5340 break;
5341 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005342 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06005343 break;
5344 }
5345
Rex Xue8fe8b02017-09-26 15:42:56 +08005346 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
5347 builder.addCapability(spv::CapabilityInt64Atomics);
5348
John Kessenich426394d2015-07-23 10:22:48 -06005349 // Sort out the operands
5350 // - mapping from glslang -> SPV
5351 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06005352 // - compare-exchange swaps the value and comparator
5353 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06005354 // - EOpAtomicCounterDecrement needs a post decrement
John Kessenich426394d2015-07-23 10:22:48 -06005355 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
5356 auto opIt = operands.begin(); // walk the glslang operands
5357 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08005358 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
5359 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
5360 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08005361 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
5362 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08005363 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06005364 spvAtomicOperands.push_back(*(opIt + 1));
5365 spvAtomicOperands.push_back(*opIt);
5366 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08005367 }
John Kessenich426394d2015-07-23 10:22:48 -06005368
John Kessenich3e60a6f2015-09-14 22:45:16 -06005369 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06005370 for (; opIt != operands.end(); ++opIt)
5371 spvAtomicOperands.push_back(*opIt);
5372
John Kessenich48d6e792017-10-06 21:21:48 -06005373 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
5374
5375 // GLSL and HLSL atomic-counter decrement return post-decrement value,
5376 // while SPIR-V returns pre-decrement value. Translate between these semantics.
5377 if (op == glslang::EOpAtomicCounterDecrement)
5378 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
5379
5380 return resultId;
John Kessenich426394d2015-07-23 10:22:48 -06005381}
5382
John Kessenich91cef522016-05-05 16:45:40 -06005383// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08005384spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06005385{
John Kessenich66011cb2018-03-06 16:12:04 -07005386 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5387 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08005388
Rex Xu51596642016-09-21 18:56:12 +08005389 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08005390 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08005391 spv::GroupOperation groupOperation = spv::GroupOperationMax;
5392
chaocf200da82016-12-20 12:44:35 -08005393 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
5394 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08005395 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
5396 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005397 } else if (op == glslang::EOpAnyInvocation ||
5398 op == glslang::EOpAllInvocations ||
5399 op == glslang::EOpAllInvocationsEqual) {
5400 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
5401 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08005402 } else {
5403 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04005404#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08005405 if (op == glslang::EOpMinInvocationsNonUniform ||
5406 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08005407 op == glslang::EOpAddInvocationsNonUniform ||
5408 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5409 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5410 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
5411 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
5412 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
5413 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08005414 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04005415#endif
Rex Xu51596642016-09-21 18:56:12 +08005416
5417 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08005418#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08005419 switch (op) {
5420 case glslang::EOpMinInvocations:
5421 case glslang::EOpMaxInvocations:
5422 case glslang::EOpAddInvocations:
5423 case glslang::EOpMinInvocationsNonUniform:
5424 case glslang::EOpMaxInvocationsNonUniform:
5425 case glslang::EOpAddInvocationsNonUniform:
5426 groupOperation = spv::GroupOperationReduce;
5427 spvGroupOperands.push_back(groupOperation);
5428 break;
5429 case glslang::EOpMinInvocationsInclusiveScan:
5430 case glslang::EOpMaxInvocationsInclusiveScan:
5431 case glslang::EOpAddInvocationsInclusiveScan:
5432 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5433 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5434 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5435 groupOperation = spv::GroupOperationInclusiveScan;
5436 spvGroupOperands.push_back(groupOperation);
5437 break;
5438 case glslang::EOpMinInvocationsExclusiveScan:
5439 case glslang::EOpMaxInvocationsExclusiveScan:
5440 case glslang::EOpAddInvocationsExclusiveScan:
5441 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5442 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5443 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5444 groupOperation = spv::GroupOperationExclusiveScan;
5445 spvGroupOperands.push_back(groupOperation);
5446 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07005447 default:
5448 break;
Rex Xu430ef402016-10-14 17:22:23 +08005449 }
Rex Xu9d93a232016-05-05 12:30:44 +08005450#endif
Rex Xu51596642016-09-21 18:56:12 +08005451 }
5452
5453 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
5454 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06005455
5456 switch (op) {
5457 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005458 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08005459 break;
John Kessenich91cef522016-05-05 16:45:40 -06005460 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005461 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08005462 break;
John Kessenich91cef522016-05-05 16:45:40 -06005463 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005464 opCode = spv::OpSubgroupAllEqualKHR;
5465 break;
Rex Xu51596642016-09-21 18:56:12 +08005466 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08005467 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08005468 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005469 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005470 break;
5471 case glslang::EOpReadFirstInvocation:
5472 opCode = spv::OpSubgroupFirstInvocationKHR;
5473 break;
5474 case glslang::EOpBallot:
5475 {
5476 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
5477 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
5478 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
5479 //
5480 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
5481 //
5482 spv::Id uintType = builder.makeUintType(32);
5483 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
5484 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
5485
5486 std::vector<spv::Id> components;
5487 components.push_back(builder.createCompositeExtract(result, uintType, 0));
5488 components.push_back(builder.createCompositeExtract(result, uintType, 1));
5489
5490 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
5491 return builder.createUnaryOp(spv::OpBitcast, typeId,
5492 builder.createCompositeConstruct(uvec2Type, components));
5493 }
5494
Rex Xu9d93a232016-05-05 12:30:44 +08005495#ifdef AMD_EXTENSIONS
5496 case glslang::EOpMinInvocations:
5497 case glslang::EOpMaxInvocations:
5498 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08005499 case glslang::EOpMinInvocationsInclusiveScan:
5500 case glslang::EOpMaxInvocationsInclusiveScan:
5501 case glslang::EOpAddInvocationsInclusiveScan:
5502 case glslang::EOpMinInvocationsExclusiveScan:
5503 case glslang::EOpMaxInvocationsExclusiveScan:
5504 case glslang::EOpAddInvocationsExclusiveScan:
5505 if (op == glslang::EOpMinInvocations ||
5506 op == glslang::EOpMinInvocationsInclusiveScan ||
5507 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005508 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005509 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005510 else {
5511 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005512 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005513 else
Rex Xu51596642016-09-21 18:56:12 +08005514 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005515 }
Rex Xu430ef402016-10-14 17:22:23 +08005516 } else if (op == glslang::EOpMaxInvocations ||
5517 op == glslang::EOpMaxInvocationsInclusiveScan ||
5518 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005519 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005520 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005521 else {
5522 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005523 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005524 else
Rex Xu51596642016-09-21 18:56:12 +08005525 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005526 }
5527 } else {
5528 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005529 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005530 else
Rex Xu51596642016-09-21 18:56:12 +08005531 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005532 }
5533
Rex Xu2bbbe062016-08-23 15:41:05 +08005534 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005535 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005536
5537 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005538 case glslang::EOpMinInvocationsNonUniform:
5539 case glslang::EOpMaxInvocationsNonUniform:
5540 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005541 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5542 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5543 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5544 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5545 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5546 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5547 if (op == glslang::EOpMinInvocationsNonUniform ||
5548 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5549 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005550 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005551 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005552 else {
5553 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005554 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005555 else
Rex Xu51596642016-09-21 18:56:12 +08005556 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005557 }
5558 }
Rex Xu430ef402016-10-14 17:22:23 +08005559 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5560 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5561 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005562 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005563 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005564 else {
5565 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005566 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005567 else
Rex Xu51596642016-09-21 18:56:12 +08005568 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005569 }
5570 }
5571 else {
5572 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005573 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005574 else
Rex Xu51596642016-09-21 18:56:12 +08005575 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005576 }
5577
Rex Xu2bbbe062016-08-23 15:41:05 +08005578 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005579 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005580
5581 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005582#endif
John Kessenich91cef522016-05-05 16:45:40 -06005583 default:
5584 logger->missingFunctionality("invocation operation");
5585 return spv::NoResult;
5586 }
Rex Xu51596642016-09-21 18:56:12 +08005587
5588 assert(opCode != spv::OpNop);
5589 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005590}
5591
Rex Xu2bbbe062016-08-23 15:41:05 +08005592// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005593spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005594{
Rex Xub7072052016-09-26 15:53:40 +08005595#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005596 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5597 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005598 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005599 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005600 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5601 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5602 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005603#else
5604 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5605 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005606 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5607 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005608#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005609
5610 // Handle group invocation operations scalar by scalar.
5611 // The result type is the same type as the original type.
5612 // The algorithm is to:
5613 // - break the vector into scalars
5614 // - apply the operation to each scalar
5615 // - make a vector out the scalar results
5616
5617 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005618 int numComponents = builder.getNumComponents(operands[0]);
5619 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005620 std::vector<spv::Id> results;
5621
5622 // do each scalar op
5623 for (int comp = 0; comp < numComponents; ++comp) {
5624 std::vector<unsigned int> indexes;
5625 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005626 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005627 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005628 if (op == spv::OpSubgroupReadInvocationKHR) {
5629 spvGroupOperands.push_back(scalar);
5630 spvGroupOperands.push_back(operands[1]);
5631 } else if (op == spv::OpGroupBroadcast) {
5632 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005633 spvGroupOperands.push_back(scalar);
5634 spvGroupOperands.push_back(operands[1]);
5635 } else {
chaocf200da82016-12-20 12:44:35 -08005636 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005637 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005638 spvGroupOperands.push_back(scalar);
5639 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005640
Rex Xub7072052016-09-26 15:53:40 +08005641 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005642 }
5643
5644 // put the pieces together
5645 return builder.createCompositeConstruct(typeId, results);
5646}
Rex Xu2bbbe062016-08-23 15:41:05 +08005647
John Kessenich66011cb2018-03-06 16:12:04 -07005648// Create subgroup invocation operations.
5649spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
5650{
5651 // Add the required capabilities.
5652 switch (op) {
5653 case glslang::EOpSubgroupElect:
5654 builder.addCapability(spv::CapabilityGroupNonUniform);
5655 break;
5656 case glslang::EOpSubgroupAll:
5657 case glslang::EOpSubgroupAny:
5658 case glslang::EOpSubgroupAllEqual:
5659 builder.addCapability(spv::CapabilityGroupNonUniform);
5660 builder.addCapability(spv::CapabilityGroupNonUniformVote);
5661 break;
5662 case glslang::EOpSubgroupBroadcast:
5663 case glslang::EOpSubgroupBroadcastFirst:
5664 case glslang::EOpSubgroupBallot:
5665 case glslang::EOpSubgroupInverseBallot:
5666 case glslang::EOpSubgroupBallotBitExtract:
5667 case glslang::EOpSubgroupBallotBitCount:
5668 case glslang::EOpSubgroupBallotInclusiveBitCount:
5669 case glslang::EOpSubgroupBallotExclusiveBitCount:
5670 case glslang::EOpSubgroupBallotFindLSB:
5671 case glslang::EOpSubgroupBallotFindMSB:
5672 builder.addCapability(spv::CapabilityGroupNonUniform);
5673 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
5674 break;
5675 case glslang::EOpSubgroupShuffle:
5676 case glslang::EOpSubgroupShuffleXor:
5677 builder.addCapability(spv::CapabilityGroupNonUniform);
5678 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
5679 break;
5680 case glslang::EOpSubgroupShuffleUp:
5681 case glslang::EOpSubgroupShuffleDown:
5682 builder.addCapability(spv::CapabilityGroupNonUniform);
5683 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
5684 break;
5685 case glslang::EOpSubgroupAdd:
5686 case glslang::EOpSubgroupMul:
5687 case glslang::EOpSubgroupMin:
5688 case glslang::EOpSubgroupMax:
5689 case glslang::EOpSubgroupAnd:
5690 case glslang::EOpSubgroupOr:
5691 case glslang::EOpSubgroupXor:
5692 case glslang::EOpSubgroupInclusiveAdd:
5693 case glslang::EOpSubgroupInclusiveMul:
5694 case glslang::EOpSubgroupInclusiveMin:
5695 case glslang::EOpSubgroupInclusiveMax:
5696 case glslang::EOpSubgroupInclusiveAnd:
5697 case glslang::EOpSubgroupInclusiveOr:
5698 case glslang::EOpSubgroupInclusiveXor:
5699 case glslang::EOpSubgroupExclusiveAdd:
5700 case glslang::EOpSubgroupExclusiveMul:
5701 case glslang::EOpSubgroupExclusiveMin:
5702 case glslang::EOpSubgroupExclusiveMax:
5703 case glslang::EOpSubgroupExclusiveAnd:
5704 case glslang::EOpSubgroupExclusiveOr:
5705 case glslang::EOpSubgroupExclusiveXor:
5706 builder.addCapability(spv::CapabilityGroupNonUniform);
5707 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
5708 break;
5709 case glslang::EOpSubgroupClusteredAdd:
5710 case glslang::EOpSubgroupClusteredMul:
5711 case glslang::EOpSubgroupClusteredMin:
5712 case glslang::EOpSubgroupClusteredMax:
5713 case glslang::EOpSubgroupClusteredAnd:
5714 case glslang::EOpSubgroupClusteredOr:
5715 case glslang::EOpSubgroupClusteredXor:
5716 builder.addCapability(spv::CapabilityGroupNonUniform);
5717 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
5718 break;
5719 case glslang::EOpSubgroupQuadBroadcast:
5720 case glslang::EOpSubgroupQuadSwapHorizontal:
5721 case glslang::EOpSubgroupQuadSwapVertical:
5722 case glslang::EOpSubgroupQuadSwapDiagonal:
5723 builder.addCapability(spv::CapabilityGroupNonUniform);
5724 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
5725 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005726#ifdef NV_EXTENSIONS
5727 case glslang::EOpSubgroupPartitionedAdd:
5728 case glslang::EOpSubgroupPartitionedMul:
5729 case glslang::EOpSubgroupPartitionedMin:
5730 case glslang::EOpSubgroupPartitionedMax:
5731 case glslang::EOpSubgroupPartitionedAnd:
5732 case glslang::EOpSubgroupPartitionedOr:
5733 case glslang::EOpSubgroupPartitionedXor:
5734 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5735 case glslang::EOpSubgroupPartitionedInclusiveMul:
5736 case glslang::EOpSubgroupPartitionedInclusiveMin:
5737 case glslang::EOpSubgroupPartitionedInclusiveMax:
5738 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5739 case glslang::EOpSubgroupPartitionedInclusiveOr:
5740 case glslang::EOpSubgroupPartitionedInclusiveXor:
5741 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5742 case glslang::EOpSubgroupPartitionedExclusiveMul:
5743 case glslang::EOpSubgroupPartitionedExclusiveMin:
5744 case glslang::EOpSubgroupPartitionedExclusiveMax:
5745 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5746 case glslang::EOpSubgroupPartitionedExclusiveOr:
5747 case glslang::EOpSubgroupPartitionedExclusiveXor:
5748 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
5749 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
5750 break;
5751#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005752 default: assert(0 && "Unhandled subgroup operation!");
5753 }
5754
5755 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
5756 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
5757 const bool isBool = typeProxy == glslang::EbtBool;
5758
5759 spv::Op opCode = spv::OpNop;
5760
5761 // Figure out which opcode to use.
5762 switch (op) {
5763 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
5764 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
5765 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
5766 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
5767 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
5768 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
5769 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
5770 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
5771 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
5772 case glslang::EOpSubgroupBallotBitCount:
5773 case glslang::EOpSubgroupBallotInclusiveBitCount:
5774 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
5775 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
5776 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
5777 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
5778 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
5779 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
5780 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
5781 case glslang::EOpSubgroupAdd:
5782 case glslang::EOpSubgroupInclusiveAdd:
5783 case glslang::EOpSubgroupExclusiveAdd:
5784 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005785#ifdef NV_EXTENSIONS
5786 case glslang::EOpSubgroupPartitionedAdd:
5787 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5788 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5789#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005790 if (isFloat) {
5791 opCode = spv::OpGroupNonUniformFAdd;
5792 } else {
5793 opCode = spv::OpGroupNonUniformIAdd;
5794 }
5795 break;
5796 case glslang::EOpSubgroupMul:
5797 case glslang::EOpSubgroupInclusiveMul:
5798 case glslang::EOpSubgroupExclusiveMul:
5799 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005800#ifdef NV_EXTENSIONS
5801 case glslang::EOpSubgroupPartitionedMul:
5802 case glslang::EOpSubgroupPartitionedInclusiveMul:
5803 case glslang::EOpSubgroupPartitionedExclusiveMul:
5804#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005805 if (isFloat) {
5806 opCode = spv::OpGroupNonUniformFMul;
5807 } else {
5808 opCode = spv::OpGroupNonUniformIMul;
5809 }
5810 break;
5811 case glslang::EOpSubgroupMin:
5812 case glslang::EOpSubgroupInclusiveMin:
5813 case glslang::EOpSubgroupExclusiveMin:
5814 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005815#ifdef NV_EXTENSIONS
5816 case glslang::EOpSubgroupPartitionedMin:
5817 case glslang::EOpSubgroupPartitionedInclusiveMin:
5818 case glslang::EOpSubgroupPartitionedExclusiveMin:
5819#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005820 if (isFloat) {
5821 opCode = spv::OpGroupNonUniformFMin;
5822 } else if (isUnsigned) {
5823 opCode = spv::OpGroupNonUniformUMin;
5824 } else {
5825 opCode = spv::OpGroupNonUniformSMin;
5826 }
5827 break;
5828 case glslang::EOpSubgroupMax:
5829 case glslang::EOpSubgroupInclusiveMax:
5830 case glslang::EOpSubgroupExclusiveMax:
5831 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005832#ifdef NV_EXTENSIONS
5833 case glslang::EOpSubgroupPartitionedMax:
5834 case glslang::EOpSubgroupPartitionedInclusiveMax:
5835 case glslang::EOpSubgroupPartitionedExclusiveMax:
5836#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005837 if (isFloat) {
5838 opCode = spv::OpGroupNonUniformFMax;
5839 } else if (isUnsigned) {
5840 opCode = spv::OpGroupNonUniformUMax;
5841 } else {
5842 opCode = spv::OpGroupNonUniformSMax;
5843 }
5844 break;
5845 case glslang::EOpSubgroupAnd:
5846 case glslang::EOpSubgroupInclusiveAnd:
5847 case glslang::EOpSubgroupExclusiveAnd:
5848 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005849#ifdef NV_EXTENSIONS
5850 case glslang::EOpSubgroupPartitionedAnd:
5851 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5852 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5853#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005854 if (isBool) {
5855 opCode = spv::OpGroupNonUniformLogicalAnd;
5856 } else {
5857 opCode = spv::OpGroupNonUniformBitwiseAnd;
5858 }
5859 break;
5860 case glslang::EOpSubgroupOr:
5861 case glslang::EOpSubgroupInclusiveOr:
5862 case glslang::EOpSubgroupExclusiveOr:
5863 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005864#ifdef NV_EXTENSIONS
5865 case glslang::EOpSubgroupPartitionedOr:
5866 case glslang::EOpSubgroupPartitionedInclusiveOr:
5867 case glslang::EOpSubgroupPartitionedExclusiveOr:
5868#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005869 if (isBool) {
5870 opCode = spv::OpGroupNonUniformLogicalOr;
5871 } else {
5872 opCode = spv::OpGroupNonUniformBitwiseOr;
5873 }
5874 break;
5875 case glslang::EOpSubgroupXor:
5876 case glslang::EOpSubgroupInclusiveXor:
5877 case glslang::EOpSubgroupExclusiveXor:
5878 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005879#ifdef NV_EXTENSIONS
5880 case glslang::EOpSubgroupPartitionedXor:
5881 case glslang::EOpSubgroupPartitionedInclusiveXor:
5882 case glslang::EOpSubgroupPartitionedExclusiveXor:
5883#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005884 if (isBool) {
5885 opCode = spv::OpGroupNonUniformLogicalXor;
5886 } else {
5887 opCode = spv::OpGroupNonUniformBitwiseXor;
5888 }
5889 break;
5890 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
5891 case glslang::EOpSubgroupQuadSwapHorizontal:
5892 case glslang::EOpSubgroupQuadSwapVertical:
5893 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
5894 default: assert(0 && "Unhandled subgroup operation!");
5895 }
5896
5897 std::vector<spv::Id> spvGroupOperands;
5898
5899 // Every operation begins with the Execution Scope operand.
5900 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
5901
5902 // Next, for all operations that use a Group Operation, push that as an operand.
5903 switch (op) {
5904 default: break;
5905 case glslang::EOpSubgroupBallotBitCount:
5906 case glslang::EOpSubgroupAdd:
5907 case glslang::EOpSubgroupMul:
5908 case glslang::EOpSubgroupMin:
5909 case glslang::EOpSubgroupMax:
5910 case glslang::EOpSubgroupAnd:
5911 case glslang::EOpSubgroupOr:
5912 case glslang::EOpSubgroupXor:
5913 spvGroupOperands.push_back(spv::GroupOperationReduce);
5914 break;
5915 case glslang::EOpSubgroupBallotInclusiveBitCount:
5916 case glslang::EOpSubgroupInclusiveAdd:
5917 case glslang::EOpSubgroupInclusiveMul:
5918 case glslang::EOpSubgroupInclusiveMin:
5919 case glslang::EOpSubgroupInclusiveMax:
5920 case glslang::EOpSubgroupInclusiveAnd:
5921 case glslang::EOpSubgroupInclusiveOr:
5922 case glslang::EOpSubgroupInclusiveXor:
5923 spvGroupOperands.push_back(spv::GroupOperationInclusiveScan);
5924 break;
5925 case glslang::EOpSubgroupBallotExclusiveBitCount:
5926 case glslang::EOpSubgroupExclusiveAdd:
5927 case glslang::EOpSubgroupExclusiveMul:
5928 case glslang::EOpSubgroupExclusiveMin:
5929 case glslang::EOpSubgroupExclusiveMax:
5930 case glslang::EOpSubgroupExclusiveAnd:
5931 case glslang::EOpSubgroupExclusiveOr:
5932 case glslang::EOpSubgroupExclusiveXor:
5933 spvGroupOperands.push_back(spv::GroupOperationExclusiveScan);
5934 break;
5935 case glslang::EOpSubgroupClusteredAdd:
5936 case glslang::EOpSubgroupClusteredMul:
5937 case glslang::EOpSubgroupClusteredMin:
5938 case glslang::EOpSubgroupClusteredMax:
5939 case glslang::EOpSubgroupClusteredAnd:
5940 case glslang::EOpSubgroupClusteredOr:
5941 case glslang::EOpSubgroupClusteredXor:
5942 spvGroupOperands.push_back(spv::GroupOperationClusteredReduce);
5943 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005944#ifdef NV_EXTENSIONS
5945 case glslang::EOpSubgroupPartitionedAdd:
5946 case glslang::EOpSubgroupPartitionedMul:
5947 case glslang::EOpSubgroupPartitionedMin:
5948 case glslang::EOpSubgroupPartitionedMax:
5949 case glslang::EOpSubgroupPartitionedAnd:
5950 case glslang::EOpSubgroupPartitionedOr:
5951 case glslang::EOpSubgroupPartitionedXor:
5952 spvGroupOperands.push_back(spv::GroupOperationPartitionedReduceNV);
5953 break;
5954 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5955 case glslang::EOpSubgroupPartitionedInclusiveMul:
5956 case glslang::EOpSubgroupPartitionedInclusiveMin:
5957 case glslang::EOpSubgroupPartitionedInclusiveMax:
5958 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5959 case glslang::EOpSubgroupPartitionedInclusiveOr:
5960 case glslang::EOpSubgroupPartitionedInclusiveXor:
5961 spvGroupOperands.push_back(spv::GroupOperationPartitionedInclusiveScanNV);
5962 break;
5963 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5964 case glslang::EOpSubgroupPartitionedExclusiveMul:
5965 case glslang::EOpSubgroupPartitionedExclusiveMin:
5966 case glslang::EOpSubgroupPartitionedExclusiveMax:
5967 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5968 case glslang::EOpSubgroupPartitionedExclusiveOr:
5969 case glslang::EOpSubgroupPartitionedExclusiveXor:
5970 spvGroupOperands.push_back(spv::GroupOperationPartitionedExclusiveScanNV);
5971 break;
5972#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005973 }
5974
5975 // Push back the operands next.
5976 for (auto opIt : operands) {
5977 spvGroupOperands.push_back(opIt);
5978 }
5979
5980 // Some opcodes have additional operands.
5981 switch (op) {
5982 default: break;
5983 case glslang::EOpSubgroupQuadSwapHorizontal: spvGroupOperands.push_back(builder.makeUintConstant(0)); break;
5984 case glslang::EOpSubgroupQuadSwapVertical: spvGroupOperands.push_back(builder.makeUintConstant(1)); break;
5985 case glslang::EOpSubgroupQuadSwapDiagonal: spvGroupOperands.push_back(builder.makeUintConstant(2)); break;
5986 }
5987
5988 return builder.createOp(opCode, typeId, spvGroupOperands);
5989}
5990
John Kessenich5e4b1242015-08-06 22:53:06 -06005991spv::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 -06005992{
John Kessenich66011cb2018-03-06 16:12:04 -07005993 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5994 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06005995
John Kessenich140f3df2015-06-26 16:58:36 -06005996 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005997 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005998 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005999 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006000 spv::Id typeId0 = 0;
6001 if (consumedOperands > 0)
6002 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006003 spv::Id typeId1 = 0;
6004 if (consumedOperands > 1)
6005 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006006 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006007
6008 switch (op) {
6009 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006010 if (isFloat)
6011 libCall = spv::GLSLstd450FMin;
6012 else if (isUnsigned)
6013 libCall = spv::GLSLstd450UMin;
6014 else
6015 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006016 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006017 break;
6018 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006019 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006020 break;
6021 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006022 if (isFloat)
6023 libCall = spv::GLSLstd450FMax;
6024 else if (isUnsigned)
6025 libCall = spv::GLSLstd450UMax;
6026 else
6027 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006028 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006029 break;
6030 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006031 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006032 break;
6033 case glslang::EOpDot:
6034 opCode = spv::OpDot;
6035 break;
6036 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006037 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006038 break;
6039
6040 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006041 if (isFloat)
6042 libCall = spv::GLSLstd450FClamp;
6043 else if (isUnsigned)
6044 libCall = spv::GLSLstd450UClamp;
6045 else
6046 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006047 builder.promoteScalar(precision, operands.front(), operands[1]);
6048 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006049 break;
6050 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006051 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6052 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006053 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006054 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006055 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006056 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006057 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006058 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006059 break;
6060 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006061 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006062 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006063 break;
6064 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006065 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006066 builder.promoteScalar(precision, operands[0], operands[2]);
6067 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006068 break;
6069
6070 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006071 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006072 break;
6073 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006074 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006075 break;
6076 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006077 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006078 break;
6079 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006080 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006081 break;
6082 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006083 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006084 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006085 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006086#ifdef AMD_EXTENSIONS
6087 if (typeProxy == glslang::EbtFloat16)
6088 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6089#endif
John Kessenich92187592016-02-01 13:45:25 -07006090 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08006091 libCall = spv::GLSLstd450InterpolateAtSample;
6092 break;
6093 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006094#ifdef AMD_EXTENSIONS
6095 if (typeProxy == glslang::EbtFloat16)
6096 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6097#endif
John Kessenich92187592016-02-01 13:45:25 -07006098 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08006099 libCall = spv::GLSLstd450InterpolateAtOffset;
6100 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006101 case glslang::EOpAddCarry:
6102 opCode = spv::OpIAddCarry;
6103 typeId = builder.makeStructResultType(typeId0, typeId0);
6104 consumedOperands = 2;
6105 break;
6106 case glslang::EOpSubBorrow:
6107 opCode = spv::OpISubBorrow;
6108 typeId = builder.makeStructResultType(typeId0, typeId0);
6109 consumedOperands = 2;
6110 break;
6111 case glslang::EOpUMulExtended:
6112 opCode = spv::OpUMulExtended;
6113 typeId = builder.makeStructResultType(typeId0, typeId0);
6114 consumedOperands = 2;
6115 break;
6116 case glslang::EOpIMulExtended:
6117 opCode = spv::OpSMulExtended;
6118 typeId = builder.makeStructResultType(typeId0, typeId0);
6119 consumedOperands = 2;
6120 break;
6121 case glslang::EOpBitfieldExtract:
6122 if (isUnsigned)
6123 opCode = spv::OpBitFieldUExtract;
6124 else
6125 opCode = spv::OpBitFieldSExtract;
6126 break;
6127 case glslang::EOpBitfieldInsert:
6128 opCode = spv::OpBitFieldInsert;
6129 break;
6130
6131 case glslang::EOpFma:
6132 libCall = spv::GLSLstd450Fma;
6133 break;
6134 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006135 {
6136 libCall = spv::GLSLstd450FrexpStruct;
6137 assert(builder.isPointerType(typeId1));
6138 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006139 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006140#ifdef AMD_EXTENSIONS
6141 if (width == 16)
6142 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6143 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
6144#endif
Rex Xu470026f2017-03-29 17:12:40 +08006145 if (builder.getNumComponents(operands[0]) == 1)
6146 frexpIntType = builder.makeIntegerType(width, true);
6147 else
6148 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6149 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6150 consumedOperands = 1;
6151 }
John Kessenich55e7d112015-11-15 21:33:39 -07006152 break;
6153 case glslang::EOpLdexp:
6154 libCall = spv::GLSLstd450Ldexp;
6155 break;
6156
Rex Xu574ab042016-04-14 16:53:07 +08006157 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08006158 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08006159
John Kessenich66011cb2018-03-06 16:12:04 -07006160 case glslang::EOpSubgroupBroadcast:
6161 case glslang::EOpSubgroupBallotBitExtract:
6162 case glslang::EOpSubgroupShuffle:
6163 case glslang::EOpSubgroupShuffleXor:
6164 case glslang::EOpSubgroupShuffleUp:
6165 case glslang::EOpSubgroupShuffleDown:
6166 case glslang::EOpSubgroupClusteredAdd:
6167 case glslang::EOpSubgroupClusteredMul:
6168 case glslang::EOpSubgroupClusteredMin:
6169 case glslang::EOpSubgroupClusteredMax:
6170 case glslang::EOpSubgroupClusteredAnd:
6171 case glslang::EOpSubgroupClusteredOr:
6172 case glslang::EOpSubgroupClusteredXor:
6173 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006174#ifdef NV_EXTENSIONS
6175 case glslang::EOpSubgroupPartitionedAdd:
6176 case glslang::EOpSubgroupPartitionedMul:
6177 case glslang::EOpSubgroupPartitionedMin:
6178 case glslang::EOpSubgroupPartitionedMax:
6179 case glslang::EOpSubgroupPartitionedAnd:
6180 case glslang::EOpSubgroupPartitionedOr:
6181 case glslang::EOpSubgroupPartitionedXor:
6182 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6183 case glslang::EOpSubgroupPartitionedInclusiveMul:
6184 case glslang::EOpSubgroupPartitionedInclusiveMin:
6185 case glslang::EOpSubgroupPartitionedInclusiveMax:
6186 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6187 case glslang::EOpSubgroupPartitionedInclusiveOr:
6188 case glslang::EOpSubgroupPartitionedInclusiveXor:
6189 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6190 case glslang::EOpSubgroupPartitionedExclusiveMul:
6191 case glslang::EOpSubgroupPartitionedExclusiveMin:
6192 case glslang::EOpSubgroupPartitionedExclusiveMax:
6193 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6194 case glslang::EOpSubgroupPartitionedExclusiveOr:
6195 case glslang::EOpSubgroupPartitionedExclusiveXor:
6196#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006197 return createSubgroupOperation(op, typeId, operands, typeProxy);
6198
Rex Xu9d93a232016-05-05 12:30:44 +08006199#ifdef AMD_EXTENSIONS
6200 case glslang::EOpSwizzleInvocations:
6201 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6202 libCall = spv::SwizzleInvocationsAMD;
6203 break;
6204 case glslang::EOpSwizzleInvocationsMasked:
6205 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6206 libCall = spv::SwizzleInvocationsMaskedAMD;
6207 break;
6208 case glslang::EOpWriteInvocation:
6209 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6210 libCall = spv::WriteInvocationAMD;
6211 break;
6212
6213 case glslang::EOpMin3:
6214 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6215 if (isFloat)
6216 libCall = spv::FMin3AMD;
6217 else {
6218 if (isUnsigned)
6219 libCall = spv::UMin3AMD;
6220 else
6221 libCall = spv::SMin3AMD;
6222 }
6223 break;
6224 case glslang::EOpMax3:
6225 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6226 if (isFloat)
6227 libCall = spv::FMax3AMD;
6228 else {
6229 if (isUnsigned)
6230 libCall = spv::UMax3AMD;
6231 else
6232 libCall = spv::SMax3AMD;
6233 }
6234 break;
6235 case glslang::EOpMid3:
6236 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6237 if (isFloat)
6238 libCall = spv::FMid3AMD;
6239 else {
6240 if (isUnsigned)
6241 libCall = spv::UMid3AMD;
6242 else
6243 libCall = spv::SMid3AMD;
6244 }
6245 break;
6246
6247 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006248 if (typeProxy == glslang::EbtFloat16)
6249 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08006250 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
6251 libCall = spv::InterpolateAtVertexAMD;
6252 break;
6253#endif
6254
John Kessenich140f3df2015-06-26 16:58:36 -06006255 default:
6256 return 0;
6257 }
6258
6259 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07006260 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05006261 // Use an extended instruction from the standard library.
6262 // Construct the call arguments, without modifying the original operands vector.
6263 // We might need the remaining arguments, e.g. in the EOpFrexp case.
6264 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08006265 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07006266 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07006267 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06006268 case 0:
6269 // should all be handled by visitAggregate and createNoArgOperation
6270 assert(0);
6271 return 0;
6272 case 1:
6273 // should all be handled by createUnaryOperation
6274 assert(0);
6275 return 0;
6276 case 2:
6277 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
6278 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006279 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006280 // anything 3 or over doesn't have l-value operands, so all should be consumed
6281 assert(consumedOperands == operands.size());
6282 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06006283 break;
6284 }
6285 }
6286
John Kessenich55e7d112015-11-15 21:33:39 -07006287 // Decode the return types that were structures
6288 switch (op) {
6289 case glslang::EOpAddCarry:
6290 case glslang::EOpSubBorrow:
6291 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6292 id = builder.createCompositeExtract(id, typeId0, 0);
6293 break;
6294 case glslang::EOpUMulExtended:
6295 case glslang::EOpIMulExtended:
6296 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
6297 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6298 break;
6299 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006300 {
6301 assert(operands.size() == 2);
6302 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
6303 // "exp" is floating-point type (from HLSL intrinsic)
6304 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
6305 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
6306 builder.createStore(member1, operands[1]);
6307 } else
6308 // "exp" is integer type (from GLSL built-in function)
6309 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
6310 id = builder.createCompositeExtract(id, typeId0, 0);
6311 }
John Kessenich55e7d112015-11-15 21:33:39 -07006312 break;
6313 default:
6314 break;
6315 }
6316
John Kessenich32cfd492016-02-02 12:37:46 -07006317 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006318}
6319
Rex Xu9d93a232016-05-05 12:30:44 +08006320// Intrinsics with no arguments (or no return value, and no precision).
6321spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06006322{
6323 // TODO: get the barrier operands correct
6324
6325 switch (op) {
6326 case glslang::EOpEmitVertex:
6327 builder.createNoResultOp(spv::OpEmitVertex);
6328 return 0;
6329 case glslang::EOpEndPrimitive:
6330 builder.createNoResultOp(spv::OpEndPrimitive);
6331 return 0;
6332 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006333 if (glslangIntermediate->getStage() == EShLangTessControl) {
6334 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
6335 // TODO: prefer the following, when available:
6336 // builder.createControlBarrier(spv::ScopePatch, spv::ScopePatch,
6337 // spv::MemorySemanticsPatchMask |
6338 // spv::MemorySemanticsAcquireReleaseMask);
6339 } else {
6340 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6341 spv::MemorySemanticsWorkgroupMemoryMask |
6342 spv::MemorySemanticsAcquireReleaseMask);
6343 }
John Kessenich140f3df2015-06-26 16:58:36 -06006344 return 0;
6345 case glslang::EOpMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006346 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory |
6347 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006348 return 0;
6349 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich82979362017-12-11 04:02:24 -07006350 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask |
6351 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006352 return 0;
6353 case glslang::EOpMemoryBarrierBuffer:
John Kessenich82979362017-12-11 04:02:24 -07006354 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6355 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006356 return 0;
6357 case glslang::EOpMemoryBarrierImage:
John Kessenich82979362017-12-11 04:02:24 -07006358 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask |
6359 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006360 return 0;
6361 case glslang::EOpMemoryBarrierShared:
John Kessenich82979362017-12-11 04:02:24 -07006362 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask |
6363 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006364 return 0;
6365 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006366 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
6367 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006368 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06006369 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006370 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07006371 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07006372 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006373 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07006374 case glslang::EOpDeviceMemoryBarrier:
6375 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6376 spv::MemorySemanticsImageMemoryMask |
6377 spv::MemorySemanticsAcquireReleaseMask);
6378 return 0;
6379 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
6380 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6381 spv::MemorySemanticsImageMemoryMask |
6382 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006383 return 0;
6384 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07006385 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6386 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006387 return 0;
6388 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006389 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6390 spv::MemorySemanticsWorkgroupMemoryMask |
6391 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006392 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07006393 case glslang::EOpSubgroupBarrier:
6394 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6395 spv::MemorySemanticsAcquireReleaseMask);
6396 return spv::NoResult;
6397 case glslang::EOpSubgroupMemoryBarrier:
6398 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6399 spv::MemorySemanticsAcquireReleaseMask);
6400 return spv::NoResult;
6401 case glslang::EOpSubgroupMemoryBarrierBuffer:
6402 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
6403 spv::MemorySemanticsAcquireReleaseMask);
6404 return spv::NoResult;
6405 case glslang::EOpSubgroupMemoryBarrierImage:
6406 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
6407 spv::MemorySemanticsAcquireReleaseMask);
6408 return spv::NoResult;
6409 case glslang::EOpSubgroupMemoryBarrierShared:
6410 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6411 spv::MemorySemanticsAcquireReleaseMask);
6412 return spv::NoResult;
6413 case glslang::EOpSubgroupElect: {
6414 std::vector<spv::Id> operands;
6415 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
6416 }
Rex Xu9d93a232016-05-05 12:30:44 +08006417#ifdef AMD_EXTENSIONS
6418 case glslang::EOpTime:
6419 {
6420 std::vector<spv::Id> args; // Dummy arguments
6421 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
6422 return builder.setPrecision(id, precision);
6423 }
6424#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006425 default:
Lei Zhang17535f72016-05-04 15:55:59 -04006426 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06006427 return 0;
6428 }
6429}
6430
6431spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
6432{
John Kessenich2f273362015-07-18 22:34:27 -06006433 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06006434 spv::Id id;
6435 if (symbolValues.end() != iter) {
6436 id = iter->second;
6437 return id;
6438 }
6439
6440 // it was not found, create it
6441 id = createSpvVariable(symbol);
6442 symbolValues[symbol->getId()] = id;
6443
Rex Xuc884b4a2016-06-29 15:03:44 +08006444 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006445 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
6446 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
6447 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07006448 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07006449 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06006450 if (symbol->getQualifier().hasIndex())
6451 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
6452 if (symbol->getQualifier().hasComponent())
6453 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06006454 // atomic counters use this:
6455 if (symbol->getQualifier().hasOffset())
6456 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006457 }
6458
scygan2c864272016-05-18 18:09:17 +02006459 if (symbol->getQualifier().hasLocation())
6460 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07006461 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07006462 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07006463 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06006464 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07006465 }
John Kessenich140f3df2015-06-26 16:58:36 -06006466 if (symbol->getQualifier().hasSet())
6467 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07006468 else if (IsDescriptorResource(symbol->getType())) {
6469 // default to 0
6470 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
6471 }
John Kessenich140f3df2015-06-26 16:58:36 -06006472 if (symbol->getQualifier().hasBinding())
6473 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07006474 if (symbol->getQualifier().hasAttachment())
6475 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06006476 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07006477 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06006478 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06006479 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07006480 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06006481 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07006482 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
6483 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
6484 builder.addDecoration(id, spv::DecorationXfbStride, stride);
6485 }
6486 if (symbol->getQualifier().hasXfbOffset())
6487 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006488 }
6489
Rex Xu1da878f2016-02-21 20:59:01 +08006490 if (symbol->getType().isImage()) {
6491 std::vector<spv::Decoration> memory;
6492 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
6493 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07006494 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08006495 }
6496
John Kessenich140f3df2015-06-26 16:58:36 -06006497 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06006498 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06006499 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07006500 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06006501
John Kessenich5611c6d2018-04-05 11:25:02 -06006502 // nonuniform
6503 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
6504
John Kessenichecba76f2017-01-06 00:34:48 -07006505#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08006506 if (builtIn == spv::BuiltInSampleMask) {
6507 spv::Decoration decoration;
6508 // GL_NV_sample_mask_override_coverage extension
6509 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08006510 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08006511 else
6512 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07006513 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08006514 if (decoration != spv::DecorationMax) {
6515 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
6516 }
6517 }
chaoc771d89f2017-01-13 01:10:53 -08006518 else if (builtIn == spv::BuiltInLayer) {
6519 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06006520 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006521 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08006522 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
6523 builder.addExtension(spv::E_SPV_NV_viewport_array2);
6524 }
John Kessenichb41bff62017-08-11 13:07:17 -06006525 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006526 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
6527 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08006528 builder.addCapability(spv::CapabilityShaderStereoViewNV);
6529 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
6530 }
6531 }
6532
chaoc6e5acae2016-12-20 13:28:52 -08006533 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006534 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08006535 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08006536 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
6537 }
chaoc0ad6a4e2016-12-19 16:29:34 -08006538#endif
6539
John Kessenich5d610ee2018-03-07 18:05:55 -07006540 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
6541 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
6542 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
6543 symbol->getType().getQualifier().semanticName);
6544 }
6545
John Kessenich140f3df2015-06-26 16:58:36 -06006546 return id;
6547}
6548
John Kessenich55e7d112015-11-15 21:33:39 -07006549// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07006550// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07006551//
6552// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
6553//
6554// Recursively walk the nodes. The nodes form a tree whose leaves are
6555// regular constants, which themselves are trees that createSpvConstant()
6556// recursively walks. So, this function walks the "top" of the tree:
6557// - emit specialization constant-building instructions for specConstant
6558// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04006559spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07006560{
John Kessenich7cc0e282016-03-20 00:46:02 -06006561 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07006562
qining4f4bb812016-04-03 23:55:17 -04006563 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07006564 if (! node.getQualifier().specConstant) {
6565 // hand off to the non-spec-constant path
6566 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
6567 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04006568 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07006569 nextConst, false);
6570 }
6571
6572 // We now know we have a specialization constant to build
6573
John Kessenichd94c0032016-05-30 19:29:40 -06006574 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04006575 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
6576 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
6577 std::vector<spv::Id> dimConstId;
6578 for (int dim = 0; dim < 3; ++dim) {
6579 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
6580 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07006581 if (specConst) {
6582 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
6583 glslangIntermediate->getLocalSizeSpecId(dim));
6584 }
qining4f4bb812016-04-03 23:55:17 -04006585 }
6586 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
6587 }
6588
6589 // An AST node labelled as specialization constant should be a symbol node.
6590 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
6591 if (auto* sn = node.getAsSymbolNode()) {
6592 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04006593 // Traverse the constant constructor sub tree like generating normal run-time instructions.
6594 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
6595 // will set the builder into spec constant op instruction generating mode.
6596 sub_tree->traverse(this);
6597 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04006598 } else if (auto* const_union_array = &sn->getConstArray()){
6599 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01006600 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
6601 builder.addName(id, sn->getName().c_str());
6602 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07006603 }
6604 }
qining4f4bb812016-04-03 23:55:17 -04006605
6606 // Neither a front-end constant node, nor a specialization constant node with constant union array or
6607 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04006608 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04006609 exit(1);
6610 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07006611}
6612
John Kessenich140f3df2015-06-26 16:58:36 -06006613// Use 'consts' as the flattened glslang source of scalar constants to recursively
6614// build the aggregate SPIR-V constant.
6615//
6616// If there are not enough elements present in 'consts', 0 will be substituted;
6617// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
6618//
qining08408382016-03-21 09:51:37 -04006619spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06006620{
6621 // vector of constants for SPIR-V
6622 std::vector<spv::Id> spvConsts;
6623
6624 // Type is used for struct and array constants
6625 spv::Id typeId = convertGlslangToSpvType(glslangType);
6626
6627 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006628 glslang::TType elementType(glslangType, 0);
6629 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04006630 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006631 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006632 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06006633 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04006634 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006635 } else if (glslangType.getStruct()) {
6636 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
6637 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04006638 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06006639 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06006640 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
6641 bool zero = nextConst >= consts.size();
6642 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006643 case glslang::EbtInt8:
6644 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
6645 break;
6646 case glslang::EbtUint8:
6647 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
6648 break;
6649 case glslang::EbtInt16:
6650 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
6651 break;
6652 case glslang::EbtUint16:
6653 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
6654 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006655 case glslang::EbtInt:
6656 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
6657 break;
6658 case glslang::EbtUint:
6659 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
6660 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006661 case glslang::EbtInt64:
6662 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
6663 break;
6664 case glslang::EbtUint64:
6665 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
6666 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006667 case glslang::EbtFloat:
6668 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
6669 break;
6670 case glslang::EbtDouble:
6671 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
6672 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006673 case glslang::EbtFloat16:
6674 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
6675 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006676 case glslang::EbtBool:
6677 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
6678 break;
6679 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006680 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06006681 break;
6682 }
6683 ++nextConst;
6684 }
6685 } else {
6686 // we have a non-aggregate (scalar) constant
6687 bool zero = nextConst >= consts.size();
6688 spv::Id scalar = 0;
6689 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006690 case glslang::EbtInt8:
6691 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
6692 break;
6693 case glslang::EbtUint8:
6694 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
6695 break;
6696 case glslang::EbtInt16:
6697 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
6698 break;
6699 case glslang::EbtUint16:
6700 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
6701 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006702 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07006703 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006704 break;
6705 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07006706 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006707 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006708 case glslang::EbtInt64:
6709 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
6710 break;
6711 case glslang::EbtUint64:
6712 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
6713 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006714 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07006715 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006716 break;
6717 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07006718 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006719 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006720 case glslang::EbtFloat16:
6721 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
6722 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006723 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07006724 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006725 break;
6726 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006727 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06006728 break;
6729 }
6730 ++nextConst;
6731 return scalar;
6732 }
6733
6734 return builder.makeCompositeConstant(typeId, spvConsts);
6735}
6736
John Kessenich7c1aa102015-10-15 13:29:11 -06006737// Return true if the node is a constant or symbol whose reading has no
6738// non-trivial observable cost or effect.
6739bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
6740{
6741 // don't know what this is
6742 if (node == nullptr)
6743 return false;
6744
6745 // a constant is safe
6746 if (node->getAsConstantUnion() != nullptr)
6747 return true;
6748
6749 // not a symbol means non-trivial
6750 if (node->getAsSymbolNode() == nullptr)
6751 return false;
6752
6753 // a symbol, depends on what's being read
6754 switch (node->getType().getQualifier().storage) {
6755 case glslang::EvqTemporary:
6756 case glslang::EvqGlobal:
6757 case glslang::EvqIn:
6758 case glslang::EvqInOut:
6759 case glslang::EvqConst:
6760 case glslang::EvqConstReadOnly:
6761 case glslang::EvqUniform:
6762 return true;
6763 default:
6764 return false;
6765 }
qining25262b32016-05-06 17:25:16 -04006766}
John Kessenich7c1aa102015-10-15 13:29:11 -06006767
6768// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06006769// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06006770// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06006771// Return true if trivial.
6772bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
6773{
6774 if (node == nullptr)
6775 return false;
6776
John Kessenich84cc15f2017-05-24 16:44:47 -06006777 // count non scalars as trivial, as well as anything coming from HLSL
6778 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06006779 return true;
6780
John Kessenich7c1aa102015-10-15 13:29:11 -06006781 // symbols and constants are trivial
6782 if (isTrivialLeaf(node))
6783 return true;
6784
6785 // otherwise, it needs to be a simple operation or one or two leaf nodes
6786
6787 // not a simple operation
6788 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
6789 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
6790 if (binaryNode == nullptr && unaryNode == nullptr)
6791 return false;
6792
6793 // not on leaf nodes
6794 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
6795 return false;
6796
6797 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
6798 return false;
6799 }
6800
6801 switch (node->getAsOperator()->getOp()) {
6802 case glslang::EOpLogicalNot:
6803 case glslang::EOpConvIntToBool:
6804 case glslang::EOpConvUintToBool:
6805 case glslang::EOpConvFloatToBool:
6806 case glslang::EOpConvDoubleToBool:
6807 case glslang::EOpEqual:
6808 case glslang::EOpNotEqual:
6809 case glslang::EOpLessThan:
6810 case glslang::EOpGreaterThan:
6811 case glslang::EOpLessThanEqual:
6812 case glslang::EOpGreaterThanEqual:
6813 case glslang::EOpIndexDirect:
6814 case glslang::EOpIndexDirectStruct:
6815 case glslang::EOpLogicalXor:
6816 case glslang::EOpAny:
6817 case glslang::EOpAll:
6818 return true;
6819 default:
6820 return false;
6821 }
6822}
6823
6824// Emit short-circuiting code, where 'right' is never evaluated unless
6825// the left side is true (for &&) or false (for ||).
6826spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
6827{
6828 spv::Id boolTypeId = builder.makeBoolType();
6829
6830 // emit left operand
6831 builder.clearAccessChain();
6832 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006833 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006834
6835 // Operands to accumulate OpPhi operands
6836 std::vector<spv::Id> phiOperands;
6837 // accumulate left operand's phi information
6838 phiOperands.push_back(leftId);
6839 phiOperands.push_back(builder.getBuildPoint()->getId());
6840
6841 // Make the two kinds of operation symmetric with a "!"
6842 // || => emit "if (! left) result = right"
6843 // && => emit "if ( left) result = right"
6844 //
6845 // TODO: this runtime "not" for || could be avoided by adding functionality
6846 // to 'builder' to have an "else" without an "then"
6847 if (op == glslang::EOpLogicalOr)
6848 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
6849
6850 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08006851 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06006852
6853 // emit right operand as the "then" part of the "if"
6854 builder.clearAccessChain();
6855 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006856 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006857
6858 // accumulate left operand's phi information
6859 phiOperands.push_back(rightId);
6860 phiOperands.push_back(builder.getBuildPoint()->getId());
6861
6862 // finish the "if"
6863 ifBuilder.makeEndIf();
6864
6865 // phi together the two results
6866 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
6867}
6868
Frank Henigman541f7bb2018-01-16 00:18:26 -05006869#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08006870// Return type Id of the imported set of extended instructions corresponds to the name.
6871// Import this set if it has not been imported yet.
6872spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
6873{
6874 if (extBuiltinMap.find(name) != extBuiltinMap.end())
6875 return extBuiltinMap[name];
6876 else {
Rex Xu51596642016-09-21 18:56:12 +08006877 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08006878 spv::Id extBuiltins = builder.import(name);
6879 extBuiltinMap[name] = extBuiltins;
6880 return extBuiltins;
6881 }
6882}
Frank Henigman541f7bb2018-01-16 00:18:26 -05006883#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006884
John Kessenich140f3df2015-06-26 16:58:36 -06006885}; // end anonymous namespace
6886
6887namespace glslang {
6888
John Kessenich68d78fd2015-07-12 19:28:10 -06006889void GetSpirvVersion(std::string& version)
6890{
John Kessenich9e55f632015-07-15 10:03:39 -06006891 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06006892 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07006893 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06006894 version = buf;
6895}
6896
John Kessenicha372a3e2017-11-02 22:32:14 -06006897// For low-order part of the generator's magic number. Bump up
6898// when there is a change in the style (e.g., if SSA form changes,
6899// or a different instruction sequence to do something gets used).
6900int GetSpirvGeneratorVersion()
6901{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07006902 // return 1; // start
6903 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07006904 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07006905 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07006906 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06006907 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
6908 // versions 4 and 6 each generate OpArrayLength as it has long been done
6909 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06006910}
6911
John Kessenich140f3df2015-06-26 16:58:36 -06006912// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006913void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06006914{
6915 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06006916 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006917 if (out.fail())
6918 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06006919 for (int i = 0; i < (int)spirv.size(); ++i) {
6920 unsigned int word = spirv[i];
6921 out.write((const char*)&word, 4);
6922 }
6923 out.close();
6924}
6925
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006926// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08006927void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006928{
6929 std::ofstream out;
6930 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006931 if (out.fail())
6932 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07006933 out << "\t// " <<
6934 glslang::GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
6935 std::endl;
Flavio15017db2017-02-15 14:29:33 -08006936 if (varName != nullptr) {
6937 out << "\t #pragma once" << std::endl;
6938 out << "const uint32_t " << varName << "[] = {" << std::endl;
6939 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006940 const int WORDS_PER_LINE = 8;
6941 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
6942 out << "\t";
6943 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
6944 const unsigned int word = spirv[i + j];
6945 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
6946 if (i + j + 1 < (int)spirv.size()) {
6947 out << ",";
6948 }
6949 }
6950 out << std::endl;
6951 }
Flavio15017db2017-02-15 14:29:33 -08006952 if (varName != nullptr) {
6953 out << "};";
6954 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006955 out.close();
6956}
6957
John Kessenich140f3df2015-06-26 16:58:36 -06006958//
6959// Set up the glslang traversal
6960//
John Kessenich121853f2017-05-31 17:11:16 -06006961void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06006962{
Lei Zhang17535f72016-05-04 15:55:59 -04006963 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06006964 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04006965}
6966
John Kessenich121853f2017-05-31 17:11:16 -06006967void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
6968 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04006969{
John Kessenich140f3df2015-06-26 16:58:36 -06006970 TIntermNode* root = intermediate.getTreeRoot();
6971
6972 if (root == 0)
6973 return;
6974
John Kessenich121853f2017-05-31 17:11:16 -06006975 glslang::SpvOptions defaultOptions;
6976 if (options == nullptr)
6977 options = &defaultOptions;
6978
John Kessenich140f3df2015-06-26 16:58:36 -06006979 glslang::GetThreadPoolAllocator().push();
6980
John Kessenich2b5ea9f2018-01-31 18:35:56 -07006981 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06006982 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07006983 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06006984 it.dumpSpv(spirv);
6985
GregFfb03a552018-03-29 11:49:14 -06006986#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06006987 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
6988 // eg. forward and remove memory writes of opaque types.
6989 if ((intermediate.getSource() == EShSourceHlsl ||
6990 options->optimizeSize) &&
6991 !options->disableOptimizer) {
6992 spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
6993
6994 spvtools::Optimizer optimizer(target_env);
6995 optimizer.SetMessageConsumer([](spv_message_level_t level,
6996 const char* source,
6997 const spv_position_t& position,
6998 const char* message) {
6999 std::cerr << StringifyMessage(level, source, position, message)
7000 << std::endl;
7001 });
7002
GregFeecb8742018-03-26 12:11:55 -06007003 optimizer.RegisterPass(CreateMergeReturnPass());
GregFcd1f1692017-09-21 18:40:22 -06007004 optimizer.RegisterPass(CreateInlineExhaustivePass());
GregFe0639282017-12-21 10:55:57 -07007005 optimizer.RegisterPass(CreateEliminateDeadFunctionsPass());
7006 optimizer.RegisterPass(CreateScalarReplacementPass());
GregFcd1f1692017-09-21 18:40:22 -06007007 optimizer.RegisterPass(CreateLocalAccessChainConvertPass());
7008 optimizer.RegisterPass(CreateLocalSingleBlockLoadStoreElimPass());
7009 optimizer.RegisterPass(CreateLocalSingleStoreElimPass());
GregFb0c42b22018-05-31 16:17:18 -06007010 optimizer.RegisterPass(CreateSimplificationPass());
GregFeecb8742018-03-26 12:11:55 -06007011 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFb0c42b22018-05-31 16:17:18 -06007012 optimizer.RegisterPass(CreateVectorDCEPass());
GregF8a4848f2018-02-07 16:04:42 -07007013 optimizer.RegisterPass(CreateDeadInsertElimPass());
GregFcd1f1692017-09-21 18:40:22 -06007014 optimizer.RegisterPass(CreateAggressiveDCEPass());
7015 optimizer.RegisterPass(CreateDeadBranchElimPass());
7016 optimizer.RegisterPass(CreateBlockMergePass());
7017 optimizer.RegisterPass(CreateLocalMultiStoreElimPass());
GregFb0c42b22018-05-31 16:17:18 -06007018 optimizer.RegisterPass(CreateIfConversionPass());
7019 optimizer.RegisterPass(CreateSimplificationPass());
GregFeecb8742018-03-26 12:11:55 -06007020 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFb0c42b22018-05-31 16:17:18 -06007021 optimizer.RegisterPass(CreateVectorDCEPass());
GregF8a4848f2018-02-07 16:04:42 -07007022 optimizer.RegisterPass(CreateDeadInsertElimPass());
7023 if (options->optimizeSize) {
7024 optimizer.RegisterPass(CreateRedundancyEliminationPass());
7025 // TODO(greg-lunarg): Add this when AMD driver issues are resolved
7026 // optimizer.RegisterPass(CreateCommonUniformElimPass());
7027 }
GregFcd1f1692017-09-21 18:40:22 -06007028 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFb0c42b22018-05-31 16:17:18 -06007029 optimizer.RegisterPass(CreateCFGCleanupPass());
GregFcd1f1692017-09-21 18:40:22 -06007030
7031 if (!optimizer.Run(spirv.data(), spirv.size(), &spirv))
7032 return;
GregFcd1f1692017-09-21 18:40:22 -06007033 }
7034#endif
7035
John Kessenich140f3df2015-06-26 16:58:36 -06007036 glslang::GetThreadPoolAllocator().pop();
7037}
7038
7039}; // end namespace glslang