blob: 86c4d4911712259d73cd2414aeaececea14a512e [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 Kessenichf04c51b2018-08-03 15:56:12 -06001194 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001195 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001196 builder.setBuildPoint(shaderEntry->getLastBlock());
1197 builder.leaveFunction();
1198 }
1199
John Kessenich7ba63412015-12-20 17:37:07 -07001200 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001201 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1202 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001203
John Kessenichf04c51b2018-08-03 15:56:12 -06001204 // Add capabilities, extensions, remove unneeded decorations, etc.,
1205 // based on the resulting SPIR-V.
1206 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001207}
1208
John Kessenichfca82622016-11-26 13:23:20 -07001209// Write the SPV into 'out'.
1210void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001211{
John Kessenichfca82622016-11-26 13:23:20 -07001212 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001213}
1214
1215//
1216// Implement the traversal functions.
1217//
1218// Return true from interior nodes to have the external traversal
1219// continue on to children. Return false if children were
1220// already processed.
1221//
1222
1223//
qining25262b32016-05-06 17:25:16 -04001224// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001225// - uniform/input reads
1226// - output writes
1227// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1228// - something simple that degenerates into the last bullet
1229//
1230void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1231{
qining75d1d802016-04-06 14:42:01 -04001232 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1233 if (symbol->getType().getQualifier().isSpecConstant())
1234 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1235
John Kessenich140f3df2015-06-26 16:58:36 -06001236 // getSymbolId() will set up all the IO decorations on the first call.
1237 // Formal function parameters were mapped during makeFunctions().
1238 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001239
1240 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1241 if (builder.isPointer(id)) {
1242 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001243 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1244 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1245 iOSet.insert(id);
1246 }
John Kessenich7ba63412015-12-20 17:37:07 -07001247 }
1248
1249 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001250 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001251 // Prepare to generate code for the access
1252
1253 // L-value chains will be computed left to right. We're on the symbol now,
1254 // which is the left-most part of the access chain, so now is "clear" time,
1255 // followed by setting the base.
1256 builder.clearAccessChain();
1257
1258 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001259 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001260 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001261 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001262 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001263 // These are also pure R-values.
1264 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001265 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001266 builder.setAccessChainRValue(id);
1267 else
1268 builder.setAccessChainLValue(id);
1269 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001270
1271 // Process linkage-only nodes for any special additional interface work.
1272 if (linkageOnly) {
1273 if (glslangIntermediate->getHlslFunctionality1()) {
1274 // Map implicit counter buffers to their originating buffers, which should have been
1275 // seen by now, given earlier pruning of unused counters, and preservation of order
1276 // of declaration.
1277 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1278 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1279 // Save possible originating buffers for counter buffers, keyed by
1280 // making the potential counter-buffer name.
1281 std::string keyName = symbol->getName().c_str();
1282 keyName = glslangIntermediate->addCounterBufferName(keyName);
1283 counterOriginator[keyName] = symbol;
1284 } else {
1285 // Handle a counter buffer, by finding the saved originating buffer.
1286 std::string keyName = symbol->getName().c_str();
1287 auto it = counterOriginator.find(keyName);
1288 if (it != counterOriginator.end()) {
1289 id = getSymbolId(it->second);
1290 if (id != spv::NoResult) {
1291 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001292 if (counterId != spv::NoResult) {
1293 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001294 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001295 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001296 }
1297 }
1298 }
1299 }
1300 }
1301 }
John Kessenich140f3df2015-06-26 16:58:36 -06001302}
1303
1304bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1305{
John Kesseniche485c7a2017-05-31 18:50:53 -06001306 builder.setLine(node->getLoc().line);
1307
qining40887662016-04-03 22:20:42 -04001308 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1309 if (node->getType().getQualifier().isSpecConstant())
1310 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1311
John Kessenich140f3df2015-06-26 16:58:36 -06001312 // First, handle special cases
1313 switch (node->getOp()) {
1314 case glslang::EOpAssign:
1315 case glslang::EOpAddAssign:
1316 case glslang::EOpSubAssign:
1317 case glslang::EOpMulAssign:
1318 case glslang::EOpVectorTimesMatrixAssign:
1319 case glslang::EOpVectorTimesScalarAssign:
1320 case glslang::EOpMatrixTimesScalarAssign:
1321 case glslang::EOpMatrixTimesMatrixAssign:
1322 case glslang::EOpDivAssign:
1323 case glslang::EOpModAssign:
1324 case glslang::EOpAndAssign:
1325 case glslang::EOpInclusiveOrAssign:
1326 case glslang::EOpExclusiveOrAssign:
1327 case glslang::EOpLeftShiftAssign:
1328 case glslang::EOpRightShiftAssign:
1329 // A bin-op assign "a += b" means the same thing as "a = a + b"
1330 // where a is evaluated before b. For a simple assignment, GLSL
1331 // says to evaluate the left before the right. So, always, left
1332 // node then right node.
1333 {
1334 // get the left l-value, save it away
1335 builder.clearAccessChain();
1336 node->getLeft()->traverse(this);
1337 spv::Builder::AccessChain lValue = builder.getAccessChain();
1338
1339 // evaluate the right
1340 builder.clearAccessChain();
1341 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001342 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001343
1344 if (node->getOp() != glslang::EOpAssign) {
1345 // the left is also an r-value
1346 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001347 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001348
1349 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001350 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001351 TranslateNoContractionDecoration(node->getType().getQualifier()),
1352 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001353 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001354 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1355 node->getType().getBasicType());
1356
1357 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001358 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001359 }
1360
1361 // store the result
1362 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001363 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001364
1365 // assignments are expressions having an rValue after they are evaluated...
1366 builder.clearAccessChain();
1367 builder.setAccessChainRValue(rValue);
1368 }
1369 return false;
1370 case glslang::EOpIndexDirect:
1371 case glslang::EOpIndexDirectStruct:
1372 {
1373 // Get the left part of the access chain.
1374 node->getLeft()->traverse(this);
1375
1376 // Add the next element in the chain
1377
David Netoa901ffe2016-06-08 14:11:40 +01001378 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001379 if (! node->getLeft()->getType().isArray() &&
1380 node->getLeft()->getType().isVector() &&
1381 node->getOp() == glslang::EOpIndexDirect) {
1382 // This is essentially a hard-coded vector swizzle of size 1,
1383 // so short circuit the access-chain stuff with a swizzle.
1384 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001385 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001386 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001387 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001388 int spvIndex = glslangIndex;
1389 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1390 node->getOp() == glslang::EOpIndexDirectStruct)
1391 {
1392 // This may be, e.g., an anonymous block-member selection, which generally need
1393 // index remapping due to hidden members in anonymous blocks.
1394 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1395 assert(remapper.size() > 0);
1396 spvIndex = remapper[glslangIndex];
1397 }
John Kessenichebb50532016-05-16 19:22:05 -06001398
David Netoa901ffe2016-06-08 14:11:40 +01001399 // normal case for indexing array or structure or block
1400 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1401
1402 // Add capabilities here for accessing PointSize and clip/cull distance.
1403 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001404 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001405 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001406 }
1407 }
1408 return false;
1409 case glslang::EOpIndexIndirect:
1410 {
1411 // Structure or array or vector indirection.
1412 // Will use native SPIR-V access-chain for struct and array indirection;
1413 // matrices are arrays of vectors, so will also work for a matrix.
1414 // Will use the access chain's 'component' for variable index into a vector.
1415
1416 // This adapter is building access chains left to right.
1417 // Set up the access chain to the left.
1418 node->getLeft()->traverse(this);
1419
1420 // save it so that computing the right side doesn't trash it
1421 spv::Builder::AccessChain partial = builder.getAccessChain();
1422
1423 // compute the next index in the chain
1424 builder.clearAccessChain();
1425 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001426 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001427
John Kessenich5611c6d2018-04-05 11:25:02 -06001428 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1429
John Kessenich140f3df2015-06-26 16:58:36 -06001430 // restore the saved access chain
1431 builder.setAccessChain(partial);
1432
1433 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001434 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001435 else
John Kessenichfa668da2015-09-13 14:46:30 -06001436 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001437 }
1438 return false;
1439 case glslang::EOpVectorSwizzle:
1440 {
1441 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001442 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001443 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001444 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001445 }
1446 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001447 case glslang::EOpMatrixSwizzle:
1448 logger->missingFunctionality("matrix swizzle");
1449 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001450 case glslang::EOpLogicalOr:
1451 case glslang::EOpLogicalAnd:
1452 {
1453
1454 // These may require short circuiting, but can sometimes be done as straight
1455 // binary operations. The right operand must be short circuited if it has
1456 // side effects, and should probably be if it is complex.
1457 if (isTrivial(node->getRight()->getAsTyped()))
1458 break; // handle below as a normal binary operation
1459 // otherwise, we need to do dynamic short circuiting on the right operand
1460 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1461 builder.clearAccessChain();
1462 builder.setAccessChainRValue(result);
1463 }
1464 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001465 default:
1466 break;
1467 }
1468
1469 // Assume generic binary op...
1470
John Kessenich32cfd492016-02-02 12:37:46 -07001471 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001472 builder.clearAccessChain();
1473 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001474 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001475
John Kessenich32cfd492016-02-02 12:37:46 -07001476 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001477 builder.clearAccessChain();
1478 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001479 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001480
John Kessenich32cfd492016-02-02 12:37:46 -07001481 // get result
John Kessenichead86222018-03-28 18:01:20 -06001482 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001483 TranslateNoContractionDecoration(node->getType().getQualifier()),
1484 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001485 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001486 convertGlslangToSpvType(node->getType()), left, right,
1487 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001488
John Kessenich50e57562015-12-21 21:21:11 -07001489 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001490 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001491 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001492 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001493 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001494 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001495 return false;
1496 }
John Kessenich140f3df2015-06-26 16:58:36 -06001497}
1498
1499bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1500{
John Kesseniche485c7a2017-05-31 18:50:53 -06001501 builder.setLine(node->getLoc().line);
1502
qining40887662016-04-03 22:20:42 -04001503 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1504 if (node->getType().getQualifier().isSpecConstant())
1505 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1506
John Kessenichfc51d282015-08-19 13:34:18 -06001507 spv::Id result = spv::NoResult;
1508
1509 // try texturing first
1510 result = createImageTextureFunctionCall(node);
1511 if (result != spv::NoResult) {
1512 builder.clearAccessChain();
1513 builder.setAccessChainRValue(result);
1514
1515 return false; // done with this node
1516 }
1517
1518 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001519
1520 if (node->getOp() == glslang::EOpArrayLength) {
1521 // Quite special; won't want to evaluate the operand.
1522
John Kessenich5611c6d2018-04-05 11:25:02 -06001523 // Currently, the front-end does not allow .length() on an array until it is sized,
1524 // except for the last block membeor of an SSBO.
1525 // TODO: If this changes, link-time sized arrays might show up here, and need their
1526 // size extracted.
1527
John Kessenichc9a80832015-09-12 12:17:44 -06001528 // Normal .length() would have been constant folded by the front-end.
1529 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001530 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001531
John Kessenichc9a80832015-09-12 12:17:44 -06001532 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1533 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001534 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1535 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001536
1537 builder.clearAccessChain();
1538 builder.setAccessChainRValue(length);
1539
1540 return false;
1541 }
1542
John Kessenichfc51d282015-08-19 13:34:18 -06001543 // Start by evaluating the operand
1544
John Kessenich8c8505c2016-07-26 12:50:38 -06001545 // Does it need a swizzle inversion? If so, evaluation is inverted;
1546 // operate first on the swizzle base, then apply the swizzle.
1547 spv::Id invertedType = spv::NoType;
1548 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1549 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1550 invertedType = getInvertedSwizzleType(*node->getOperand());
1551
John Kessenich140f3df2015-06-26 16:58:36 -06001552 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001553 if (invertedType != spv::NoType)
1554 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1555 else
1556 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001557
Rex Xufc618912015-09-09 16:42:49 +08001558 spv::Id operand = spv::NoResult;
1559
1560 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1561 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001562 node->getOp() == glslang::EOpAtomicCounter ||
1563 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001564 operand = builder.accessChainGetLValue(); // Special case l-value operands
1565 else
John Kessenich32cfd492016-02-02 12:37:46 -07001566 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001567
John Kessenichead86222018-03-28 18:01:20 -06001568 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001569 TranslateNoContractionDecoration(node->getType().getQualifier()),
1570 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001571
1572 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001573 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001574 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001575
1576 // if not, then possibly an operation
1577 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001578 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001579
1580 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001581 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001582 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001583 builder.addDecoration(result, decorations.nonUniform);
1584 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001585
John Kessenich140f3df2015-06-26 16:58:36 -06001586 builder.clearAccessChain();
1587 builder.setAccessChainRValue(result);
1588
1589 return false; // done with this node
1590 }
1591
1592 // it must be a special case, check...
1593 switch (node->getOp()) {
1594 case glslang::EOpPostIncrement:
1595 case glslang::EOpPostDecrement:
1596 case glslang::EOpPreIncrement:
1597 case glslang::EOpPreDecrement:
1598 {
1599 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001600 spv::Id one = 0;
1601 if (node->getBasicType() == glslang::EbtFloat)
1602 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001603 else if (node->getBasicType() == glslang::EbtDouble)
1604 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001605 else if (node->getBasicType() == glslang::EbtFloat16)
1606 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001607 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1608 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001609 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1610 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001611 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1612 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001613 else
1614 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001615 glslang::TOperator op;
1616 if (node->getOp() == glslang::EOpPreIncrement ||
1617 node->getOp() == glslang::EOpPostIncrement)
1618 op = glslang::EOpAdd;
1619 else
1620 op = glslang::EOpSub;
1621
John Kessenichead86222018-03-28 18:01:20 -06001622 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001623 convertGlslangToSpvType(node->getType()), operand, one,
1624 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001625 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001626
1627 // The result of operation is always stored, but conditionally the
1628 // consumed result. The consumed result is always an r-value.
1629 builder.accessChainStore(result);
1630 builder.clearAccessChain();
1631 if (node->getOp() == glslang::EOpPreIncrement ||
1632 node->getOp() == glslang::EOpPreDecrement)
1633 builder.setAccessChainRValue(result);
1634 else
1635 builder.setAccessChainRValue(operand);
1636 }
1637
1638 return false;
1639
1640 case glslang::EOpEmitStreamVertex:
1641 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1642 return false;
1643 case glslang::EOpEndStreamPrimitive:
1644 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1645 return false;
1646
1647 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001648 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001649 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001650 }
John Kessenich140f3df2015-06-26 16:58:36 -06001651}
1652
1653bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1654{
qining27e04a02016-04-14 16:40:20 -04001655 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1656 if (node->getType().getQualifier().isSpecConstant())
1657 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1658
John Kessenichfc51d282015-08-19 13:34:18 -06001659 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001660 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1661 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001662
1663 // try texturing
1664 result = createImageTextureFunctionCall(node);
1665 if (result != spv::NoResult) {
1666 builder.clearAccessChain();
1667 builder.setAccessChainRValue(result);
1668
1669 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001670#ifdef AMD_EXTENSIONS
1671 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1672#else
John Kessenich56bab042015-09-16 10:54:31 -06001673 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001674#endif
Rex Xufc618912015-09-09 16:42:49 +08001675 // "imageStore" is a special case, which has no result
1676 return false;
1677 }
John Kessenichfc51d282015-08-19 13:34:18 -06001678
John Kessenich140f3df2015-06-26 16:58:36 -06001679 glslang::TOperator binOp = glslang::EOpNull;
1680 bool reduceComparison = true;
1681 bool isMatrix = false;
1682 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001683 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001684
1685 assert(node->getOp());
1686
John Kessenichf6640762016-08-01 19:44:00 -06001687 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001688
1689 switch (node->getOp()) {
1690 case glslang::EOpSequence:
1691 {
1692 if (preVisit)
1693 ++sequenceDepth;
1694 else
1695 --sequenceDepth;
1696
1697 if (sequenceDepth == 1) {
1698 // If this is the parent node of all the functions, we want to see them
1699 // early, so all call points have actual SPIR-V functions to reference.
1700 // In all cases, still let the traverser visit the children for us.
1701 makeFunctions(node->getAsAggregate()->getSequence());
1702
John Kessenich6fccb3c2016-09-19 16:01:41 -06001703 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001704 // anything else gets there, so visit out of order, doing them all now.
1705 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1706
John Kessenich6a60c2f2016-12-08 21:01:59 -07001707 // 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 -06001708 // so do them manually.
1709 visitFunctions(node->getAsAggregate()->getSequence());
1710
1711 return false;
1712 }
1713
1714 return true;
1715 }
1716 case glslang::EOpLinkerObjects:
1717 {
1718 if (visit == glslang::EvPreVisit)
1719 linkageOnly = true;
1720 else
1721 linkageOnly = false;
1722
1723 return true;
1724 }
1725 case glslang::EOpComma:
1726 {
1727 // processing from left to right naturally leaves the right-most
1728 // lying around in the access chain
1729 glslang::TIntermSequence& glslangOperands = node->getSequence();
1730 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1731 glslangOperands[i]->traverse(this);
1732
1733 return false;
1734 }
1735 case glslang::EOpFunction:
1736 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001737 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001738 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001739 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001740 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001741 } else {
1742 handleFunctionEntry(node);
1743 }
1744 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001745 if (inEntryPoint)
1746 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001747 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001748 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001749 }
1750
1751 return true;
1752 case glslang::EOpParameters:
1753 // Parameters will have been consumed by EOpFunction processing, but not
1754 // the body, so we still visited the function node's children, making this
1755 // child redundant.
1756 return false;
1757 case glslang::EOpFunctionCall:
1758 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001759 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001760 if (node->isUserDefined())
1761 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001762 // 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 -07001763 if (result) {
1764 builder.clearAccessChain();
1765 builder.setAccessChainRValue(result);
1766 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001767 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001768
1769 return false;
1770 }
1771 case glslang::EOpConstructMat2x2:
1772 case glslang::EOpConstructMat2x3:
1773 case glslang::EOpConstructMat2x4:
1774 case glslang::EOpConstructMat3x2:
1775 case glslang::EOpConstructMat3x3:
1776 case glslang::EOpConstructMat3x4:
1777 case glslang::EOpConstructMat4x2:
1778 case glslang::EOpConstructMat4x3:
1779 case glslang::EOpConstructMat4x4:
1780 case glslang::EOpConstructDMat2x2:
1781 case glslang::EOpConstructDMat2x3:
1782 case glslang::EOpConstructDMat2x4:
1783 case glslang::EOpConstructDMat3x2:
1784 case glslang::EOpConstructDMat3x3:
1785 case glslang::EOpConstructDMat3x4:
1786 case glslang::EOpConstructDMat4x2:
1787 case glslang::EOpConstructDMat4x3:
1788 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001789 case glslang::EOpConstructIMat2x2:
1790 case glslang::EOpConstructIMat2x3:
1791 case glslang::EOpConstructIMat2x4:
1792 case glslang::EOpConstructIMat3x2:
1793 case glslang::EOpConstructIMat3x3:
1794 case glslang::EOpConstructIMat3x4:
1795 case glslang::EOpConstructIMat4x2:
1796 case glslang::EOpConstructIMat4x3:
1797 case glslang::EOpConstructIMat4x4:
1798 case glslang::EOpConstructUMat2x2:
1799 case glslang::EOpConstructUMat2x3:
1800 case glslang::EOpConstructUMat2x4:
1801 case glslang::EOpConstructUMat3x2:
1802 case glslang::EOpConstructUMat3x3:
1803 case glslang::EOpConstructUMat3x4:
1804 case glslang::EOpConstructUMat4x2:
1805 case glslang::EOpConstructUMat4x3:
1806 case glslang::EOpConstructUMat4x4:
1807 case glslang::EOpConstructBMat2x2:
1808 case glslang::EOpConstructBMat2x3:
1809 case glslang::EOpConstructBMat2x4:
1810 case glslang::EOpConstructBMat3x2:
1811 case glslang::EOpConstructBMat3x3:
1812 case glslang::EOpConstructBMat3x4:
1813 case glslang::EOpConstructBMat4x2:
1814 case glslang::EOpConstructBMat4x3:
1815 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001816 case glslang::EOpConstructF16Mat2x2:
1817 case glslang::EOpConstructF16Mat2x3:
1818 case glslang::EOpConstructF16Mat2x4:
1819 case glslang::EOpConstructF16Mat3x2:
1820 case glslang::EOpConstructF16Mat3x3:
1821 case glslang::EOpConstructF16Mat3x4:
1822 case glslang::EOpConstructF16Mat4x2:
1823 case glslang::EOpConstructF16Mat4x3:
1824 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06001825 isMatrix = true;
1826 // fall through
1827 case glslang::EOpConstructFloat:
1828 case glslang::EOpConstructVec2:
1829 case glslang::EOpConstructVec3:
1830 case glslang::EOpConstructVec4:
1831 case glslang::EOpConstructDouble:
1832 case glslang::EOpConstructDVec2:
1833 case glslang::EOpConstructDVec3:
1834 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001835 case glslang::EOpConstructFloat16:
1836 case glslang::EOpConstructF16Vec2:
1837 case glslang::EOpConstructF16Vec3:
1838 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001839 case glslang::EOpConstructBool:
1840 case glslang::EOpConstructBVec2:
1841 case glslang::EOpConstructBVec3:
1842 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07001843 case glslang::EOpConstructInt8:
1844 case glslang::EOpConstructI8Vec2:
1845 case glslang::EOpConstructI8Vec3:
1846 case glslang::EOpConstructI8Vec4:
1847 case glslang::EOpConstructUint8:
1848 case glslang::EOpConstructU8Vec2:
1849 case glslang::EOpConstructU8Vec3:
1850 case glslang::EOpConstructU8Vec4:
1851 case glslang::EOpConstructInt16:
1852 case glslang::EOpConstructI16Vec2:
1853 case glslang::EOpConstructI16Vec3:
1854 case glslang::EOpConstructI16Vec4:
1855 case glslang::EOpConstructUint16:
1856 case glslang::EOpConstructU16Vec2:
1857 case glslang::EOpConstructU16Vec3:
1858 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001859 case glslang::EOpConstructInt:
1860 case glslang::EOpConstructIVec2:
1861 case glslang::EOpConstructIVec3:
1862 case glslang::EOpConstructIVec4:
1863 case glslang::EOpConstructUint:
1864 case glslang::EOpConstructUVec2:
1865 case glslang::EOpConstructUVec3:
1866 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001867 case glslang::EOpConstructInt64:
1868 case glslang::EOpConstructI64Vec2:
1869 case glslang::EOpConstructI64Vec3:
1870 case glslang::EOpConstructI64Vec4:
1871 case glslang::EOpConstructUint64:
1872 case glslang::EOpConstructU64Vec2:
1873 case glslang::EOpConstructU64Vec3:
1874 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001875 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001876 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001877 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001878 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001879 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001880 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001881 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001882 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001883 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001884 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001885 std::vector<spv::Id> constituents;
1886 for (int c = 0; c < (int)arguments.size(); ++c)
1887 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001888 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001889 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001890 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001891 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001892 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001893
1894 builder.clearAccessChain();
1895 builder.setAccessChainRValue(constructed);
1896
1897 return false;
1898 }
1899
1900 // These six are component-wise compares with component-wise results.
1901 // Forward on to createBinaryOperation(), requesting a vector result.
1902 case glslang::EOpLessThan:
1903 case glslang::EOpGreaterThan:
1904 case glslang::EOpLessThanEqual:
1905 case glslang::EOpGreaterThanEqual:
1906 case glslang::EOpVectorEqual:
1907 case glslang::EOpVectorNotEqual:
1908 {
1909 // Map the operation to a binary
1910 binOp = node->getOp();
1911 reduceComparison = false;
1912 switch (node->getOp()) {
1913 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1914 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1915 default: binOp = node->getOp(); break;
1916 }
1917
1918 break;
1919 }
1920 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001921 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001922 binOp = glslang::EOpMul;
1923 break;
1924 case glslang::EOpOuterProduct:
1925 // two vectors multiplied to make a matrix
1926 binOp = glslang::EOpOuterProduct;
1927 break;
1928 case glslang::EOpDot:
1929 {
qining25262b32016-05-06 17:25:16 -04001930 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001931 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001932 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001933 binOp = glslang::EOpMul;
1934 break;
1935 }
1936 case glslang::EOpMod:
1937 // when an aggregate, this is the floating-point mod built-in function,
1938 // which can be emitted by the one in createBinaryOperation()
1939 binOp = glslang::EOpMod;
1940 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001941 case glslang::EOpEmitVertex:
1942 case glslang::EOpEndPrimitive:
1943 case glslang::EOpBarrier:
1944 case glslang::EOpMemoryBarrier:
1945 case glslang::EOpMemoryBarrierAtomicCounter:
1946 case glslang::EOpMemoryBarrierBuffer:
1947 case glslang::EOpMemoryBarrierImage:
1948 case glslang::EOpMemoryBarrierShared:
1949 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07001950 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001951 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07001952 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001953 case glslang::EOpWorkgroupMemoryBarrier:
1954 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07001955 case glslang::EOpSubgroupBarrier:
1956 case glslang::EOpSubgroupMemoryBarrier:
1957 case glslang::EOpSubgroupMemoryBarrierBuffer:
1958 case glslang::EOpSubgroupMemoryBarrierImage:
1959 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06001960 noReturnValue = true;
1961 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1962 break;
1963
John Kessenich426394d2015-07-23 10:22:48 -06001964 case glslang::EOpAtomicAdd:
1965 case glslang::EOpAtomicMin:
1966 case glslang::EOpAtomicMax:
1967 case glslang::EOpAtomicAnd:
1968 case glslang::EOpAtomicOr:
1969 case glslang::EOpAtomicXor:
1970 case glslang::EOpAtomicExchange:
1971 case glslang::EOpAtomicCompSwap:
1972 atomic = true;
1973 break;
1974
John Kessenich0d0c6d32017-07-23 16:08:26 -06001975 case glslang::EOpAtomicCounterAdd:
1976 case glslang::EOpAtomicCounterSubtract:
1977 case glslang::EOpAtomicCounterMin:
1978 case glslang::EOpAtomicCounterMax:
1979 case glslang::EOpAtomicCounterAnd:
1980 case glslang::EOpAtomicCounterOr:
1981 case glslang::EOpAtomicCounterXor:
1982 case glslang::EOpAtomicCounterExchange:
1983 case glslang::EOpAtomicCounterCompSwap:
1984 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1985 builder.addCapability(spv::CapabilityAtomicStorageOps);
1986 atomic = true;
1987 break;
1988
John Kessenich140f3df2015-06-26 16:58:36 -06001989 default:
1990 break;
1991 }
1992
1993 //
1994 // See if it maps to a regular operation.
1995 //
John Kessenich140f3df2015-06-26 16:58:36 -06001996 if (binOp != glslang::EOpNull) {
1997 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1998 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1999 assert(left && right);
2000
2001 builder.clearAccessChain();
2002 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002003 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002004
2005 builder.clearAccessChain();
2006 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002007 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002008
John Kesseniche485c7a2017-05-31 18:50:53 -06002009 builder.setLine(node->getLoc().line);
John Kessenichead86222018-03-28 18:01:20 -06002010 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002011 TranslateNoContractionDecoration(node->getType().getQualifier()),
2012 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002013 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002014 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002015 left->getType().getBasicType(), reduceComparison);
2016
2017 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002018 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002019 builder.clearAccessChain();
2020 builder.setAccessChainRValue(result);
2021
2022 return false;
2023 }
2024
John Kessenich426394d2015-07-23 10:22:48 -06002025 //
2026 // Create the list of operands.
2027 //
John Kessenich140f3df2015-06-26 16:58:36 -06002028 glslang::TIntermSequence& glslangOperands = node->getSequence();
2029 std::vector<spv::Id> operands;
2030 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002031 // special case l-value operands; there are just a few
2032 bool lvalue = false;
2033 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002034 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002035 case glslang::EOpModf:
2036 if (arg == 1)
2037 lvalue = true;
2038 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002039 case glslang::EOpInterpolateAtSample:
2040 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002041#ifdef AMD_EXTENSIONS
2042 case glslang::EOpInterpolateAtVertex:
2043#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002044 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002045 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002046
2047 // Does it need a swizzle inversion? If so, evaluation is inverted;
2048 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002049 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002050 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2051 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2052 }
Rex Xu7a26c172015-12-08 17:12:09 +08002053 break;
Rex Xud4782c12015-09-06 16:30:11 +08002054 case glslang::EOpAtomicAdd:
2055 case glslang::EOpAtomicMin:
2056 case glslang::EOpAtomicMax:
2057 case glslang::EOpAtomicAnd:
2058 case glslang::EOpAtomicOr:
2059 case glslang::EOpAtomicXor:
2060 case glslang::EOpAtomicExchange:
2061 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002062 case glslang::EOpAtomicCounterAdd:
2063 case glslang::EOpAtomicCounterSubtract:
2064 case glslang::EOpAtomicCounterMin:
2065 case glslang::EOpAtomicCounterMax:
2066 case glslang::EOpAtomicCounterAnd:
2067 case glslang::EOpAtomicCounterOr:
2068 case glslang::EOpAtomicCounterXor:
2069 case glslang::EOpAtomicCounterExchange:
2070 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002071 if (arg == 0)
2072 lvalue = true;
2073 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002074 case glslang::EOpAddCarry:
2075 case glslang::EOpSubBorrow:
2076 if (arg == 2)
2077 lvalue = true;
2078 break;
2079 case glslang::EOpUMulExtended:
2080 case glslang::EOpIMulExtended:
2081 if (arg >= 2)
2082 lvalue = true;
2083 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002084 default:
2085 break;
2086 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002087 builder.clearAccessChain();
2088 if (invertedType != spv::NoType && arg == 0)
2089 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2090 else
2091 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002092 if (lvalue)
2093 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002094 else {
2095 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07002096 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002097 }
John Kessenich140f3df2015-06-26 16:58:36 -06002098 }
John Kessenich426394d2015-07-23 10:22:48 -06002099
John Kesseniche485c7a2017-05-31 18:50:53 -06002100 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06002101 if (atomic) {
2102 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002103 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002104 } else {
2105 // Pass through to generic operations.
2106 switch (glslangOperands.size()) {
2107 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002108 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002109 break;
2110 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002111 {
2112 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002113 TranslateNoContractionDecoration(node->getType().getQualifier()),
2114 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002115 result = createUnaryOperation(
2116 node->getOp(), decorations,
2117 resultType(), operands.front(),
2118 glslangOperands[0]->getAsTyped()->getBasicType());
2119 }
John Kessenich426394d2015-07-23 10:22:48 -06002120 break;
2121 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002122 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002123 break;
2124 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002125 if (invertedType)
2126 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002127 }
2128
2129 if (noReturnValue)
2130 return false;
2131
2132 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002133 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002134 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002135 } else {
2136 builder.clearAccessChain();
2137 builder.setAccessChainRValue(result);
2138 return false;
2139 }
2140}
2141
John Kessenich433e9ff2017-01-26 20:31:11 -07002142// This path handles both if-then-else and ?:
2143// The if-then-else has a node type of void, while
2144// ?: has either a void or a non-void node type
2145//
2146// Leaving the result, when not void:
2147// GLSL only has r-values as the result of a :?, but
2148// if we have an l-value, that can be more efficient if it will
2149// become the base of a complex r-value expression, because the
2150// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002151bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2152{
John Kessenich4bee5312018-02-20 21:29:05 -07002153 // See if it simple and safe, or required, to execute both sides.
2154 // Crucially, side effects must be either semantically required or avoided,
2155 // and there are performance trade-offs.
2156 // Return true if required or a good idea (and safe) to execute both sides,
2157 // false otherwise.
2158 const auto bothSidesPolicy = [&]() -> bool {
2159 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002160 if (node->getTrueBlock() == nullptr ||
2161 node->getFalseBlock() == nullptr)
2162 return false;
2163
John Kessenich4bee5312018-02-20 21:29:05 -07002164 // required? (unless we write additional code to look for side effects
2165 // and make performance trade-offs if none are present)
2166 if (!node->getShortCircuit())
2167 return true;
2168
2169 // if not required to execute both, decide based on performance/practicality...
2170
2171 // see if OpSelect can handle it
2172 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2173 node->getBasicType() == glslang::EbtVoid)
2174 return false;
2175
John Kessenich433e9ff2017-01-26 20:31:11 -07002176 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2177 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2178
2179 // return true if a single operand to ? : is okay for OpSelect
2180 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002181 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002182 };
2183
2184 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2185 operandOkay(node->getFalseBlock()->getAsTyped());
2186 };
2187
John Kessenich4bee5312018-02-20 21:29:05 -07002188 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2189 // emit the condition before doing anything with selection
2190 node->getCondition()->traverse(this);
2191 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2192
2193 // Find a way of executing both sides and selecting the right result.
2194 const auto executeBothSides = [&]() -> void {
2195 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002196 node->getTrueBlock()->traverse(this);
2197 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2198 node->getFalseBlock()->traverse(this);
2199 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2200
John Kesseniche485c7a2017-05-31 18:50:53 -06002201 builder.setLine(node->getLoc().line);
2202
John Kessenich4bee5312018-02-20 21:29:05 -07002203 // done if void
2204 if (node->getBasicType() == glslang::EbtVoid)
2205 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002206
John Kessenich4bee5312018-02-20 21:29:05 -07002207 // emit code to select between trueValue and falseValue
2208
2209 // see if OpSelect can handle it
2210 if (node->getType().isScalar() || node->getType().isVector()) {
2211 // Emit OpSelect for this selection.
2212
2213 // smear condition to vector, if necessary (AST is always scalar)
2214 if (builder.isVector(trueValue))
2215 condition = builder.smearScalar(spv::NoPrecision, condition,
2216 builder.makeVectorType(builder.makeBoolType(),
2217 builder.getNumComponents(trueValue)));
2218
2219 // OpSelect
2220 result = builder.createTriOp(spv::OpSelect,
2221 convertGlslangToSpvType(node->getType()), condition,
2222 trueValue, falseValue);
2223
2224 builder.clearAccessChain();
2225 builder.setAccessChainRValue(result);
2226 } else {
2227 // We need control flow to select the result.
2228 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2229 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2230
2231 // Selection control:
2232 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2233
2234 // make an "if" based on the value created by the condition
2235 spv::Builder::If ifBuilder(condition, control, builder);
2236
2237 // emit the "then" statement
2238 builder.createStore(trueValue, result);
2239 ifBuilder.makeBeginElse();
2240 // emit the "else" statement
2241 builder.createStore(falseValue, result);
2242
2243 // finish off the control flow
2244 ifBuilder.makeEndIf();
2245
2246 builder.clearAccessChain();
2247 builder.setAccessChainLValue(result);
2248 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002249 };
2250
John Kessenich4bee5312018-02-20 21:29:05 -07002251 // Execute the one side needed, as per the condition
2252 const auto executeOneSide = [&]() {
2253 // Always emit control flow.
2254 if (node->getBasicType() != glslang::EbtVoid)
2255 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002256
John Kessenich4bee5312018-02-20 21:29:05 -07002257 // Selection control:
2258 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2259
2260 // make an "if" based on the value created by the condition
2261 spv::Builder::If ifBuilder(condition, control, builder);
2262
2263 // emit the "then" statement
2264 if (node->getTrueBlock() != nullptr) {
2265 node->getTrueBlock()->traverse(this);
2266 if (result != spv::NoResult)
2267 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2268 }
2269
2270 if (node->getFalseBlock() != nullptr) {
2271 ifBuilder.makeBeginElse();
2272 // emit the "else" statement
2273 node->getFalseBlock()->traverse(this);
2274 if (result != spv::NoResult)
2275 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2276 }
2277
2278 // finish off the control flow
2279 ifBuilder.makeEndIf();
2280
2281 if (result != spv::NoResult) {
2282 builder.clearAccessChain();
2283 builder.setAccessChainLValue(result);
2284 }
2285 };
2286
2287 // Try for OpSelect (or a requirement to execute both sides)
2288 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002289 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2290 if (node->getType().getQualifier().isSpecConstant())
2291 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002292 executeBothSides();
2293 } else
2294 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002295
2296 return false;
2297}
2298
2299bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2300{
2301 // emit and get the condition before doing anything with switch
2302 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002303 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002304
Rex Xu57e65922017-07-04 23:23:40 +08002305 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002306 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002307
John Kessenich140f3df2015-06-26 16:58:36 -06002308 // browse the children to sort out code segments
2309 int defaultSegment = -1;
2310 std::vector<TIntermNode*> codeSegments;
2311 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2312 std::vector<int> caseValues;
2313 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2314 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2315 TIntermNode* child = *c;
2316 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002317 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002318 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002319 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002320 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2321 } else
2322 codeSegments.push_back(child);
2323 }
2324
qining25262b32016-05-06 17:25:16 -04002325 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002326 // statements between the last case and the end of the switch statement
2327 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2328 (int)codeSegments.size() == defaultSegment)
2329 codeSegments.push_back(nullptr);
2330
2331 // make the switch statement
2332 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002333 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002334
2335 // emit all the code in the segments
2336 breakForLoop.push(false);
2337 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2338 builder.nextSwitchSegment(segmentBlocks, s);
2339 if (codeSegments[s])
2340 codeSegments[s]->traverse(this);
2341 else
2342 builder.addSwitchBreak();
2343 }
2344 breakForLoop.pop();
2345
2346 builder.endSwitch(segmentBlocks);
2347
2348 return false;
2349}
2350
2351void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2352{
2353 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002354 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002355
2356 builder.clearAccessChain();
2357 builder.setAccessChainRValue(constant);
2358}
2359
2360bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2361{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002362 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002363 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002364
2365 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002366 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2367 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002368
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002369 // Spec requires back edges to target header blocks, and every header block
2370 // must dominate its merge block. Make a header block first to ensure these
2371 // conditions are met. By definition, it will contain OpLoopMerge, followed
2372 // by a block-ending branch. But we don't want to put any other body/test
2373 // instructions in it, since the body/test may have arbitrary instructions,
2374 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002375 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002376 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002377 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002378 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002379 spv::Block& test = builder.makeNewBlock();
2380 builder.createBranch(&test);
2381
2382 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002383 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002384 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002385 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2386
2387 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002388 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002389 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002390 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002391 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002392 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002393
2394 builder.setBuildPoint(&blocks.continue_target);
2395 if (node->getTerminal())
2396 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002397 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002398 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002399 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002400 builder.createBranch(&blocks.body);
2401
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002402 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002403 builder.setBuildPoint(&blocks.body);
2404 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002405 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002406 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002407 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002408
2409 builder.setBuildPoint(&blocks.continue_target);
2410 if (node->getTerminal())
2411 node->getTerminal()->traverse(this);
2412 if (node->getTest()) {
2413 node->getTest()->traverse(this);
2414 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002415 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002416 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002417 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002418 // TODO: unless there was a break/return/discard instruction
2419 // somewhere in the body, this is an infinite loop, so we should
2420 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002421 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002422 }
John Kessenich140f3df2015-06-26 16:58:36 -06002423 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002424 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002425 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002426 return false;
2427}
2428
2429bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2430{
2431 if (node->getExpression())
2432 node->getExpression()->traverse(this);
2433
John Kesseniche485c7a2017-05-31 18:50:53 -06002434 builder.setLine(node->getLoc().line);
2435
John Kessenich140f3df2015-06-26 16:58:36 -06002436 switch (node->getFlowOp()) {
2437 case glslang::EOpKill:
2438 builder.makeDiscard();
2439 break;
2440 case glslang::EOpBreak:
2441 if (breakForLoop.top())
2442 builder.createLoopExit();
2443 else
2444 builder.addSwitchBreak();
2445 break;
2446 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002447 builder.createLoopContinue();
2448 break;
2449 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002450 if (node->getExpression()) {
2451 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2452 spv::Id returnId = accessChainLoad(glslangReturnType);
2453 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2454 builder.clearAccessChain();
2455 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2456 builder.setAccessChainLValue(copyId);
2457 multiTypeStore(glslangReturnType, returnId);
2458 returnId = builder.createLoad(copyId);
2459 }
2460 builder.makeReturn(false, returnId);
2461 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002462 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002463
2464 builder.clearAccessChain();
2465 break;
2466
2467 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002468 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002469 break;
2470 }
2471
2472 return false;
2473}
2474
2475spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2476{
qining25262b32016-05-06 17:25:16 -04002477 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002478 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002479 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002480 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002481 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002482 }
2483
2484 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002485 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002486 spv::Id spvType = convertGlslangToSpvType(node->getType());
2487
Rex Xucabbb782017-03-24 13:41:14 +08002488 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2489 node->getType().containsBasicType(glslang::EbtInt16) ||
2490 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002491 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002492 switch (storageClass) {
2493 case spv::StorageClassInput:
2494 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002495 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002496 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002497 break;
2498 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07002499 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002500 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06002501 break;
2502 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07002503 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002504 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2505 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06002506 else
2507 builder.addCapability(spv::CapabilityStorageUniform16);
2508 break;
2509 case spv::StorageClassStorageBuffer:
2510 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
2511 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2512 break;
2513 default:
2514 break;
Rex Xuf89ad982017-04-07 23:22:33 +08002515 }
2516 }
Rex Xuf89ad982017-04-07 23:22:33 +08002517
John Kessenich312dcfb2018-07-03 13:19:51 -06002518 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
2519 node->getType().containsBasicType(glslang::EbtUint8);
2520 if (contains8BitType) {
2521 if (storageClass == spv::StorageClassPushConstant) {
2522 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2523 builder.addCapability(spv::CapabilityStoragePushConstant8);
2524 } else if (storageClass == spv::StorageClassUniform) {
2525 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2526 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
2527 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2528 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
2529 }
2530 }
2531
John Kessenich140f3df2015-06-26 16:58:36 -06002532 const char* name = node->getName().c_str();
2533 if (glslang::IsAnonymous(name))
2534 name = "";
2535
2536 return builder.createVariable(storageClass, spvType, name);
2537}
2538
2539// Return type Id of the sampled type.
2540spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2541{
2542 switch (sampler.type) {
2543 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08002544#ifdef AMD_EXTENSIONS
2545 case glslang::EbtFloat16:
2546 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
2547 builder.addCapability(spv::CapabilityFloat16ImageAMD);
2548 return builder.makeFloatType(16);
2549#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002550 case glslang::EbtInt: return builder.makeIntType(32);
2551 case glslang::EbtUint: return builder.makeUintType(32);
2552 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002553 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002554 return builder.makeFloatType(32);
2555 }
2556}
2557
John Kessenich8c8505c2016-07-26 12:50:38 -06002558// If node is a swizzle operation, return the type that should be used if
2559// the swizzle base is first consumed by another operation, before the swizzle
2560// is applied.
2561spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2562{
John Kessenichecba76f2017-01-06 00:34:48 -07002563 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002564 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2565 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2566 else
2567 return spv::NoType;
2568}
2569
2570// When inverting a swizzle with a parent op, this function
2571// will apply the swizzle operation to a completed parent operation.
2572spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2573{
2574 std::vector<unsigned> swizzle;
2575 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2576 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2577}
2578
John Kessenich8c8505c2016-07-26 12:50:38 -06002579// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2580void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2581{
2582 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2583 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2584 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2585}
2586
John Kessenich3ac051e2015-12-20 11:29:16 -07002587// Convert from a glslang type to an SPV type, by calling into a
2588// recursive version of this function. This establishes the inherited
2589// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002590spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2591{
John Kessenichead86222018-03-28 18:01:20 -06002592 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false);
John Kessenich31ed4832015-09-09 17:51:38 -06002593}
2594
2595// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002596// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002597// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06002598spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
2599 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier, bool lastBufferBlockMember)
John Kessenich31ed4832015-09-09 17:51:38 -06002600{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002601 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002602
2603 switch (type.getBasicType()) {
2604 case glslang::EbtVoid:
2605 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002606 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002607 break;
2608 case glslang::EbtFloat:
2609 spvType = builder.makeFloatType(32);
2610 break;
2611 case glslang::EbtDouble:
2612 spvType = builder.makeFloatType(64);
2613 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002614 case glslang::EbtFloat16:
John Kessenich66011cb2018-03-06 16:12:04 -07002615 builder.addCapability(spv::CapabilityFloat16);
2616#if AMD_EXTENSIONS
2617 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2618 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
2619#endif
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002620 spvType = builder.makeFloatType(16);
2621 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002622 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002623 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2624 // a 32-bit int where non-0 means true.
2625 if (explicitLayout != glslang::ElpNone)
2626 spvType = builder.makeUintType(32);
2627 else
2628 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002629 break;
John Kessenich66011cb2018-03-06 16:12:04 -07002630 case glslang::EbtInt8:
2631 builder.addCapability(spv::CapabilityInt8);
2632 spvType = builder.makeIntType(8);
2633 break;
2634 case glslang::EbtUint8:
2635 builder.addCapability(spv::CapabilityInt8);
2636 spvType = builder.makeUintType(8);
2637 break;
2638 case glslang::EbtInt16:
2639 builder.addCapability(spv::CapabilityInt16);
2640#ifdef AMD_EXTENSIONS
2641 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2642 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2643#endif
2644 spvType = builder.makeIntType(16);
2645 break;
2646 case glslang::EbtUint16:
2647 builder.addCapability(spv::CapabilityInt16);
2648#ifdef AMD_EXTENSIONS
2649 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2650 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2651#endif
2652 spvType = builder.makeUintType(16);
2653 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002654 case glslang::EbtInt:
2655 spvType = builder.makeIntType(32);
2656 break;
2657 case glslang::EbtUint:
2658 spvType = builder.makeUintType(32);
2659 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002660 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002661 spvType = builder.makeIntType(64);
2662 break;
2663 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002664 spvType = builder.makeUintType(64);
2665 break;
John Kessenich426394d2015-07-23 10:22:48 -06002666 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002667 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002668 spvType = builder.makeUintType(32);
2669 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002670 case glslang::EbtSampler:
2671 {
2672 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002673 if (sampler.sampler) {
2674 // pure sampler
2675 spvType = builder.makeSamplerType();
2676 } else {
2677 // an image is present, make its type
2678 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2679 sampler.image ? 2 : 1, TranslateImageFormat(type));
2680 if (sampler.combined) {
2681 // already has both image and sampler, make the combined type
2682 spvType = builder.makeSampledImageType(spvType);
2683 }
John Kessenich55e7d112015-11-15 21:33:39 -07002684 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002685 }
John Kessenich140f3df2015-06-26 16:58:36 -06002686 break;
2687 case glslang::EbtStruct:
2688 case glslang::EbtBlock:
2689 {
2690 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002691 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002692
2693 // Try to share structs for different layouts, but not yet for other
2694 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002695 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002696 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002697 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002698 break;
2699
2700 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002701 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002702 memberRemapper[glslangMembers].resize(glslangMembers->size());
2703 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002704 }
2705 break;
2706 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002707 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002708 break;
2709 }
2710
2711 if (type.isMatrix())
2712 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2713 else {
2714 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2715 if (type.getVectorSize() > 1)
2716 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2717 }
2718
2719 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002720 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2721
John Kessenichc9a80832015-09-12 12:17:44 -06002722 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002723 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002724 // We need to decorate array strides for types needing explicit layout, except blocks.
2725 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002726 // Use a dummy glslang type for querying internal strides of
2727 // arrays of arrays, but using just a one-dimensional array.
2728 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06002729 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
2730 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07002731
2732 // Will compute the higher-order strides here, rather than making a whole
2733 // pile of types and doing repetitive recursion on their contents.
2734 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2735 }
John Kessenichf8842e52016-01-04 19:22:56 -07002736
2737 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002738 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002739 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002740 if (stride > 0)
2741 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002742 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002743 }
2744 } else {
2745 // single-dimensional array, and don't yet have stride
2746
John Kessenichf8842e52016-01-04 19:22:56 -07002747 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002748 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2749 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002750 }
John Kessenich31ed4832015-09-09 17:51:38 -06002751
John Kessenichead86222018-03-28 18:01:20 -06002752 // Do the outer dimension, which might not be known for a runtime-sized array.
2753 // (Unsized arrays that survive through linking will be runtime-sized arrays)
2754 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07002755 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06002756 else {
2757 if (!lastBufferBlockMember) {
2758 builder.addExtension("SPV_EXT_descriptor_indexing");
2759 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
2760 }
John Kessenichead86222018-03-28 18:01:20 -06002761 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06002762 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002763 if (stride > 0)
2764 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002765 }
2766
2767 return spvType;
2768}
2769
John Kessenich0e737842017-03-24 18:38:16 -06002770// TODO: this functionality should exist at a higher level, in creating the AST
2771//
2772// Identify interface members that don't have their required extension turned on.
2773//
2774bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2775{
2776 auto& extensions = glslangIntermediate->getRequestedExtensions();
2777
Rex Xubcf291a2017-03-29 23:01:36 +08002778 if (member.getFieldName() == "gl_ViewportMask" &&
2779 extensions.find("GL_NV_viewport_array2") == extensions.end())
2780 return true;
2781 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2782 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2783 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002784 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2785 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2786 return true;
2787 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2788 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2789 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002790 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2791 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2792 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002793
2794 return false;
2795};
2796
John Kessenich6090df02016-06-30 21:18:02 -06002797// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2798// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2799// Mutually recursive with convertGlslangToSpvType().
2800spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2801 const glslang::TTypeList* glslangMembers,
2802 glslang::TLayoutPacking explicitLayout,
2803 const glslang::TQualifier& qualifier)
2804{
2805 // Create a vector of struct types for SPIR-V to consume
2806 std::vector<spv::Id> spvMembers;
2807 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 -06002808 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2809 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2810 if (glslangMember.hiddenMember()) {
2811 ++memberDelta;
2812 if (type.getBasicType() == glslang::EbtBlock)
2813 memberRemapper[glslangMembers][i] = -1;
2814 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002815 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002816 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002817 if (filterMember(glslangMember))
2818 continue;
2819 }
John Kessenich6090df02016-06-30 21:18:02 -06002820 // modify just this child's view of the qualifier
2821 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2822 InheritQualifiers(memberQualifier, qualifier);
2823
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002824 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002825 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002826 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002827
2828 // recurse
John Kessenichead86222018-03-28 18:01:20 -06002829 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
2830 i == (int)glslangMembers->size() - 1;
2831 spvMembers.push_back(
2832 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember));
John Kessenich6090df02016-06-30 21:18:02 -06002833 }
2834 }
2835
2836 // Make the SPIR-V type
2837 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002838 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002839 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2840
2841 // Decorate it
2842 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2843
2844 return spvType;
2845}
2846
2847void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2848 const glslang::TTypeList* glslangMembers,
2849 glslang::TLayoutPacking explicitLayout,
2850 const glslang::TQualifier& qualifier,
2851 spv::Id spvType)
2852{
2853 // Name and decorate the non-hidden members
2854 int offset = -1;
2855 int locationOffset = 0; // for use within the members of this struct
2856 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2857 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2858 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002859 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002860 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002861 if (filterMember(glslangMember))
2862 continue;
2863 }
John Kessenich6090df02016-06-30 21:18:02 -06002864
2865 // modify just this child's view of the qualifier
2866 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2867 InheritQualifiers(memberQualifier, qualifier);
2868
2869 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07002870 if (member < 0)
2871 continue;
2872
2873 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2874 builder.addMemberDecoration(spvType, member,
2875 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2876 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2877 // Add interpolation and auxiliary storage decorations only to
2878 // top-level members of Input and Output storage classes
2879 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2880 type.getQualifier().storage == glslang::EvqVaryingOut) {
2881 if (type.getBasicType() == glslang::EbtBlock ||
2882 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
2883 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2884 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002885 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002886 }
2887 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002888
John Kessenich5d610ee2018-03-07 18:05:55 -07002889 if (type.getBasicType() == glslang::EbtBlock &&
2890 qualifier.storage == glslang::EvqBuffer) {
2891 // Add memory decorations only to top-level members of shader storage block
2892 std::vector<spv::Decoration> memory;
2893 TranslateMemoryDecoration(memberQualifier, memory);
2894 for (unsigned int i = 0; i < memory.size(); ++i)
2895 builder.addMemberDecoration(spvType, member, memory[i]);
2896 }
John Kessenich6090df02016-06-30 21:18:02 -06002897
John Kessenich5d610ee2018-03-07 18:05:55 -07002898 // Location assignment was already completed correctly by the front end,
2899 // just track whether a member needs to be decorated.
2900 // Ignore member locations if the container is an array, as that's
2901 // ill-specified and decisions have been made to not allow this.
2902 if (! type.isArray() && memberQualifier.hasLocation())
2903 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002904
John Kessenich5d610ee2018-03-07 18:05:55 -07002905 if (qualifier.hasLocation()) // track for upcoming inheritance
2906 locationOffset += glslangIntermediate->computeTypeLocationSize(
2907 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06002908
John Kessenich5d610ee2018-03-07 18:05:55 -07002909 // component, XFB, others
2910 if (glslangMember.getQualifier().hasComponent())
2911 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
2912 glslangMember.getQualifier().layoutComponent);
2913 if (glslangMember.getQualifier().hasXfbOffset())
2914 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
2915 glslangMember.getQualifier().layoutXfbOffset);
2916 else if (explicitLayout != glslang::ElpNone) {
2917 // figure out what to do with offset, which is accumulating
2918 int nextOffset;
2919 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2920 if (offset >= 0)
2921 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2922 offset = nextOffset;
2923 }
John Kessenich6090df02016-06-30 21:18:02 -06002924
John Kessenich5d610ee2018-03-07 18:05:55 -07002925 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2926 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
2927 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06002928
John Kessenich5d610ee2018-03-07 18:05:55 -07002929 // built-in variable decorations
2930 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
2931 if (builtIn != spv::BuiltInMax)
2932 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002933
John Kessenich5611c6d2018-04-05 11:25:02 -06002934 // nonuniform
2935 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
2936
John Kessenichead86222018-03-28 18:01:20 -06002937 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
2938 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
2939 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
2940 memberQualifier.semanticName);
2941 }
2942
chaoc771d89f2017-01-13 01:10:53 -08002943#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07002944 if (builtIn == spv::BuiltInLayer) {
2945 // SPV_NV_viewport_array2 extension
2946 if (glslangMember.getQualifier().layoutViewportRelative){
2947 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2948 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2949 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08002950 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002951 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2952 builder.addMemberDecoration(spvType, member,
2953 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
2954 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2955 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2956 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08002957 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002958 }
2959 if (glslangMember.getQualifier().layoutPassthrough) {
2960 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2961 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2962 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2963 }
chaoc771d89f2017-01-13 01:10:53 -08002964#endif
John Kessenich6090df02016-06-30 21:18:02 -06002965 }
2966
2967 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07002968 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2969 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002970 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2971 builder.addCapability(spv::CapabilityGeometryStreams);
2972 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2973 }
John Kessenich6090df02016-06-30 21:18:02 -06002974}
2975
John Kessenich6c292d32016-02-15 20:58:50 -07002976// Turn the expression forming the array size into an id.
2977// This is not quite trivial, because of specialization constants.
2978// Sometimes, a raw constant is turned into an Id, and sometimes
2979// a specialization constant expression is.
2980spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2981{
2982 // First, see if this is sized with a node, meaning a specialization constant:
2983 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2984 if (specNode != nullptr) {
2985 builder.clearAccessChain();
2986 specNode->traverse(this);
2987 return accessChainLoad(specNode->getAsTyped()->getType());
2988 }
qining25262b32016-05-06 17:25:16 -04002989
John Kessenich6c292d32016-02-15 20:58:50 -07002990 // Otherwise, need a compile-time (front end) size, get it:
2991 int size = arraySizes.getDimSize(dim);
2992 assert(size > 0);
2993 return builder.makeUintConstant(size);
2994}
2995
John Kessenich103bef92016-02-08 21:38:15 -07002996// Wrap the builder's accessChainLoad to:
2997// - localize handling of RelaxedPrecision
2998// - use the SPIR-V inferred type instead of another conversion of the glslang type
2999// (avoids unnecessary work and possible type punning for structures)
3000// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003001spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3002{
John Kessenich103bef92016-02-08 21:38:15 -07003003 spv::Id nominalTypeId = builder.accessChainGetInferredType();
John Kessenich5611c6d2018-04-05 11:25:02 -06003004 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
3005 TranslateNonUniformDecoration(type.getQualifier()), nominalTypeId);
John Kessenich103bef92016-02-08 21:38:15 -07003006
3007 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003008 if (type.getBasicType() == glslang::EbtBool) {
3009 if (builder.isScalarType(nominalTypeId)) {
3010 // Conversion for bool
3011 spv::Id boolType = builder.makeBoolType();
3012 if (nominalTypeId != boolType)
3013 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3014 } else if (builder.isVectorType(nominalTypeId)) {
3015 // Conversion for bvec
3016 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3017 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3018 if (nominalTypeId != bvecType)
3019 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3020 }
3021 }
John Kessenich103bef92016-02-08 21:38:15 -07003022
3023 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003024}
3025
Rex Xu27253232016-02-23 17:51:09 +08003026// Wrap the builder's accessChainStore to:
3027// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003028//
3029// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003030void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3031{
3032 // Need to convert to abstract types when necessary
3033 if (type.getBasicType() == glslang::EbtBool) {
3034 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3035
3036 if (builder.isScalarType(nominalTypeId)) {
3037 // Conversion for bool
3038 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003039 if (nominalTypeId != boolType) {
3040 // keep these outside arguments, for determinant order-of-evaluation
3041 spv::Id one = builder.makeUintConstant(1);
3042 spv::Id zero = builder.makeUintConstant(0);
3043 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3044 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003045 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003046 } else if (builder.isVectorType(nominalTypeId)) {
3047 // Conversion for bvec
3048 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3049 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003050 if (nominalTypeId != bvecType) {
3051 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003052 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3053 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3054 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003055 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003056 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3057 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003058 }
3059 }
3060
3061 builder.accessChainStore(rvalue);
3062}
3063
John Kessenich4bf71552016-09-02 11:20:21 -06003064// For storing when types match at the glslang level, but not might match at the
3065// SPIR-V level.
3066//
3067// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003068// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003069// as in a member-decorated way.
3070//
3071// NOTE: This function can handle any store request; if it's not special it
3072// simplifies to a simple OpStore.
3073//
3074// Implicitly uses the existing builder.accessChain as the storage target.
3075void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3076{
John Kessenichb3e24e42016-09-11 12:33:43 -06003077 // we only do the complex path here if it's an aggregate
3078 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003079 accessChainStore(type, rValue);
3080 return;
3081 }
3082
John Kessenichb3e24e42016-09-11 12:33:43 -06003083 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003084 spv::Id rType = builder.getTypeId(rValue);
3085 spv::Id lValue = builder.accessChainGetLValue();
3086 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3087 if (lType == rType) {
3088 accessChainStore(type, rValue);
3089 return;
3090 }
3091
John Kessenichb3e24e42016-09-11 12:33:43 -06003092 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003093 // where the two types were the same type in GLSL. This requires member
3094 // by member copy, recursively.
3095
John Kessenichb3e24e42016-09-11 12:33:43 -06003096 // If an array, copy element by element.
3097 if (type.isArray()) {
3098 glslang::TType glslangElementType(type, 0);
3099 spv::Id elementRType = builder.getContainedTypeId(rType);
3100 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3101 // get the source member
3102 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003103
John Kessenichb3e24e42016-09-11 12:33:43 -06003104 // set up the target storage
3105 builder.clearAccessChain();
3106 builder.setAccessChainLValue(lValue);
3107 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06003108
John Kessenichb3e24e42016-09-11 12:33:43 -06003109 // store the member
3110 multiTypeStore(glslangElementType, elementRValue);
3111 }
3112 } else {
3113 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003114
John Kessenichb3e24e42016-09-11 12:33:43 -06003115 // loop over structure members
3116 const glslang::TTypeList& members = *type.getStruct();
3117 for (int m = 0; m < (int)members.size(); ++m) {
3118 const glslang::TType& glslangMemberType = *members[m].type;
3119
3120 // get the source member
3121 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3122 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3123
3124 // set up the target storage
3125 builder.clearAccessChain();
3126 builder.setAccessChainLValue(lValue);
3127 builder.accessChainPush(builder.makeIntConstant(m));
3128
3129 // store the member
3130 multiTypeStore(glslangMemberType, memberRValue);
3131 }
John Kessenich4bf71552016-09-02 11:20:21 -06003132 }
3133}
3134
John Kessenichf85e8062015-12-19 13:57:10 -07003135// Decide whether or not this type should be
3136// decorated with offsets and strides, and if so
3137// whether std140 or std430 rules should be applied.
3138glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003139{
John Kessenichf85e8062015-12-19 13:57:10 -07003140 // has to be a block
3141 if (type.getBasicType() != glslang::EbtBlock)
3142 return glslang::ElpNone;
3143
3144 // has to be a uniform or buffer block
3145 if (type.getQualifier().storage != glslang::EvqUniform &&
3146 type.getQualifier().storage != glslang::EvqBuffer)
3147 return glslang::ElpNone;
3148
3149 // return the layout to use
3150 switch (type.getQualifier().layoutPacking) {
3151 case glslang::ElpStd140:
3152 case glslang::ElpStd430:
3153 return type.getQualifier().layoutPacking;
3154 default:
3155 return glslang::ElpNone;
3156 }
John Kessenich31ed4832015-09-09 17:51:38 -06003157}
3158
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003159// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003160int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003161{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003162 int size;
John Kessenich49987892015-12-29 17:11:44 -07003163 int stride;
3164 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003165
3166 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003167}
3168
John Kessenich49987892015-12-29 17:11:44 -07003169// 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 -07003170// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003171int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003172{
John Kessenich49987892015-12-29 17:11:44 -07003173 glslang::TType elementType;
3174 elementType.shallowCopy(matrixType);
3175 elementType.clearArraySizes();
3176
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003177 int size;
John Kessenich49987892015-12-29 17:11:44 -07003178 int stride;
3179 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
3180
3181 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003182}
3183
John Kessenich5e4b1242015-08-06 22:53:06 -06003184// Given a member type of a struct, realign the current offset for it, and compute
3185// the next (not yet aligned) offset for the next member, which will get aligned
3186// on the next call.
3187// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3188// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3189// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003190void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003191 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003192{
3193 // this will get a positive value when deemed necessary
3194 nextOffset = -1;
3195
John Kessenich5e4b1242015-08-06 22:53:06 -06003196 // override anything in currentOffset with user-set offset
3197 if (memberType.getQualifier().hasOffset())
3198 currentOffset = memberType.getQualifier().layoutOffset;
3199
3200 // It could be that current linker usage in glslang updated all the layoutOffset,
3201 // in which case the following code does not matter. But, that's not quite right
3202 // once cross-compilation unit GLSL validation is done, as the original user
3203 // settings are needed in layoutOffset, and then the following will come into play.
3204
John Kessenichf85e8062015-12-19 13:57:10 -07003205 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003206 if (! memberType.getQualifier().hasOffset())
3207 currentOffset = -1;
3208
3209 return;
3210 }
3211
John Kessenichf85e8062015-12-19 13:57:10 -07003212 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003213 if (currentOffset < 0)
3214 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003215
John Kessenich5e4b1242015-08-06 22:53:06 -06003216 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3217 // but possibly not yet correctly aligned.
3218
3219 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003220 int dummyStride;
3221 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003222
3223 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003224 // TODO: make this consistent in early phases of code:
3225 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3226 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3227 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06003228 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003229 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003230 int dummySize;
3231 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3232 if (componentAlignment <= 4)
3233 memberAlignment = componentAlignment;
3234 }
3235
3236 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003237 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003238
3239 // Bump up to vec4 if there is a bad straddle
3240 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
3241 glslang::RoundToPow2(currentOffset, 16);
3242
John Kessenich5e4b1242015-08-06 22:53:06 -06003243 nextOffset = currentOffset + memberSize;
3244}
3245
David Netoa901ffe2016-06-08 14:11:40 +01003246void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003247{
David Netoa901ffe2016-06-08 14:11:40 +01003248 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3249 switch (glslangBuiltIn)
3250 {
3251 case glslang::EbvClipDistance:
3252 case glslang::EbvCullDistance:
3253 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003254#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003255 case glslang::EbvViewportMaskNV:
3256 case glslang::EbvSecondaryPositionNV:
3257 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003258 case glslang::EbvPositionPerViewNV:
3259 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08003260#endif
David Netoa901ffe2016-06-08 14:11:40 +01003261 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3262 // Alternately, we could just call this for any glslang built-in, since the
3263 // capability already guards against duplicates.
3264 TranslateBuiltInDecoration(glslangBuiltIn, false);
3265 break;
3266 default:
3267 // Capabilities were already generated when the struct was declared.
3268 break;
3269 }
John Kessenichebb50532016-05-16 19:22:05 -06003270}
3271
John Kessenich6fccb3c2016-09-19 16:01:41 -06003272bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003273{
John Kessenicheee9d532016-09-19 18:09:30 -06003274 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003275}
3276
John Kessenichd41993d2017-09-10 15:21:05 -06003277// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003278// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3279// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003280bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003281{
John Kessenich6a14f782017-12-04 02:48:10 -07003282 assert(qualifier == glslang::EvqIn ||
3283 qualifier == glslang::EvqOut ||
3284 qualifier == glslang::EvqInOut ||
3285 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003286 return qualifier != glslang::EvqConstReadOnly;
3287}
3288
3289// Is parameter pass-by-original?
3290bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3291 bool implicitThisParam)
3292{
3293 if (implicitThisParam) // implicit this
3294 return true;
3295 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003296 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003297 return paramType.containsOpaque() || // sampler, etc.
3298 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3299}
3300
John Kessenich140f3df2015-06-26 16:58:36 -06003301// Make all the functions, skeletally, without actually visiting their bodies.
3302void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3303{
John Kessenichfad62972017-07-18 02:35:46 -06003304 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
3305 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3306 if (paramPrecision != spv::NoPrecision)
3307 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06003308 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06003309 };
3310
John Kessenich140f3df2015-06-26 16:58:36 -06003311 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3312 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003313 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003314 continue;
3315
3316 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003317 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003318 //
qining25262b32016-05-06 17:25:16 -04003319 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003320 // function. What it is an address of varies:
3321 //
John Kessenich4bf71552016-09-02 11:20:21 -06003322 // - "in" parameters not marked as "const" can be written to without modifying the calling
3323 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003324 //
3325 // - "const in" parameters can just be the r-value, as no writes need occur.
3326 //
John Kessenich4bf71552016-09-02 11:20:21 -06003327 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3328 // 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 -06003329
3330 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003331 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003332 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3333
John Kessenichfad62972017-07-18 02:35:46 -06003334 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3335 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003336
John Kessenichfad62972017-07-18 02:35:46 -06003337 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003338 for (int p = 0; p < (int)parameters.size(); ++p) {
3339 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3340 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003341 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003342 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003343 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003344 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3345 else
John Kessenich4bf71552016-09-02 11:20:21 -06003346 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003347 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003348 paramTypes.push_back(typeId);
3349 }
3350
3351 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003352 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3353 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003354 glslFunction->getName().c_str(), paramTypes,
3355 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003356 if (implicitThis)
3357 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003358
3359 // Track function to emit/call later
3360 functionMap[glslFunction->getName().c_str()] = function;
3361
3362 // Set the parameter id's
3363 for (int p = 0; p < (int)parameters.size(); ++p) {
3364 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3365 // give a name too
3366 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3367 }
3368 }
3369}
3370
3371// Process all the initializers, while skipping the functions and link objects
3372void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3373{
3374 builder.setBuildPoint(shaderEntry->getLastBlock());
3375 for (int i = 0; i < (int)initializers.size(); ++i) {
3376 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3377 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3378
3379 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003380 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003381 initializer->traverse(this);
3382 }
3383 }
3384}
3385
3386// Process all the functions, while skipping initializers.
3387void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3388{
3389 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3390 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003391 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003392 node->traverse(this);
3393 }
3394}
3395
3396void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3397{
qining25262b32016-05-06 17:25:16 -04003398 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003399 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003400 currentFunction = functionMap[node->getName().c_str()];
3401 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003402 builder.setBuildPoint(functionBlock);
3403}
3404
Rex Xu04db3f52015-09-16 11:44:02 +08003405void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003406{
Rex Xufc618912015-09-09 16:42:49 +08003407 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003408
3409 glslang::TSampler sampler = {};
3410 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003411#ifdef AMD_EXTENSIONS
3412 bool f16ShadowCompare = false;
3413#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003414 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003415 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3416 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003417#ifdef AMD_EXTENSIONS
3418 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3419#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003420 }
3421
John Kessenich140f3df2015-06-26 16:58:36 -06003422 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3423 builder.clearAccessChain();
3424 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003425
3426 // Special case l-value operands
3427 bool lvalue = false;
3428 switch (node.getOp()) {
3429 case glslang::EOpImageAtomicAdd:
3430 case glslang::EOpImageAtomicMin:
3431 case glslang::EOpImageAtomicMax:
3432 case glslang::EOpImageAtomicAnd:
3433 case glslang::EOpImageAtomicOr:
3434 case glslang::EOpImageAtomicXor:
3435 case glslang::EOpImageAtomicExchange:
3436 case glslang::EOpImageAtomicCompSwap:
3437 if (i == 0)
3438 lvalue = true;
3439 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003440 case glslang::EOpSparseImageLoad:
3441 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3442 lvalue = true;
3443 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003444#ifdef AMD_EXTENSIONS
3445 case glslang::EOpSparseTexture:
3446 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3447 lvalue = true;
3448 break;
3449 case glslang::EOpSparseTextureClamp:
3450 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3451 lvalue = true;
3452 break;
3453 case glslang::EOpSparseTextureLod:
3454 case glslang::EOpSparseTextureOffset:
3455 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
3456 lvalue = true;
3457 break;
3458#else
Rex Xu48edadf2015-12-31 16:11:41 +08003459 case glslang::EOpSparseTexture:
3460 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3461 lvalue = true;
3462 break;
3463 case glslang::EOpSparseTextureClamp:
3464 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3465 lvalue = true;
3466 break;
3467 case glslang::EOpSparseTextureLod:
3468 case glslang::EOpSparseTextureOffset:
3469 if (i == 3)
3470 lvalue = true;
3471 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003472#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003473 case glslang::EOpSparseTextureFetch:
3474 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3475 lvalue = true;
3476 break;
3477 case glslang::EOpSparseTextureFetchOffset:
3478 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3479 lvalue = true;
3480 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003481#ifdef AMD_EXTENSIONS
3482 case glslang::EOpSparseTextureLodOffset:
3483 case glslang::EOpSparseTextureGrad:
3484 case glslang::EOpSparseTextureOffsetClamp:
3485 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
3486 lvalue = true;
3487 break;
3488 case glslang::EOpSparseTextureGradOffset:
3489 case glslang::EOpSparseTextureGradClamp:
3490 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
3491 lvalue = true;
3492 break;
3493 case glslang::EOpSparseTextureGradOffsetClamp:
3494 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
3495 lvalue = true;
3496 break;
3497#else
Rex Xu48edadf2015-12-31 16:11:41 +08003498 case glslang::EOpSparseTextureLodOffset:
3499 case glslang::EOpSparseTextureGrad:
3500 case glslang::EOpSparseTextureOffsetClamp:
3501 if (i == 4)
3502 lvalue = true;
3503 break;
3504 case glslang::EOpSparseTextureGradOffset:
3505 case glslang::EOpSparseTextureGradClamp:
3506 if (i == 5)
3507 lvalue = true;
3508 break;
3509 case glslang::EOpSparseTextureGradOffsetClamp:
3510 if (i == 6)
3511 lvalue = true;
3512 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003513#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08003514 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003515 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3516 lvalue = true;
3517 break;
3518 case glslang::EOpSparseTextureGatherOffset:
3519 case glslang::EOpSparseTextureGatherOffsets:
3520 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3521 lvalue = true;
3522 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003523#ifdef AMD_EXTENSIONS
3524 case glslang::EOpSparseTextureGatherLod:
3525 if (i == 3)
3526 lvalue = true;
3527 break;
3528 case glslang::EOpSparseTextureGatherLodOffset:
3529 case glslang::EOpSparseTextureGatherLodOffsets:
3530 if (i == 4)
3531 lvalue = true;
3532 break;
Rex Xu129799a2017-07-05 17:23:28 +08003533 case glslang::EOpSparseImageLoadLod:
3534 if (i == 3)
3535 lvalue = true;
3536 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003537#endif
Rex Xufc618912015-09-09 16:42:49 +08003538 default:
3539 break;
3540 }
3541
Rex Xu6b86d492015-09-16 17:48:22 +08003542 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003543 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003544 else
John Kessenich32cfd492016-02-02 12:37:46 -07003545 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003546 }
3547}
3548
John Kessenichfc51d282015-08-19 13:34:18 -06003549void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003550{
John Kessenichfc51d282015-08-19 13:34:18 -06003551 builder.clearAccessChain();
3552 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003553 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003554}
John Kessenich140f3df2015-06-26 16:58:36 -06003555
John Kessenichfc51d282015-08-19 13:34:18 -06003556spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3557{
John Kesseniche485c7a2017-05-31 18:50:53 -06003558 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003559 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003560
3561 builder.setLine(node->getLoc().line);
3562
John Kessenichfc51d282015-08-19 13:34:18 -06003563 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003564 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3565 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08003566#ifdef AMD_EXTENSIONS
3567 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
3568 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
3569 : false;
3570#endif
3571
John Kessenichfc51d282015-08-19 13:34:18 -06003572 std::vector<spv::Id> arguments;
3573 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003574 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003575 else
3576 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003577 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003578
3579 spv::Builder::TextureParameters params = { };
3580 params.sampler = arguments[0];
3581
Rex Xu04db3f52015-09-16 11:44:02 +08003582 glslang::TCrackedTextureOp cracked;
3583 node->crackTexture(sampler, cracked);
3584
amhagan05506bb2017-06-13 16:53:02 -04003585 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003586
John Kessenichfc51d282015-08-19 13:34:18 -06003587 // Check for queries
3588 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003589 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3590 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003591 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003592
John Kessenichfc51d282015-08-19 13:34:18 -06003593 switch (node->getOp()) {
3594 case glslang::EOpImageQuerySize:
3595 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003596 if (arguments.size() > 1) {
3597 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003598 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003599 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003600 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003601 case glslang::EOpImageQuerySamples:
3602 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003603 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003604 case glslang::EOpTextureQueryLod:
3605 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003606 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003607 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003608 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003609 case glslang::EOpSparseTexelsResident:
3610 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003611 default:
3612 assert(0);
3613 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003614 }
John Kessenich140f3df2015-06-26 16:58:36 -06003615 }
3616
LoopDawg4425f242018-02-18 11:40:01 -07003617 int components = node->getType().getVectorSize();
3618
3619 if (node->getOp() == glslang::EOpTextureFetch) {
3620 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3621 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3622 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3623 // here around e.g. which ones return scalars or other types.
3624 components = 4;
3625 }
3626
3627 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3628
3629 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3630
Rex Xufc618912015-09-09 16:42:49 +08003631 // Check for image functions other than queries
3632 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003633 std::vector<spv::Id> operands;
3634 auto opIt = arguments.begin();
3635 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003636
3637 // Handle subpass operations
3638 // TODO: GLSL should change to have the "MS" only on the type rather than the
3639 // built-in function.
3640 if (cracked.subpass) {
3641 // add on the (0,0) coordinate
3642 spv::Id zero = builder.makeIntConstant(0);
3643 std::vector<spv::Id> comps;
3644 comps.push_back(zero);
3645 comps.push_back(zero);
3646 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3647 if (sampler.ms) {
3648 operands.push_back(spv::ImageOperandsSampleMask);
3649 operands.push_back(*(opIt++));
3650 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003651 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3652 builder.setPrecision(result, precision);
3653 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003654 }
3655
John Kessenich56bab042015-09-16 10:54:31 -06003656 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003657#ifdef AMD_EXTENSIONS
3658 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3659#else
John Kessenich56bab042015-09-16 10:54:31 -06003660 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003661#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003662 if (sampler.ms) {
3663 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003664 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003665#ifdef AMD_EXTENSIONS
3666 } else if (cracked.lod) {
3667 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3668 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3669
3670 operands.push_back(spv::ImageOperandsLodMask);
3671 operands.push_back(*opIt);
3672#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003673 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003674 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3675 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003676
St0fFa1184dd2018-04-09 21:08:14 +02003677 std::vector<spv::Id> result( 1, builder.createOp(spv::OpImageRead, resultType(), operands) );
LoopDawg4425f242018-02-18 11:40:01 -07003678 builder.setPrecision(result[0], precision);
3679
3680 // If needed, add a conversion constructor to the proper size.
3681 if (components != node->getType().getVectorSize())
3682 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3683
3684 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08003685#ifdef AMD_EXTENSIONS
3686 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3687#else
John Kessenich56bab042015-09-16 10:54:31 -06003688 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003689#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003690 if (sampler.ms) {
3691 operands.push_back(*(opIt + 1));
3692 operands.push_back(spv::ImageOperandsSampleMask);
3693 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003694#ifdef AMD_EXTENSIONS
3695 } else if (cracked.lod) {
3696 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3697 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3698
3699 operands.push_back(*(opIt + 1));
3700 operands.push_back(spv::ImageOperandsLodMask);
3701 operands.push_back(*opIt);
3702#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003703 } else
3704 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003705 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003706 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3707 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003708 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003709#ifdef AMD_EXTENSIONS
3710 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3711#else
Rex Xu5eafa472016-02-19 22:24:03 +08003712 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003713#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003714 builder.addCapability(spv::CapabilitySparseResidency);
3715 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3716 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3717
3718 if (sampler.ms) {
3719 operands.push_back(spv::ImageOperandsSampleMask);
3720 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003721#ifdef AMD_EXTENSIONS
3722 } else if (cracked.lod) {
3723 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3724 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3725
3726 operands.push_back(spv::ImageOperandsLodMask);
3727 operands.push_back(*opIt++);
3728#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003729 }
3730
3731 // Create the return type that was a special structure
3732 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003733 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003734 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3735 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3736
3737 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3738
3739 // Decode the return type
3740 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3741 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003742 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003743 // Process image atomic operations
3744
3745 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3746 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003747 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003748
John Kessenich8c8505c2016-07-26 12:50:38 -06003749 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003750 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003751
3752 std::vector<spv::Id> operands;
3753 operands.push_back(pointer);
3754 for (; opIt != arguments.end(); ++opIt)
3755 operands.push_back(*opIt);
3756
John Kessenich8c8505c2016-07-26 12:50:38 -06003757 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003758 }
3759 }
3760
amhagan05506bb2017-06-13 16:53:02 -04003761#ifdef AMD_EXTENSIONS
3762 // Check for fragment mask functions other than queries
3763 if (cracked.fragMask) {
3764 assert(sampler.ms);
3765
3766 auto opIt = arguments.begin();
3767 std::vector<spv::Id> operands;
3768
3769 // Extract the image if necessary
3770 if (builder.isSampledImage(params.sampler))
3771 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3772
3773 operands.push_back(params.sampler);
3774 ++opIt;
3775
3776 if (sampler.isSubpass()) {
3777 // add on the (0,0) coordinate
3778 spv::Id zero = builder.makeIntConstant(0);
3779 std::vector<spv::Id> comps;
3780 comps.push_back(zero);
3781 comps.push_back(zero);
3782 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3783 }
3784
3785 for (; opIt != arguments.end(); ++opIt)
3786 operands.push_back(*opIt);
3787
3788 spv::Op fragMaskOp = spv::OpNop;
3789 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3790 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3791 else if (node->getOp() == glslang::EOpFragmentFetch)
3792 fragMaskOp = spv::OpFragmentFetchAMD;
3793
3794 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3795 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3796 return builder.createOp(fragMaskOp, resultType(), operands);
3797 }
3798#endif
3799
Rex Xufc618912015-09-09 16:42:49 +08003800 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003801 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003802 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3803
John Kessenichfc51d282015-08-19 13:34:18 -06003804 // check for bias argument
3805 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003806#ifdef AMD_EXTENSIONS
3807 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3808#else
Rex Xu71519fe2015-11-11 15:35:47 +08003809 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003810#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003811 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003812#ifdef AMD_EXTENSIONS
3813 if (cracked.gather)
3814 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08003815
3816 if (f16ShadowCompare)
3817 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003818#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003819 if (cracked.offset)
3820 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003821#ifdef AMD_EXTENSIONS
3822 else if (cracked.offsets)
3823 ++nonBiasArgCount;
3824#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003825 if (cracked.grad)
3826 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003827 if (cracked.lodClamp)
3828 ++nonBiasArgCount;
3829 if (sparse)
3830 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003831
3832 if ((int)arguments.size() > nonBiasArgCount)
3833 bias = true;
3834 }
3835
John Kessenicha5c33d62016-06-02 23:45:21 -06003836 // See if the sampler param should really be just the SPV image part
3837 if (cracked.fetch) {
3838 // a fetch needs to have the image extracted first
3839 if (builder.isSampledImage(params.sampler))
3840 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3841 }
3842
Rex Xu225e0fc2016-11-17 17:47:59 +08003843#ifdef AMD_EXTENSIONS
3844 if (cracked.gather) {
3845 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3846 if (bias || cracked.lod ||
3847 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3848 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003849 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003850 }
3851 }
3852#endif
3853
John Kessenichfc51d282015-08-19 13:34:18 -06003854 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003855
John Kessenichfc51d282015-08-19 13:34:18 -06003856 params.coords = arguments[1];
3857 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003858 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003859
3860 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08003861#ifdef AMD_EXTENSIONS
3862 if (cubeCompare || f16ShadowCompare) {
3863#else
Rex Xu48edadf2015-12-31 16:11:41 +08003864 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08003865#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003866 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003867 ++extraArgs;
3868 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003869 params.Dref = arguments[2];
3870 ++extraArgs;
3871 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003872 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003873 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003874 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003875 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003876 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003877 dRefComp = builder.getNumComponents(params.coords) - 1;
3878 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003879 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3880 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003881
3882 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003883 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003884 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003885 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003886 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3887 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3888 noImplicitLod = true;
3889 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003890
3891 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003892 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003893 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003894 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003895 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003896
3897 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003898 if (cracked.grad) {
3899 params.gradX = arguments[2 + extraArgs];
3900 params.gradY = arguments[3 + extraArgs];
3901 extraArgs += 2;
3902 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003903
3904 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003905 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003906 params.offset = arguments[2 + extraArgs];
3907 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003908 } else if (cracked.offsets) {
3909 params.offsets = arguments[2 + extraArgs];
3910 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003911 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003912
3913 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003914 if (cracked.lodClamp) {
3915 params.lodClamp = arguments[2 + extraArgs];
3916 ++extraArgs;
3917 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003918
3919 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003920 if (sparse) {
3921 params.texelOut = arguments[2 + extraArgs];
3922 ++extraArgs;
3923 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003924
John Kessenich76d4dfc2016-06-16 12:43:23 -06003925 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003926 if (cracked.gather && ! sampler.shadow) {
3927 // default component is 0, if missing, otherwise an argument
3928 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003929 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003930 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003931 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003932 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003933 }
3934
3935 // bias
3936 if (bias) {
3937 params.bias = arguments[2 + extraArgs];
3938 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003939 }
John Kessenichfc51d282015-08-19 13:34:18 -06003940
John Kessenich65336482016-06-16 14:06:26 -06003941 // projective component (might not to move)
3942 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3943 // are divided by the last component of P."
3944 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3945 // unused components will appear after all used components."
3946 if (cracked.proj) {
3947 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3948 int projTargetComp;
3949 switch (sampler.dim) {
3950 case glslang::Esd1D: projTargetComp = 1; break;
3951 case glslang::Esd2D: projTargetComp = 2; break;
3952 case glslang::EsdRect: projTargetComp = 2; break;
3953 default: projTargetComp = projSourceComp; break;
3954 }
3955 // copy the projective coordinate if we have to
3956 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003957 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003958 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3959 projSourceComp);
3960 params.coords = builder.createCompositeInsert(projComp, params.coords,
3961 builder.getTypeId(params.coords), projTargetComp);
3962 }
3963 }
3964
St0fFa1184dd2018-04-09 21:08:14 +02003965 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07003966 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02003967 );
LoopDawg4425f242018-02-18 11:40:01 -07003968
3969 if (components != node->getType().getVectorSize())
3970 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3971
3972 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06003973}
3974
3975spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3976{
3977 // Grab the function's pointer from the previously created function
3978 spv::Function* function = functionMap[node->getName().c_str()];
3979 if (! function)
3980 return 0;
3981
3982 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3983 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3984
3985 // See comments in makeFunctions() for details about the semantics for parameter passing.
3986 //
3987 // These imply we need a four step process:
3988 // 1. Evaluate the arguments
3989 // 2. Allocate and make copies of in, out, and inout arguments
3990 // 3. Make the call
3991 // 4. Copy back the results
3992
John Kessenichd3ed90b2018-05-04 11:43:03 -06003993 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06003994 std::vector<spv::Builder::AccessChain> lValues;
3995 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003996 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003997 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06003998 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003999 // build l-value
4000 builder.clearAccessChain();
4001 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004002 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004003 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004004 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004005 // save l-value
4006 lValues.push_back(builder.getAccessChain());
4007 } else {
4008 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004009 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004010 }
4011 }
4012
4013 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4014 // copy the original into that space.
4015 //
4016 // Also, build up the list of actual arguments to pass in for the call
4017 int lValueCount = 0;
4018 int rValueCount = 0;
4019 std::vector<spv::Id> spvArgs;
4020 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4021 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004022 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004023 builder.setAccessChain(lValues[lValueCount]);
4024 arg = builder.accessChainGetLValue();
4025 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004026 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004027 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004028 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004029 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4030 // need to copy the input into output space
4031 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004032 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004033 builder.clearAccessChain();
4034 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004035 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004036 }
4037 ++lValueCount;
4038 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004039 // process r-value, which involves a copy for a type mismatch
4040 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4041 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4042 builder.clearAccessChain();
4043 builder.setAccessChainLValue(argCopy);
4044 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4045 arg = builder.createLoad(argCopy);
4046 } else
4047 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004048 ++rValueCount;
4049 }
4050 spvArgs.push_back(arg);
4051 }
4052
4053 // 3. Make the call.
4054 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004055 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004056
4057 // 4. Copy back out an "out" arguments.
4058 lValueCount = 0;
4059 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004060 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004061 ++lValueCount;
4062 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004063 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4064 spv::Id copy = builder.createLoad(spvArgs[a]);
4065 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004066 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004067 }
4068 ++lValueCount;
4069 }
4070 }
4071
4072 return result;
4073}
4074
4075// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004076spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004077 spv::Id typeId, spv::Id left, spv::Id right,
4078 glslang::TBasicType typeProxy, bool reduceComparison)
4079{
John Kessenich66011cb2018-03-06 16:12:04 -07004080 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4081 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004082 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004083
4084 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004085 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004086 bool comparison = false;
4087
4088 switch (op) {
4089 case glslang::EOpAdd:
4090 case glslang::EOpAddAssign:
4091 if (isFloat)
4092 binOp = spv::OpFAdd;
4093 else
4094 binOp = spv::OpIAdd;
4095 break;
4096 case glslang::EOpSub:
4097 case glslang::EOpSubAssign:
4098 if (isFloat)
4099 binOp = spv::OpFSub;
4100 else
4101 binOp = spv::OpISub;
4102 break;
4103 case glslang::EOpMul:
4104 case glslang::EOpMulAssign:
4105 if (isFloat)
4106 binOp = spv::OpFMul;
4107 else
4108 binOp = spv::OpIMul;
4109 break;
4110 case glslang::EOpVectorTimesScalar:
4111 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004112 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004113 if (builder.isVector(right))
4114 std::swap(left, right);
4115 assert(builder.isScalar(right));
4116 needMatchingVectors = false;
4117 binOp = spv::OpVectorTimesScalar;
4118 } else
4119 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004120 break;
4121 case glslang::EOpVectorTimesMatrix:
4122 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004123 binOp = spv::OpVectorTimesMatrix;
4124 break;
4125 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004126 binOp = spv::OpMatrixTimesVector;
4127 break;
4128 case glslang::EOpMatrixTimesScalar:
4129 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004130 binOp = spv::OpMatrixTimesScalar;
4131 break;
4132 case glslang::EOpMatrixTimesMatrix:
4133 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004134 binOp = spv::OpMatrixTimesMatrix;
4135 break;
4136 case glslang::EOpOuterProduct:
4137 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004138 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004139 break;
4140
4141 case glslang::EOpDiv:
4142 case glslang::EOpDivAssign:
4143 if (isFloat)
4144 binOp = spv::OpFDiv;
4145 else if (isUnsigned)
4146 binOp = spv::OpUDiv;
4147 else
4148 binOp = spv::OpSDiv;
4149 break;
4150 case glslang::EOpMod:
4151 case glslang::EOpModAssign:
4152 if (isFloat)
4153 binOp = spv::OpFMod;
4154 else if (isUnsigned)
4155 binOp = spv::OpUMod;
4156 else
4157 binOp = spv::OpSMod;
4158 break;
4159 case glslang::EOpRightShift:
4160 case glslang::EOpRightShiftAssign:
4161 if (isUnsigned)
4162 binOp = spv::OpShiftRightLogical;
4163 else
4164 binOp = spv::OpShiftRightArithmetic;
4165 break;
4166 case glslang::EOpLeftShift:
4167 case glslang::EOpLeftShiftAssign:
4168 binOp = spv::OpShiftLeftLogical;
4169 break;
4170 case glslang::EOpAnd:
4171 case glslang::EOpAndAssign:
4172 binOp = spv::OpBitwiseAnd;
4173 break;
4174 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004175 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004176 binOp = spv::OpLogicalAnd;
4177 break;
4178 case glslang::EOpInclusiveOr:
4179 case glslang::EOpInclusiveOrAssign:
4180 binOp = spv::OpBitwiseOr;
4181 break;
4182 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004183 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004184 binOp = spv::OpLogicalOr;
4185 break;
4186 case glslang::EOpExclusiveOr:
4187 case glslang::EOpExclusiveOrAssign:
4188 binOp = spv::OpBitwiseXor;
4189 break;
4190 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004191 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004192 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004193 break;
4194
4195 case glslang::EOpLessThan:
4196 case glslang::EOpGreaterThan:
4197 case glslang::EOpLessThanEqual:
4198 case glslang::EOpGreaterThanEqual:
4199 case glslang::EOpEqual:
4200 case glslang::EOpNotEqual:
4201 case glslang::EOpVectorEqual:
4202 case glslang::EOpVectorNotEqual:
4203 comparison = true;
4204 break;
4205 default:
4206 break;
4207 }
4208
John Kessenich7c1aa102015-10-15 13:29:11 -06004209 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004210 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004211 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07004212 if (builder.isMatrix(left) || builder.isMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004213 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004214
4215 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004216 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004217 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004218
qining25262b32016-05-06 17:25:16 -04004219 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004220 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004221 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004222 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004223 }
4224
4225 if (! comparison)
4226 return 0;
4227
John Kessenich7c1aa102015-10-15 13:29:11 -06004228 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004229
John Kessenich4583b612016-08-07 19:14:22 -06004230 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004231 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4232 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004233 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004234 return result;
4235 }
John Kessenich140f3df2015-06-26 16:58:36 -06004236
4237 switch (op) {
4238 case glslang::EOpLessThan:
4239 if (isFloat)
4240 binOp = spv::OpFOrdLessThan;
4241 else if (isUnsigned)
4242 binOp = spv::OpULessThan;
4243 else
4244 binOp = spv::OpSLessThan;
4245 break;
4246 case glslang::EOpGreaterThan:
4247 if (isFloat)
4248 binOp = spv::OpFOrdGreaterThan;
4249 else if (isUnsigned)
4250 binOp = spv::OpUGreaterThan;
4251 else
4252 binOp = spv::OpSGreaterThan;
4253 break;
4254 case glslang::EOpLessThanEqual:
4255 if (isFloat)
4256 binOp = spv::OpFOrdLessThanEqual;
4257 else if (isUnsigned)
4258 binOp = spv::OpULessThanEqual;
4259 else
4260 binOp = spv::OpSLessThanEqual;
4261 break;
4262 case glslang::EOpGreaterThanEqual:
4263 if (isFloat)
4264 binOp = spv::OpFOrdGreaterThanEqual;
4265 else if (isUnsigned)
4266 binOp = spv::OpUGreaterThanEqual;
4267 else
4268 binOp = spv::OpSGreaterThanEqual;
4269 break;
4270 case glslang::EOpEqual:
4271 case glslang::EOpVectorEqual:
4272 if (isFloat)
4273 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004274 else if (isBool)
4275 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004276 else
4277 binOp = spv::OpIEqual;
4278 break;
4279 case glslang::EOpNotEqual:
4280 case glslang::EOpVectorNotEqual:
4281 if (isFloat)
4282 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004283 else if (isBool)
4284 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004285 else
4286 binOp = spv::OpINotEqual;
4287 break;
4288 default:
4289 break;
4290 }
4291
qining25262b32016-05-06 17:25:16 -04004292 if (binOp != spv::OpNop) {
4293 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004294 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004295 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004296 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004297 }
John Kessenich140f3df2015-06-26 16:58:36 -06004298
4299 return 0;
4300}
4301
John Kessenich04bb8a02015-12-12 12:28:14 -07004302//
4303// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
4304// These can be any of:
4305//
4306// matrix * scalar
4307// scalar * matrix
4308// matrix * matrix linear algebraic
4309// matrix * vector
4310// vector * matrix
4311// matrix * matrix componentwise
4312// matrix op matrix op in {+, -, /}
4313// matrix op scalar op in {+, -, /}
4314// scalar op matrix op in {+, -, /}
4315//
John Kessenichead86222018-03-28 18:01:20 -06004316spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4317 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07004318{
4319 bool firstClass = true;
4320
4321 // First, handle first-class matrix operations (* and matrix/scalar)
4322 switch (op) {
4323 case spv::OpFDiv:
4324 if (builder.isMatrix(left) && builder.isScalar(right)) {
4325 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01004326 spv::Id resultType = builder.getTypeId(right);
4327 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07004328 op = spv::OpMatrixTimesScalar;
4329 } else
4330 firstClass = false;
4331 break;
4332 case spv::OpMatrixTimesScalar:
4333 if (builder.isMatrix(right))
4334 std::swap(left, right);
4335 assert(builder.isScalar(right));
4336 break;
4337 case spv::OpVectorTimesMatrix:
4338 assert(builder.isVector(left));
4339 assert(builder.isMatrix(right));
4340 break;
4341 case spv::OpMatrixTimesVector:
4342 assert(builder.isMatrix(left));
4343 assert(builder.isVector(right));
4344 break;
4345 case spv::OpMatrixTimesMatrix:
4346 assert(builder.isMatrix(left));
4347 assert(builder.isMatrix(right));
4348 break;
4349 default:
4350 firstClass = false;
4351 break;
4352 }
4353
qining25262b32016-05-06 17:25:16 -04004354 if (firstClass) {
4355 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004356 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004357 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004358 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004359 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004360
LoopDawg592860c2016-06-09 08:57:35 -06004361 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004362 // The result type of all of them is the same type as the (a) matrix operand.
4363 // The algorithm is to:
4364 // - break the matrix(es) into vectors
4365 // - smear any scalar to a vector
4366 // - do vector operations
4367 // - make a matrix out the vector results
4368 switch (op) {
4369 case spv::OpFAdd:
4370 case spv::OpFSub:
4371 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004372 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004373 case spv::OpFMul:
4374 {
4375 // one time set up...
4376 bool leftMat = builder.isMatrix(left);
4377 bool rightMat = builder.isMatrix(right);
4378 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4379 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4380 spv::Id scalarType = builder.getScalarTypeId(typeId);
4381 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4382 std::vector<spv::Id> results;
4383 spv::Id smearVec = spv::NoResult;
4384 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06004385 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004386 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06004387 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004388
4389 // do each vector op
4390 for (unsigned int c = 0; c < numCols; ++c) {
4391 std::vector<unsigned int> indexes;
4392 indexes.push_back(c);
4393 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4394 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004395 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06004396 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004397 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004398 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004399 }
4400
4401 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004402 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004403 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004404 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07004405 }
4406 default:
4407 assert(0);
4408 return spv::NoResult;
4409 }
4410}
4411
John Kessenichead86222018-03-28 18:01:20 -06004412spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
4413 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004414{
4415 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004416 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004417 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07004418 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4419 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004420
4421 switch (op) {
4422 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004423 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004424 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004425 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06004426 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004427 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004428 unaryOp = spv::OpSNegate;
4429 break;
4430
4431 case glslang::EOpLogicalNot:
4432 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004433 unaryOp = spv::OpLogicalNot;
4434 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004435 case glslang::EOpBitwiseNot:
4436 unaryOp = spv::OpNot;
4437 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004438
John Kessenich140f3df2015-06-26 16:58:36 -06004439 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004440 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004441 break;
4442 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004443 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004444 break;
4445 case glslang::EOpTranspose:
4446 unaryOp = spv::OpTranspose;
4447 break;
4448
4449 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004450 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004451 break;
4452 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004453 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004454 break;
4455 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004456 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004457 break;
4458 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004459 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004460 break;
4461 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004462 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004463 break;
4464 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004465 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004466 break;
4467 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004468 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004469 break;
4470 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004471 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004472 break;
4473
4474 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004475 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004476 break;
4477 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004478 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004479 break;
4480 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004481 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004482 break;
4483 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004484 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004485 break;
4486 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004487 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004488 break;
4489 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004490 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004491 break;
4492
4493 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004494 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004495 break;
4496 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004497 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004498 break;
4499
4500 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004501 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004502 break;
4503 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004504 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004505 break;
4506 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004507 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004508 break;
4509 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004510 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004511 break;
4512 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004513 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004514 break;
4515 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004516 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004517 break;
4518
4519 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004520 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004521 break;
4522 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004523 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004524 break;
4525 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004526 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004527 break;
4528 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004529 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004530 break;
4531 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004532 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004533 break;
4534 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004535 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004536 break;
4537
4538 case glslang::EOpIsNan:
4539 unaryOp = spv::OpIsNan;
4540 break;
4541 case glslang::EOpIsInf:
4542 unaryOp = spv::OpIsInf;
4543 break;
LoopDawg592860c2016-06-09 08:57:35 -06004544 case glslang::EOpIsFinite:
4545 unaryOp = spv::OpIsFinite;
4546 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004547
Rex Xucbc426e2015-12-15 16:03:10 +08004548 case glslang::EOpFloatBitsToInt:
4549 case glslang::EOpFloatBitsToUint:
4550 case glslang::EOpIntBitsToFloat:
4551 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004552 case glslang::EOpDoubleBitsToInt64:
4553 case glslang::EOpDoubleBitsToUint64:
4554 case glslang::EOpInt64BitsToDouble:
4555 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004556 case glslang::EOpFloat16BitsToInt16:
4557 case glslang::EOpFloat16BitsToUint16:
4558 case glslang::EOpInt16BitsToFloat16:
4559 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08004560 unaryOp = spv::OpBitcast;
4561 break;
4562
John Kessenich140f3df2015-06-26 16:58:36 -06004563 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004564 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004565 break;
4566 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004567 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004568 break;
4569 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004570 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004571 break;
4572 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004573 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004574 break;
4575 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004576 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004577 break;
4578 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004579 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004580 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004581 case glslang::EOpPackSnorm4x8:
4582 libCall = spv::GLSLstd450PackSnorm4x8;
4583 break;
4584 case glslang::EOpUnpackSnorm4x8:
4585 libCall = spv::GLSLstd450UnpackSnorm4x8;
4586 break;
4587 case glslang::EOpPackUnorm4x8:
4588 libCall = spv::GLSLstd450PackUnorm4x8;
4589 break;
4590 case glslang::EOpUnpackUnorm4x8:
4591 libCall = spv::GLSLstd450UnpackUnorm4x8;
4592 break;
4593 case glslang::EOpPackDouble2x32:
4594 libCall = spv::GLSLstd450PackDouble2x32;
4595 break;
4596 case glslang::EOpUnpackDouble2x32:
4597 libCall = spv::GLSLstd450UnpackDouble2x32;
4598 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004599
Rex Xu8ff43de2016-04-22 16:51:45 +08004600 case glslang::EOpPackInt2x32:
4601 case glslang::EOpUnpackInt2x32:
4602 case glslang::EOpPackUint2x32:
4603 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07004604 case glslang::EOpPack16:
4605 case glslang::EOpPack32:
4606 case glslang::EOpPack64:
4607 case glslang::EOpUnpack32:
4608 case glslang::EOpUnpack16:
4609 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08004610 case glslang::EOpPackInt2x16:
4611 case glslang::EOpUnpackInt2x16:
4612 case glslang::EOpPackUint2x16:
4613 case glslang::EOpUnpackUint2x16:
4614 case glslang::EOpPackInt4x16:
4615 case glslang::EOpUnpackInt4x16:
4616 case glslang::EOpPackUint4x16:
4617 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004618 case glslang::EOpPackFloat2x16:
4619 case glslang::EOpUnpackFloat2x16:
4620 unaryOp = spv::OpBitcast;
4621 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004622
John Kessenich140f3df2015-06-26 16:58:36 -06004623 case glslang::EOpDPdx:
4624 unaryOp = spv::OpDPdx;
4625 break;
4626 case glslang::EOpDPdy:
4627 unaryOp = spv::OpDPdy;
4628 break;
4629 case glslang::EOpFwidth:
4630 unaryOp = spv::OpFwidth;
4631 break;
4632 case glslang::EOpDPdxFine:
4633 unaryOp = spv::OpDPdxFine;
4634 break;
4635 case glslang::EOpDPdyFine:
4636 unaryOp = spv::OpDPdyFine;
4637 break;
4638 case glslang::EOpFwidthFine:
4639 unaryOp = spv::OpFwidthFine;
4640 break;
4641 case glslang::EOpDPdxCoarse:
4642 unaryOp = spv::OpDPdxCoarse;
4643 break;
4644 case glslang::EOpDPdyCoarse:
4645 unaryOp = spv::OpDPdyCoarse;
4646 break;
4647 case glslang::EOpFwidthCoarse:
4648 unaryOp = spv::OpFwidthCoarse;
4649 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004650 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08004651#ifdef AMD_EXTENSIONS
4652 if (typeProxy == glslang::EbtFloat16)
4653 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
4654#endif
Rex Xu7a26c172015-12-08 17:12:09 +08004655 libCall = spv::GLSLstd450InterpolateAtCentroid;
4656 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004657 case glslang::EOpAny:
4658 unaryOp = spv::OpAny;
4659 break;
4660 case glslang::EOpAll:
4661 unaryOp = spv::OpAll;
4662 break;
4663
4664 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004665 if (isFloat)
4666 libCall = spv::GLSLstd450FAbs;
4667 else
4668 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004669 break;
4670 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004671 if (isFloat)
4672 libCall = spv::GLSLstd450FSign;
4673 else
4674 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004675 break;
4676
John Kessenichfc51d282015-08-19 13:34:18 -06004677 case glslang::EOpAtomicCounterIncrement:
4678 case glslang::EOpAtomicCounterDecrement:
4679 case glslang::EOpAtomicCounter:
4680 {
4681 // Handle all of the atomics in one place, in createAtomicOperation()
4682 std::vector<spv::Id> operands;
4683 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06004684 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004685 }
4686
John Kessenichfc51d282015-08-19 13:34:18 -06004687 case glslang::EOpBitFieldReverse:
4688 unaryOp = spv::OpBitReverse;
4689 break;
4690 case glslang::EOpBitCount:
4691 unaryOp = spv::OpBitCount;
4692 break;
4693 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004694 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004695 break;
4696 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004697 if (isUnsigned)
4698 libCall = spv::GLSLstd450FindUMsb;
4699 else
4700 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004701 break;
4702
Rex Xu574ab042016-04-14 16:53:07 +08004703 case glslang::EOpBallot:
4704 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004705 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004706 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004707 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004708#ifdef AMD_EXTENSIONS
4709 case glslang::EOpMinInvocations:
4710 case glslang::EOpMaxInvocations:
4711 case glslang::EOpAddInvocations:
4712 case glslang::EOpMinInvocationsNonUniform:
4713 case glslang::EOpMaxInvocationsNonUniform:
4714 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004715 case glslang::EOpMinInvocationsInclusiveScan:
4716 case glslang::EOpMaxInvocationsInclusiveScan:
4717 case glslang::EOpAddInvocationsInclusiveScan:
4718 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4719 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4720 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4721 case glslang::EOpMinInvocationsExclusiveScan:
4722 case glslang::EOpMaxInvocationsExclusiveScan:
4723 case glslang::EOpAddInvocationsExclusiveScan:
4724 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4725 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4726 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004727#endif
Rex Xu51596642016-09-21 18:56:12 +08004728 {
4729 std::vector<spv::Id> operands;
4730 operands.push_back(operand);
4731 return createInvocationsOperation(op, typeId, operands, typeProxy);
4732 }
John Kessenich66011cb2018-03-06 16:12:04 -07004733 case glslang::EOpSubgroupAll:
4734 case glslang::EOpSubgroupAny:
4735 case glslang::EOpSubgroupAllEqual:
4736 case glslang::EOpSubgroupBroadcastFirst:
4737 case glslang::EOpSubgroupBallot:
4738 case glslang::EOpSubgroupInverseBallot:
4739 case glslang::EOpSubgroupBallotBitCount:
4740 case glslang::EOpSubgroupBallotInclusiveBitCount:
4741 case glslang::EOpSubgroupBallotExclusiveBitCount:
4742 case glslang::EOpSubgroupBallotFindLSB:
4743 case glslang::EOpSubgroupBallotFindMSB:
4744 case glslang::EOpSubgroupAdd:
4745 case glslang::EOpSubgroupMul:
4746 case glslang::EOpSubgroupMin:
4747 case glslang::EOpSubgroupMax:
4748 case glslang::EOpSubgroupAnd:
4749 case glslang::EOpSubgroupOr:
4750 case glslang::EOpSubgroupXor:
4751 case glslang::EOpSubgroupInclusiveAdd:
4752 case glslang::EOpSubgroupInclusiveMul:
4753 case glslang::EOpSubgroupInclusiveMin:
4754 case glslang::EOpSubgroupInclusiveMax:
4755 case glslang::EOpSubgroupInclusiveAnd:
4756 case glslang::EOpSubgroupInclusiveOr:
4757 case glslang::EOpSubgroupInclusiveXor:
4758 case glslang::EOpSubgroupExclusiveAdd:
4759 case glslang::EOpSubgroupExclusiveMul:
4760 case glslang::EOpSubgroupExclusiveMin:
4761 case glslang::EOpSubgroupExclusiveMax:
4762 case glslang::EOpSubgroupExclusiveAnd:
4763 case glslang::EOpSubgroupExclusiveOr:
4764 case glslang::EOpSubgroupExclusiveXor:
4765 case glslang::EOpSubgroupQuadSwapHorizontal:
4766 case glslang::EOpSubgroupQuadSwapVertical:
4767 case glslang::EOpSubgroupQuadSwapDiagonal: {
4768 std::vector<spv::Id> operands;
4769 operands.push_back(operand);
4770 return createSubgroupOperation(op, typeId, operands, typeProxy);
4771 }
Rex Xu9d93a232016-05-05 12:30:44 +08004772#ifdef AMD_EXTENSIONS
4773 case glslang::EOpMbcnt:
4774 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4775 libCall = spv::MbcntAMD;
4776 break;
4777
4778 case glslang::EOpCubeFaceIndex:
4779 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4780 libCall = spv::CubeFaceIndexAMD;
4781 break;
4782
4783 case glslang::EOpCubeFaceCoord:
4784 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4785 libCall = spv::CubeFaceCoordAMD;
4786 break;
4787#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05004788#ifdef NV_EXTENSIONS
4789 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05004790 unaryOp = spv::OpGroupNonUniformPartitionNV;
4791 break;
4792#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004793 default:
4794 return 0;
4795 }
4796
4797 spv::Id id;
4798 if (libCall >= 0) {
4799 std::vector<spv::Id> args;
4800 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004801 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004802 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004803 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004804 }
John Kessenich140f3df2015-06-26 16:58:36 -06004805
John Kessenichead86222018-03-28 18:01:20 -06004806 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004807 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004808 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004809}
4810
John Kessenich7a53f762016-01-20 11:19:27 -07004811// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06004812spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4813 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07004814{
4815 // Handle unary operations vector by vector.
4816 // The result type is the same type as the original type.
4817 // The algorithm is to:
4818 // - break the matrix into vectors
4819 // - apply the operation to each vector
4820 // - make a matrix out the vector results
4821
4822 // get the types sorted out
4823 int numCols = builder.getNumColumns(operand);
4824 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004825 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4826 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004827 std::vector<spv::Id> results;
4828
4829 // do each vector op
4830 for (int c = 0; c < numCols; ++c) {
4831 std::vector<unsigned int> indexes;
4832 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004833 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4834 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06004835 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004836 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004837 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004838 }
4839
4840 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004841 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004842 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004843 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07004844}
4845
John Kessenichad7645f2018-06-04 19:11:25 -06004846// For converting integers where both the bitwidth and the signedness could
4847// change, but only do the width change here. The caller is still responsible
4848// for the signedness conversion.
4849spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07004850{
John Kessenichad7645f2018-06-04 19:11:25 -06004851 // Get the result type width, based on the type to convert to.
4852 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07004853 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06004854 case glslang::EOpConvInt16ToUint8:
4855 case glslang::EOpConvIntToUint8:
4856 case glslang::EOpConvInt64ToUint8:
4857 case glslang::EOpConvUint16ToInt8:
4858 case glslang::EOpConvUintToInt8:
4859 case glslang::EOpConvUint64ToInt8:
4860 width = 8;
4861 break;
John Kessenich66011cb2018-03-06 16:12:04 -07004862 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06004863 case glslang::EOpConvIntToUint16:
4864 case glslang::EOpConvInt64ToUint16:
4865 case glslang::EOpConvUint8ToInt16:
4866 case glslang::EOpConvUintToInt16:
4867 case glslang::EOpConvUint64ToInt16:
4868 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07004869 break;
4870 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06004871 case glslang::EOpConvInt16ToUint:
4872 case glslang::EOpConvInt64ToUint:
4873 case glslang::EOpConvUint8ToInt:
4874 case glslang::EOpConvUint16ToInt:
4875 case glslang::EOpConvUint64ToInt:
4876 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07004877 break;
4878 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07004879 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07004880 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07004881 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07004882 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07004883 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06004884 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07004885 break;
4886
4887 default:
4888 assert(false && "Default missing");
4889 break;
4890 }
4891
John Kessenichad7645f2018-06-04 19:11:25 -06004892 // Get the conversion operation and result type,
4893 // based on the target width, but the source type.
4894 spv::Id type = spv::NoType;
4895 spv::Op convOp = spv::OpNop;
4896 switch(op) {
4897 case glslang::EOpConvInt8ToUint16:
4898 case glslang::EOpConvInt8ToUint:
4899 case glslang::EOpConvInt8ToUint64:
4900 case glslang::EOpConvInt16ToUint8:
4901 case glslang::EOpConvInt16ToUint:
4902 case glslang::EOpConvInt16ToUint64:
4903 case glslang::EOpConvIntToUint8:
4904 case glslang::EOpConvIntToUint16:
4905 case glslang::EOpConvIntToUint64:
4906 case glslang::EOpConvInt64ToUint8:
4907 case glslang::EOpConvInt64ToUint16:
4908 case glslang::EOpConvInt64ToUint:
4909 convOp = spv::OpSConvert;
4910 type = builder.makeIntType(width);
4911 break;
4912 default:
4913 convOp = spv::OpUConvert;
4914 type = builder.makeUintType(width);
4915 break;
4916 }
4917
John Kessenich66011cb2018-03-06 16:12:04 -07004918 if (vectorSize > 0)
4919 type = builder.makeVectorType(type, vectorSize);
4920
John Kessenichad7645f2018-06-04 19:11:25 -06004921 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07004922}
4923
John Kessenichead86222018-03-28 18:01:20 -06004924spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
4925 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004926{
4927 spv::Op convOp = spv::OpNop;
4928 spv::Id zero = 0;
4929 spv::Id one = 0;
4930
4931 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4932
4933 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07004934 case glslang::EOpConvInt8ToBool:
4935 case glslang::EOpConvUint8ToBool:
4936 zero = builder.makeUint8Constant(0);
4937 zero = makeSmearedConstant(zero, vectorSize);
4938 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08004939 case glslang::EOpConvInt16ToBool:
4940 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07004941 zero = builder.makeUint16Constant(0);
4942 zero = makeSmearedConstant(zero, vectorSize);
4943 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4944 case glslang::EOpConvIntToBool:
4945 case glslang::EOpConvUintToBool:
4946 zero = builder.makeUintConstant(0);
4947 zero = makeSmearedConstant(zero, vectorSize);
4948 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4949 case glslang::EOpConvInt64ToBool:
4950 case glslang::EOpConvUint64ToBool:
4951 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004952 zero = makeSmearedConstant(zero, vectorSize);
4953 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4954
4955 case glslang::EOpConvFloatToBool:
4956 zero = builder.makeFloatConstant(0.0F);
4957 zero = makeSmearedConstant(zero, vectorSize);
4958 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4959
4960 case glslang::EOpConvDoubleToBool:
4961 zero = builder.makeDoubleConstant(0.0);
4962 zero = makeSmearedConstant(zero, vectorSize);
4963 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4964
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004965 case glslang::EOpConvFloat16ToBool:
4966 zero = builder.makeFloat16Constant(0.0F);
4967 zero = makeSmearedConstant(zero, vectorSize);
4968 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004969
John Kessenich140f3df2015-06-26 16:58:36 -06004970 case glslang::EOpConvBoolToFloat:
4971 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004972 zero = builder.makeFloatConstant(0.0F);
4973 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004974 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004975
John Kessenich140f3df2015-06-26 16:58:36 -06004976 case glslang::EOpConvBoolToDouble:
4977 convOp = spv::OpSelect;
4978 zero = builder.makeDoubleConstant(0.0);
4979 one = builder.makeDoubleConstant(1.0);
4980 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004981
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004982 case glslang::EOpConvBoolToFloat16:
4983 convOp = spv::OpSelect;
4984 zero = builder.makeFloat16Constant(0.0F);
4985 one = builder.makeFloat16Constant(1.0F);
4986 break;
John Kessenich66011cb2018-03-06 16:12:04 -07004987
4988 case glslang::EOpConvBoolToInt8:
4989 zero = builder.makeInt8Constant(0);
4990 one = builder.makeInt8Constant(1);
4991 convOp = spv::OpSelect;
4992 break;
4993
4994 case glslang::EOpConvBoolToUint8:
4995 zero = builder.makeUint8Constant(0);
4996 one = builder.makeUint8Constant(1);
4997 convOp = spv::OpSelect;
4998 break;
4999
5000 case glslang::EOpConvBoolToInt16:
5001 zero = builder.makeInt16Constant(0);
5002 one = builder.makeInt16Constant(1);
5003 convOp = spv::OpSelect;
5004 break;
5005
5006 case glslang::EOpConvBoolToUint16:
5007 zero = builder.makeUint16Constant(0);
5008 one = builder.makeUint16Constant(1);
5009 convOp = spv::OpSelect;
5010 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005011
John Kessenich140f3df2015-06-26 16:58:36 -06005012 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005013 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005014 if (op == glslang::EOpConvBoolToInt64)
5015 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005016 else
5017 zero = builder.makeIntConstant(0);
5018
5019 if (op == glslang::EOpConvBoolToInt64)
5020 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005021 else
5022 one = builder.makeIntConstant(1);
5023
John Kessenich140f3df2015-06-26 16:58:36 -06005024 convOp = spv::OpSelect;
5025 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005026
John Kessenich140f3df2015-06-26 16:58:36 -06005027 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005028 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005029 if (op == glslang::EOpConvBoolToUint64)
5030 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005031 else
5032 zero = builder.makeUintConstant(0);
5033
5034 if (op == glslang::EOpConvBoolToUint64)
5035 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005036 else
5037 one = builder.makeUintConstant(1);
5038
John Kessenich140f3df2015-06-26 16:58:36 -06005039 convOp = spv::OpSelect;
5040 break;
5041
John Kessenich66011cb2018-03-06 16:12:04 -07005042 case glslang::EOpConvInt8ToFloat16:
5043 case glslang::EOpConvInt8ToFloat:
5044 case glslang::EOpConvInt8ToDouble:
5045 case glslang::EOpConvInt16ToFloat16:
5046 case glslang::EOpConvInt16ToFloat:
5047 case glslang::EOpConvInt16ToDouble:
5048 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005049 case glslang::EOpConvIntToFloat:
5050 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005051 case glslang::EOpConvInt64ToFloat:
5052 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005053 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005054 convOp = spv::OpConvertSToF;
5055 break;
5056
John Kessenich66011cb2018-03-06 16:12:04 -07005057 case glslang::EOpConvUint8ToFloat16:
5058 case glslang::EOpConvUint8ToFloat:
5059 case glslang::EOpConvUint8ToDouble:
5060 case glslang::EOpConvUint16ToFloat16:
5061 case glslang::EOpConvUint16ToFloat:
5062 case glslang::EOpConvUint16ToDouble:
5063 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005064 case glslang::EOpConvUintToFloat:
5065 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005066 case glslang::EOpConvUint64ToFloat:
5067 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005068 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005069 convOp = spv::OpConvertUToF;
5070 break;
5071
5072 case glslang::EOpConvDoubleToFloat:
5073 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005074 case glslang::EOpConvDoubleToFloat16:
5075 case glslang::EOpConvFloat16ToDouble:
5076 case glslang::EOpConvFloatToFloat16:
5077 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005078 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005079 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005080 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005081 break;
5082
John Kessenich66011cb2018-03-06 16:12:04 -07005083 case glslang::EOpConvFloat16ToInt8:
5084 case glslang::EOpConvFloatToInt8:
5085 case glslang::EOpConvDoubleToInt8:
5086 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005087 case glslang::EOpConvFloatToInt16:
5088 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005089 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005090 case glslang::EOpConvFloatToInt:
5091 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005092 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005093 case glslang::EOpConvFloatToInt64:
5094 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005095 convOp = spv::OpConvertFToS;
5096 break;
5097
John Kessenich66011cb2018-03-06 16:12:04 -07005098 case glslang::EOpConvUint8ToInt8:
5099 case glslang::EOpConvInt8ToUint8:
5100 case glslang::EOpConvUint16ToInt16:
5101 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005102 case glslang::EOpConvUintToInt:
5103 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005104 case glslang::EOpConvUint64ToInt64:
5105 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005106 if (builder.isInSpecConstCodeGenMode()) {
5107 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005108 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5109 zero = builder.makeUint8Constant(0);
5110 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005111 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005112 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5113 zero = builder.makeUint64Constant(0);
5114 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005115 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005116 }
qining189b2032016-04-12 23:16:20 -04005117 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005118 // Use OpIAdd, instead of OpBitcast to do the conversion when
5119 // generating for OpSpecConstantOp instruction.
5120 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5121 }
5122 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005123 convOp = spv::OpBitcast;
5124 break;
5125
John Kessenich66011cb2018-03-06 16:12:04 -07005126 case glslang::EOpConvFloat16ToUint8:
5127 case glslang::EOpConvFloatToUint8:
5128 case glslang::EOpConvDoubleToUint8:
5129 case glslang::EOpConvFloat16ToUint16:
5130 case glslang::EOpConvFloatToUint16:
5131 case glslang::EOpConvDoubleToUint16:
5132 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005133 case glslang::EOpConvFloatToUint:
5134 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005135 case glslang::EOpConvFloatToUint64:
5136 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005137 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005138 convOp = spv::OpConvertFToU;
5139 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005140
John Kessenich66011cb2018-03-06 16:12:04 -07005141 case glslang::EOpConvInt8ToInt16:
5142 case glslang::EOpConvInt8ToInt:
5143 case glslang::EOpConvInt8ToInt64:
5144 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005145 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005146 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005147 case glslang::EOpConvIntToInt8:
5148 case glslang::EOpConvIntToInt16:
5149 case glslang::EOpConvIntToInt64:
5150 case glslang::EOpConvInt64ToInt8:
5151 case glslang::EOpConvInt64ToInt16:
5152 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005153 convOp = spv::OpSConvert;
5154 break;
5155
John Kessenich66011cb2018-03-06 16:12:04 -07005156 case glslang::EOpConvUint8ToUint16:
5157 case glslang::EOpConvUint8ToUint:
5158 case glslang::EOpConvUint8ToUint64:
5159 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005160 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005161 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005162 case glslang::EOpConvUintToUint8:
5163 case glslang::EOpConvUintToUint16:
5164 case glslang::EOpConvUintToUint64:
5165 case glslang::EOpConvUint64ToUint8:
5166 case glslang::EOpConvUint64ToUint16:
5167 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005168 convOp = spv::OpUConvert;
5169 break;
5170
John Kessenich66011cb2018-03-06 16:12:04 -07005171 case glslang::EOpConvInt8ToUint16:
5172 case glslang::EOpConvInt8ToUint:
5173 case glslang::EOpConvInt8ToUint64:
5174 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005175 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005176 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005177 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005178 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005179 case glslang::EOpConvIntToUint64:
5180 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005181 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005182 case glslang::EOpConvInt64ToUint:
5183 case glslang::EOpConvUint8ToInt16:
5184 case glslang::EOpConvUint8ToInt:
5185 case glslang::EOpConvUint8ToInt64:
5186 case glslang::EOpConvUint16ToInt8:
5187 case glslang::EOpConvUint16ToInt:
5188 case glslang::EOpConvUint16ToInt64:
5189 case glslang::EOpConvUintToInt8:
5190 case glslang::EOpConvUintToInt16:
5191 case glslang::EOpConvUintToInt64:
5192 case glslang::EOpConvUint64ToInt8:
5193 case glslang::EOpConvUint64ToInt16:
5194 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005195 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005196 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005197
5198 if (builder.isInSpecConstCodeGenMode()) {
5199 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005200 switch(op) {
5201 case glslang::EOpConvInt16ToUint8:
5202 case glslang::EOpConvIntToUint8:
5203 case glslang::EOpConvInt64ToUint8:
5204 case glslang::EOpConvUint16ToInt8:
5205 case glslang::EOpConvUintToInt8:
5206 case glslang::EOpConvUint64ToInt8:
5207 zero = builder.makeUint8Constant(0);
5208 break;
5209 case glslang::EOpConvInt8ToUint16:
5210 case glslang::EOpConvIntToUint16:
5211 case glslang::EOpConvInt64ToUint16:
5212 case glslang::EOpConvUint8ToInt16:
5213 case glslang::EOpConvUintToInt16:
5214 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005215 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005216 break;
5217 case glslang::EOpConvInt8ToUint:
5218 case glslang::EOpConvInt16ToUint:
5219 case glslang::EOpConvInt64ToUint:
5220 case glslang::EOpConvUint8ToInt:
5221 case glslang::EOpConvUint16ToInt:
5222 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005223 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005224 break;
5225 case glslang::EOpConvInt8ToUint64:
5226 case glslang::EOpConvInt16ToUint64:
5227 case glslang::EOpConvIntToUint64:
5228 case glslang::EOpConvUint8ToInt64:
5229 case glslang::EOpConvUint16ToInt64:
5230 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005231 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005232 break;
5233 default:
5234 assert(false && "Default missing");
5235 break;
5236 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005237 zero = makeSmearedConstant(zero, vectorSize);
5238 // Use OpIAdd, instead of OpBitcast to do the conversion when
5239 // generating for OpSpecConstantOp instruction.
5240 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5241 }
5242 // For normal run-time conversion instruction, use OpBitcast.
5243 convOp = spv::OpBitcast;
5244 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005245 default:
5246 break;
5247 }
5248
5249 spv::Id result = 0;
5250 if (convOp == spv::OpNop)
5251 return result;
5252
5253 if (convOp == spv::OpSelect) {
5254 zero = makeSmearedConstant(zero, vectorSize);
5255 one = makeSmearedConstant(one, vectorSize);
5256 result = builder.createTriOp(convOp, destType, operand, one, zero);
5257 } else
5258 result = builder.createUnaryOp(convOp, destType, operand);
5259
John Kessenichead86222018-03-28 18:01:20 -06005260 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005261 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005262 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06005263}
5264
5265spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
5266{
5267 if (vectorSize == 0)
5268 return constant;
5269
5270 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
5271 std::vector<spv::Id> components;
5272 for (int c = 0; c < vectorSize; ++c)
5273 components.push_back(constant);
5274 return builder.makeCompositeConstant(vectorTypeId, components);
5275}
5276
John Kessenich426394d2015-07-23 10:22:48 -06005277// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07005278spv::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 -06005279{
5280 spv::Op opCode = spv::OpNop;
5281
5282 switch (op) {
5283 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08005284 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005285 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06005286 opCode = spv::OpAtomicIAdd;
5287 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06005288 case glslang::EOpAtomicCounterSubtract:
5289 opCode = spv::OpAtomicISub;
5290 break;
John Kessenich426394d2015-07-23 10:22:48 -06005291 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08005292 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005293 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08005294 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06005295 break;
5296 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08005297 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005298 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08005299 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06005300 break;
5301 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08005302 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005303 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06005304 opCode = spv::OpAtomicAnd;
5305 break;
5306 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08005307 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005308 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06005309 opCode = spv::OpAtomicOr;
5310 break;
5311 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08005312 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005313 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06005314 opCode = spv::OpAtomicXor;
5315 break;
5316 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08005317 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005318 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06005319 opCode = spv::OpAtomicExchange;
5320 break;
5321 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08005322 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005323 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06005324 opCode = spv::OpAtomicCompareExchange;
5325 break;
5326 case glslang::EOpAtomicCounterIncrement:
5327 opCode = spv::OpAtomicIIncrement;
5328 break;
5329 case glslang::EOpAtomicCounterDecrement:
5330 opCode = spv::OpAtomicIDecrement;
5331 break;
5332 case glslang::EOpAtomicCounter:
5333 opCode = spv::OpAtomicLoad;
5334 break;
5335 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005336 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06005337 break;
5338 }
5339
Rex Xue8fe8b02017-09-26 15:42:56 +08005340 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
5341 builder.addCapability(spv::CapabilityInt64Atomics);
5342
John Kessenich426394d2015-07-23 10:22:48 -06005343 // Sort out the operands
5344 // - mapping from glslang -> SPV
5345 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06005346 // - compare-exchange swaps the value and comparator
5347 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06005348 // - EOpAtomicCounterDecrement needs a post decrement
John Kessenich426394d2015-07-23 10:22:48 -06005349 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
5350 auto opIt = operands.begin(); // walk the glslang operands
5351 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08005352 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
5353 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
5354 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08005355 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
5356 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08005357 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06005358 spvAtomicOperands.push_back(*(opIt + 1));
5359 spvAtomicOperands.push_back(*opIt);
5360 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08005361 }
John Kessenich426394d2015-07-23 10:22:48 -06005362
John Kessenich3e60a6f2015-09-14 22:45:16 -06005363 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06005364 for (; opIt != operands.end(); ++opIt)
5365 spvAtomicOperands.push_back(*opIt);
5366
John Kessenich48d6e792017-10-06 21:21:48 -06005367 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
5368
5369 // GLSL and HLSL atomic-counter decrement return post-decrement value,
5370 // while SPIR-V returns pre-decrement value. Translate between these semantics.
5371 if (op == glslang::EOpAtomicCounterDecrement)
5372 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
5373
5374 return resultId;
John Kessenich426394d2015-07-23 10:22:48 -06005375}
5376
John Kessenich91cef522016-05-05 16:45:40 -06005377// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08005378spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06005379{
John Kessenich66011cb2018-03-06 16:12:04 -07005380 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5381 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08005382
Rex Xu51596642016-09-21 18:56:12 +08005383 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08005384 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08005385 spv::GroupOperation groupOperation = spv::GroupOperationMax;
5386
chaocf200da82016-12-20 12:44:35 -08005387 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
5388 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08005389 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
5390 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005391 } else if (op == glslang::EOpAnyInvocation ||
5392 op == glslang::EOpAllInvocations ||
5393 op == glslang::EOpAllInvocationsEqual) {
5394 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
5395 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08005396 } else {
5397 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04005398#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08005399 if (op == glslang::EOpMinInvocationsNonUniform ||
5400 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08005401 op == glslang::EOpAddInvocationsNonUniform ||
5402 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5403 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5404 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
5405 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
5406 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
5407 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08005408 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04005409#endif
Rex Xu51596642016-09-21 18:56:12 +08005410
5411 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08005412#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08005413 switch (op) {
5414 case glslang::EOpMinInvocations:
5415 case glslang::EOpMaxInvocations:
5416 case glslang::EOpAddInvocations:
5417 case glslang::EOpMinInvocationsNonUniform:
5418 case glslang::EOpMaxInvocationsNonUniform:
5419 case glslang::EOpAddInvocationsNonUniform:
5420 groupOperation = spv::GroupOperationReduce;
5421 spvGroupOperands.push_back(groupOperation);
5422 break;
5423 case glslang::EOpMinInvocationsInclusiveScan:
5424 case glslang::EOpMaxInvocationsInclusiveScan:
5425 case glslang::EOpAddInvocationsInclusiveScan:
5426 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5427 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5428 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5429 groupOperation = spv::GroupOperationInclusiveScan;
5430 spvGroupOperands.push_back(groupOperation);
5431 break;
5432 case glslang::EOpMinInvocationsExclusiveScan:
5433 case glslang::EOpMaxInvocationsExclusiveScan:
5434 case glslang::EOpAddInvocationsExclusiveScan:
5435 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5436 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5437 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5438 groupOperation = spv::GroupOperationExclusiveScan;
5439 spvGroupOperands.push_back(groupOperation);
5440 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07005441 default:
5442 break;
Rex Xu430ef402016-10-14 17:22:23 +08005443 }
Rex Xu9d93a232016-05-05 12:30:44 +08005444#endif
Rex Xu51596642016-09-21 18:56:12 +08005445 }
5446
5447 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
5448 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06005449
5450 switch (op) {
5451 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005452 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08005453 break;
John Kessenich91cef522016-05-05 16:45:40 -06005454 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005455 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08005456 break;
John Kessenich91cef522016-05-05 16:45:40 -06005457 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005458 opCode = spv::OpSubgroupAllEqualKHR;
5459 break;
Rex Xu51596642016-09-21 18:56:12 +08005460 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08005461 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08005462 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005463 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005464 break;
5465 case glslang::EOpReadFirstInvocation:
5466 opCode = spv::OpSubgroupFirstInvocationKHR;
5467 break;
5468 case glslang::EOpBallot:
5469 {
5470 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
5471 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
5472 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
5473 //
5474 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
5475 //
5476 spv::Id uintType = builder.makeUintType(32);
5477 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
5478 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
5479
5480 std::vector<spv::Id> components;
5481 components.push_back(builder.createCompositeExtract(result, uintType, 0));
5482 components.push_back(builder.createCompositeExtract(result, uintType, 1));
5483
5484 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
5485 return builder.createUnaryOp(spv::OpBitcast, typeId,
5486 builder.createCompositeConstruct(uvec2Type, components));
5487 }
5488
Rex Xu9d93a232016-05-05 12:30:44 +08005489#ifdef AMD_EXTENSIONS
5490 case glslang::EOpMinInvocations:
5491 case glslang::EOpMaxInvocations:
5492 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08005493 case glslang::EOpMinInvocationsInclusiveScan:
5494 case glslang::EOpMaxInvocationsInclusiveScan:
5495 case glslang::EOpAddInvocationsInclusiveScan:
5496 case glslang::EOpMinInvocationsExclusiveScan:
5497 case glslang::EOpMaxInvocationsExclusiveScan:
5498 case glslang::EOpAddInvocationsExclusiveScan:
5499 if (op == glslang::EOpMinInvocations ||
5500 op == glslang::EOpMinInvocationsInclusiveScan ||
5501 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005502 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005503 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005504 else {
5505 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005506 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005507 else
Rex Xu51596642016-09-21 18:56:12 +08005508 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005509 }
Rex Xu430ef402016-10-14 17:22:23 +08005510 } else if (op == glslang::EOpMaxInvocations ||
5511 op == glslang::EOpMaxInvocationsInclusiveScan ||
5512 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005513 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005514 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005515 else {
5516 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005517 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005518 else
Rex Xu51596642016-09-21 18:56:12 +08005519 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005520 }
5521 } else {
5522 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005523 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005524 else
Rex Xu51596642016-09-21 18:56:12 +08005525 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005526 }
5527
Rex Xu2bbbe062016-08-23 15:41:05 +08005528 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005529 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005530
5531 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005532 case glslang::EOpMinInvocationsNonUniform:
5533 case glslang::EOpMaxInvocationsNonUniform:
5534 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005535 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5536 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5537 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5538 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5539 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5540 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5541 if (op == glslang::EOpMinInvocationsNonUniform ||
5542 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5543 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005544 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005545 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005546 else {
5547 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005548 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005549 else
Rex Xu51596642016-09-21 18:56:12 +08005550 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005551 }
5552 }
Rex Xu430ef402016-10-14 17:22:23 +08005553 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5554 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5555 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005556 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005557 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005558 else {
5559 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005560 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005561 else
Rex Xu51596642016-09-21 18:56:12 +08005562 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005563 }
5564 }
5565 else {
5566 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005567 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005568 else
Rex Xu51596642016-09-21 18:56:12 +08005569 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005570 }
5571
Rex Xu2bbbe062016-08-23 15:41:05 +08005572 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005573 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005574
5575 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005576#endif
John Kessenich91cef522016-05-05 16:45:40 -06005577 default:
5578 logger->missingFunctionality("invocation operation");
5579 return spv::NoResult;
5580 }
Rex Xu51596642016-09-21 18:56:12 +08005581
5582 assert(opCode != spv::OpNop);
5583 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005584}
5585
Rex Xu2bbbe062016-08-23 15:41:05 +08005586// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005587spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005588{
Rex Xub7072052016-09-26 15:53:40 +08005589#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005590 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5591 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005592 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005593 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005594 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5595 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5596 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005597#else
5598 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5599 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005600 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5601 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005602#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005603
5604 // Handle group invocation operations scalar by scalar.
5605 // The result type is the same type as the original type.
5606 // The algorithm is to:
5607 // - break the vector into scalars
5608 // - apply the operation to each scalar
5609 // - make a vector out the scalar results
5610
5611 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005612 int numComponents = builder.getNumComponents(operands[0]);
5613 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005614 std::vector<spv::Id> results;
5615
5616 // do each scalar op
5617 for (int comp = 0; comp < numComponents; ++comp) {
5618 std::vector<unsigned int> indexes;
5619 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005620 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005621 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005622 if (op == spv::OpSubgroupReadInvocationKHR) {
5623 spvGroupOperands.push_back(scalar);
5624 spvGroupOperands.push_back(operands[1]);
5625 } else if (op == spv::OpGroupBroadcast) {
5626 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005627 spvGroupOperands.push_back(scalar);
5628 spvGroupOperands.push_back(operands[1]);
5629 } else {
chaocf200da82016-12-20 12:44:35 -08005630 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005631 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005632 spvGroupOperands.push_back(scalar);
5633 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005634
Rex Xub7072052016-09-26 15:53:40 +08005635 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005636 }
5637
5638 // put the pieces together
5639 return builder.createCompositeConstruct(typeId, results);
5640}
Rex Xu2bbbe062016-08-23 15:41:05 +08005641
John Kessenich66011cb2018-03-06 16:12:04 -07005642// Create subgroup invocation operations.
5643spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
5644{
5645 // Add the required capabilities.
5646 switch (op) {
5647 case glslang::EOpSubgroupElect:
5648 builder.addCapability(spv::CapabilityGroupNonUniform);
5649 break;
5650 case glslang::EOpSubgroupAll:
5651 case glslang::EOpSubgroupAny:
5652 case glslang::EOpSubgroupAllEqual:
5653 builder.addCapability(spv::CapabilityGroupNonUniform);
5654 builder.addCapability(spv::CapabilityGroupNonUniformVote);
5655 break;
5656 case glslang::EOpSubgroupBroadcast:
5657 case glslang::EOpSubgroupBroadcastFirst:
5658 case glslang::EOpSubgroupBallot:
5659 case glslang::EOpSubgroupInverseBallot:
5660 case glslang::EOpSubgroupBallotBitExtract:
5661 case glslang::EOpSubgroupBallotBitCount:
5662 case glslang::EOpSubgroupBallotInclusiveBitCount:
5663 case glslang::EOpSubgroupBallotExclusiveBitCount:
5664 case glslang::EOpSubgroupBallotFindLSB:
5665 case glslang::EOpSubgroupBallotFindMSB:
5666 builder.addCapability(spv::CapabilityGroupNonUniform);
5667 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
5668 break;
5669 case glslang::EOpSubgroupShuffle:
5670 case glslang::EOpSubgroupShuffleXor:
5671 builder.addCapability(spv::CapabilityGroupNonUniform);
5672 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
5673 break;
5674 case glslang::EOpSubgroupShuffleUp:
5675 case glslang::EOpSubgroupShuffleDown:
5676 builder.addCapability(spv::CapabilityGroupNonUniform);
5677 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
5678 break;
5679 case glslang::EOpSubgroupAdd:
5680 case glslang::EOpSubgroupMul:
5681 case glslang::EOpSubgroupMin:
5682 case glslang::EOpSubgroupMax:
5683 case glslang::EOpSubgroupAnd:
5684 case glslang::EOpSubgroupOr:
5685 case glslang::EOpSubgroupXor:
5686 case glslang::EOpSubgroupInclusiveAdd:
5687 case glslang::EOpSubgroupInclusiveMul:
5688 case glslang::EOpSubgroupInclusiveMin:
5689 case glslang::EOpSubgroupInclusiveMax:
5690 case glslang::EOpSubgroupInclusiveAnd:
5691 case glslang::EOpSubgroupInclusiveOr:
5692 case glslang::EOpSubgroupInclusiveXor:
5693 case glslang::EOpSubgroupExclusiveAdd:
5694 case glslang::EOpSubgroupExclusiveMul:
5695 case glslang::EOpSubgroupExclusiveMin:
5696 case glslang::EOpSubgroupExclusiveMax:
5697 case glslang::EOpSubgroupExclusiveAnd:
5698 case glslang::EOpSubgroupExclusiveOr:
5699 case glslang::EOpSubgroupExclusiveXor:
5700 builder.addCapability(spv::CapabilityGroupNonUniform);
5701 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
5702 break;
5703 case glslang::EOpSubgroupClusteredAdd:
5704 case glslang::EOpSubgroupClusteredMul:
5705 case glslang::EOpSubgroupClusteredMin:
5706 case glslang::EOpSubgroupClusteredMax:
5707 case glslang::EOpSubgroupClusteredAnd:
5708 case glslang::EOpSubgroupClusteredOr:
5709 case glslang::EOpSubgroupClusteredXor:
5710 builder.addCapability(spv::CapabilityGroupNonUniform);
5711 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
5712 break;
5713 case glslang::EOpSubgroupQuadBroadcast:
5714 case glslang::EOpSubgroupQuadSwapHorizontal:
5715 case glslang::EOpSubgroupQuadSwapVertical:
5716 case glslang::EOpSubgroupQuadSwapDiagonal:
5717 builder.addCapability(spv::CapabilityGroupNonUniform);
5718 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
5719 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005720#ifdef NV_EXTENSIONS
5721 case glslang::EOpSubgroupPartitionedAdd:
5722 case glslang::EOpSubgroupPartitionedMul:
5723 case glslang::EOpSubgroupPartitionedMin:
5724 case glslang::EOpSubgroupPartitionedMax:
5725 case glslang::EOpSubgroupPartitionedAnd:
5726 case glslang::EOpSubgroupPartitionedOr:
5727 case glslang::EOpSubgroupPartitionedXor:
5728 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5729 case glslang::EOpSubgroupPartitionedInclusiveMul:
5730 case glslang::EOpSubgroupPartitionedInclusiveMin:
5731 case glslang::EOpSubgroupPartitionedInclusiveMax:
5732 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5733 case glslang::EOpSubgroupPartitionedInclusiveOr:
5734 case glslang::EOpSubgroupPartitionedInclusiveXor:
5735 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5736 case glslang::EOpSubgroupPartitionedExclusiveMul:
5737 case glslang::EOpSubgroupPartitionedExclusiveMin:
5738 case glslang::EOpSubgroupPartitionedExclusiveMax:
5739 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5740 case glslang::EOpSubgroupPartitionedExclusiveOr:
5741 case glslang::EOpSubgroupPartitionedExclusiveXor:
5742 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
5743 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
5744 break;
5745#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005746 default: assert(0 && "Unhandled subgroup operation!");
5747 }
5748
5749 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
5750 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
5751 const bool isBool = typeProxy == glslang::EbtBool;
5752
5753 spv::Op opCode = spv::OpNop;
5754
5755 // Figure out which opcode to use.
5756 switch (op) {
5757 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
5758 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
5759 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
5760 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
5761 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
5762 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
5763 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
5764 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
5765 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
5766 case glslang::EOpSubgroupBallotBitCount:
5767 case glslang::EOpSubgroupBallotInclusiveBitCount:
5768 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
5769 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
5770 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
5771 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
5772 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
5773 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
5774 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
5775 case glslang::EOpSubgroupAdd:
5776 case glslang::EOpSubgroupInclusiveAdd:
5777 case glslang::EOpSubgroupExclusiveAdd:
5778 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005779#ifdef NV_EXTENSIONS
5780 case glslang::EOpSubgroupPartitionedAdd:
5781 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5782 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5783#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005784 if (isFloat) {
5785 opCode = spv::OpGroupNonUniformFAdd;
5786 } else {
5787 opCode = spv::OpGroupNonUniformIAdd;
5788 }
5789 break;
5790 case glslang::EOpSubgroupMul:
5791 case glslang::EOpSubgroupInclusiveMul:
5792 case glslang::EOpSubgroupExclusiveMul:
5793 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005794#ifdef NV_EXTENSIONS
5795 case glslang::EOpSubgroupPartitionedMul:
5796 case glslang::EOpSubgroupPartitionedInclusiveMul:
5797 case glslang::EOpSubgroupPartitionedExclusiveMul:
5798#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005799 if (isFloat) {
5800 opCode = spv::OpGroupNonUniformFMul;
5801 } else {
5802 opCode = spv::OpGroupNonUniformIMul;
5803 }
5804 break;
5805 case glslang::EOpSubgroupMin:
5806 case glslang::EOpSubgroupInclusiveMin:
5807 case glslang::EOpSubgroupExclusiveMin:
5808 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005809#ifdef NV_EXTENSIONS
5810 case glslang::EOpSubgroupPartitionedMin:
5811 case glslang::EOpSubgroupPartitionedInclusiveMin:
5812 case glslang::EOpSubgroupPartitionedExclusiveMin:
5813#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005814 if (isFloat) {
5815 opCode = spv::OpGroupNonUniformFMin;
5816 } else if (isUnsigned) {
5817 opCode = spv::OpGroupNonUniformUMin;
5818 } else {
5819 opCode = spv::OpGroupNonUniformSMin;
5820 }
5821 break;
5822 case glslang::EOpSubgroupMax:
5823 case glslang::EOpSubgroupInclusiveMax:
5824 case glslang::EOpSubgroupExclusiveMax:
5825 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005826#ifdef NV_EXTENSIONS
5827 case glslang::EOpSubgroupPartitionedMax:
5828 case glslang::EOpSubgroupPartitionedInclusiveMax:
5829 case glslang::EOpSubgroupPartitionedExclusiveMax:
5830#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005831 if (isFloat) {
5832 opCode = spv::OpGroupNonUniformFMax;
5833 } else if (isUnsigned) {
5834 opCode = spv::OpGroupNonUniformUMax;
5835 } else {
5836 opCode = spv::OpGroupNonUniformSMax;
5837 }
5838 break;
5839 case glslang::EOpSubgroupAnd:
5840 case glslang::EOpSubgroupInclusiveAnd:
5841 case glslang::EOpSubgroupExclusiveAnd:
5842 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005843#ifdef NV_EXTENSIONS
5844 case glslang::EOpSubgroupPartitionedAnd:
5845 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5846 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5847#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005848 if (isBool) {
5849 opCode = spv::OpGroupNonUniformLogicalAnd;
5850 } else {
5851 opCode = spv::OpGroupNonUniformBitwiseAnd;
5852 }
5853 break;
5854 case glslang::EOpSubgroupOr:
5855 case glslang::EOpSubgroupInclusiveOr:
5856 case glslang::EOpSubgroupExclusiveOr:
5857 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005858#ifdef NV_EXTENSIONS
5859 case glslang::EOpSubgroupPartitionedOr:
5860 case glslang::EOpSubgroupPartitionedInclusiveOr:
5861 case glslang::EOpSubgroupPartitionedExclusiveOr:
5862#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005863 if (isBool) {
5864 opCode = spv::OpGroupNonUniformLogicalOr;
5865 } else {
5866 opCode = spv::OpGroupNonUniformBitwiseOr;
5867 }
5868 break;
5869 case glslang::EOpSubgroupXor:
5870 case glslang::EOpSubgroupInclusiveXor:
5871 case glslang::EOpSubgroupExclusiveXor:
5872 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005873#ifdef NV_EXTENSIONS
5874 case glslang::EOpSubgroupPartitionedXor:
5875 case glslang::EOpSubgroupPartitionedInclusiveXor:
5876 case glslang::EOpSubgroupPartitionedExclusiveXor:
5877#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005878 if (isBool) {
5879 opCode = spv::OpGroupNonUniformLogicalXor;
5880 } else {
5881 opCode = spv::OpGroupNonUniformBitwiseXor;
5882 }
5883 break;
5884 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
5885 case glslang::EOpSubgroupQuadSwapHorizontal:
5886 case glslang::EOpSubgroupQuadSwapVertical:
5887 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
5888 default: assert(0 && "Unhandled subgroup operation!");
5889 }
5890
5891 std::vector<spv::Id> spvGroupOperands;
5892
5893 // Every operation begins with the Execution Scope operand.
5894 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
5895
5896 // Next, for all operations that use a Group Operation, push that as an operand.
5897 switch (op) {
5898 default: break;
5899 case glslang::EOpSubgroupBallotBitCount:
5900 case glslang::EOpSubgroupAdd:
5901 case glslang::EOpSubgroupMul:
5902 case glslang::EOpSubgroupMin:
5903 case glslang::EOpSubgroupMax:
5904 case glslang::EOpSubgroupAnd:
5905 case glslang::EOpSubgroupOr:
5906 case glslang::EOpSubgroupXor:
5907 spvGroupOperands.push_back(spv::GroupOperationReduce);
5908 break;
5909 case glslang::EOpSubgroupBallotInclusiveBitCount:
5910 case glslang::EOpSubgroupInclusiveAdd:
5911 case glslang::EOpSubgroupInclusiveMul:
5912 case glslang::EOpSubgroupInclusiveMin:
5913 case glslang::EOpSubgroupInclusiveMax:
5914 case glslang::EOpSubgroupInclusiveAnd:
5915 case glslang::EOpSubgroupInclusiveOr:
5916 case glslang::EOpSubgroupInclusiveXor:
5917 spvGroupOperands.push_back(spv::GroupOperationInclusiveScan);
5918 break;
5919 case glslang::EOpSubgroupBallotExclusiveBitCount:
5920 case glslang::EOpSubgroupExclusiveAdd:
5921 case glslang::EOpSubgroupExclusiveMul:
5922 case glslang::EOpSubgroupExclusiveMin:
5923 case glslang::EOpSubgroupExclusiveMax:
5924 case glslang::EOpSubgroupExclusiveAnd:
5925 case glslang::EOpSubgroupExclusiveOr:
5926 case glslang::EOpSubgroupExclusiveXor:
5927 spvGroupOperands.push_back(spv::GroupOperationExclusiveScan);
5928 break;
5929 case glslang::EOpSubgroupClusteredAdd:
5930 case glslang::EOpSubgroupClusteredMul:
5931 case glslang::EOpSubgroupClusteredMin:
5932 case glslang::EOpSubgroupClusteredMax:
5933 case glslang::EOpSubgroupClusteredAnd:
5934 case glslang::EOpSubgroupClusteredOr:
5935 case glslang::EOpSubgroupClusteredXor:
5936 spvGroupOperands.push_back(spv::GroupOperationClusteredReduce);
5937 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005938#ifdef NV_EXTENSIONS
5939 case glslang::EOpSubgroupPartitionedAdd:
5940 case glslang::EOpSubgroupPartitionedMul:
5941 case glslang::EOpSubgroupPartitionedMin:
5942 case glslang::EOpSubgroupPartitionedMax:
5943 case glslang::EOpSubgroupPartitionedAnd:
5944 case glslang::EOpSubgroupPartitionedOr:
5945 case glslang::EOpSubgroupPartitionedXor:
5946 spvGroupOperands.push_back(spv::GroupOperationPartitionedReduceNV);
5947 break;
5948 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5949 case glslang::EOpSubgroupPartitionedInclusiveMul:
5950 case glslang::EOpSubgroupPartitionedInclusiveMin:
5951 case glslang::EOpSubgroupPartitionedInclusiveMax:
5952 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5953 case glslang::EOpSubgroupPartitionedInclusiveOr:
5954 case glslang::EOpSubgroupPartitionedInclusiveXor:
5955 spvGroupOperands.push_back(spv::GroupOperationPartitionedInclusiveScanNV);
5956 break;
5957 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5958 case glslang::EOpSubgroupPartitionedExclusiveMul:
5959 case glslang::EOpSubgroupPartitionedExclusiveMin:
5960 case glslang::EOpSubgroupPartitionedExclusiveMax:
5961 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5962 case glslang::EOpSubgroupPartitionedExclusiveOr:
5963 case glslang::EOpSubgroupPartitionedExclusiveXor:
5964 spvGroupOperands.push_back(spv::GroupOperationPartitionedExclusiveScanNV);
5965 break;
5966#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005967 }
5968
5969 // Push back the operands next.
5970 for (auto opIt : operands) {
5971 spvGroupOperands.push_back(opIt);
5972 }
5973
5974 // Some opcodes have additional operands.
5975 switch (op) {
5976 default: break;
5977 case glslang::EOpSubgroupQuadSwapHorizontal: spvGroupOperands.push_back(builder.makeUintConstant(0)); break;
5978 case glslang::EOpSubgroupQuadSwapVertical: spvGroupOperands.push_back(builder.makeUintConstant(1)); break;
5979 case glslang::EOpSubgroupQuadSwapDiagonal: spvGroupOperands.push_back(builder.makeUintConstant(2)); break;
5980 }
5981
5982 return builder.createOp(opCode, typeId, spvGroupOperands);
5983}
5984
John Kessenich5e4b1242015-08-06 22:53:06 -06005985spv::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 -06005986{
John Kessenich66011cb2018-03-06 16:12:04 -07005987 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5988 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06005989
John Kessenich140f3df2015-06-26 16:58:36 -06005990 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005991 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005992 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005993 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005994 spv::Id typeId0 = 0;
5995 if (consumedOperands > 0)
5996 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005997 spv::Id typeId1 = 0;
5998 if (consumedOperands > 1)
5999 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006000 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006001
6002 switch (op) {
6003 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006004 if (isFloat)
6005 libCall = spv::GLSLstd450FMin;
6006 else if (isUnsigned)
6007 libCall = spv::GLSLstd450UMin;
6008 else
6009 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006010 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006011 break;
6012 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006013 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006014 break;
6015 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006016 if (isFloat)
6017 libCall = spv::GLSLstd450FMax;
6018 else if (isUnsigned)
6019 libCall = spv::GLSLstd450UMax;
6020 else
6021 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006022 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006023 break;
6024 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006025 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006026 break;
6027 case glslang::EOpDot:
6028 opCode = spv::OpDot;
6029 break;
6030 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006031 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006032 break;
6033
6034 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006035 if (isFloat)
6036 libCall = spv::GLSLstd450FClamp;
6037 else if (isUnsigned)
6038 libCall = spv::GLSLstd450UClamp;
6039 else
6040 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006041 builder.promoteScalar(precision, operands.front(), operands[1]);
6042 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006043 break;
6044 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006045 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6046 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006047 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006048 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006049 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006050 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006051 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006052 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006053 break;
6054 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006055 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006056 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006057 break;
6058 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006059 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006060 builder.promoteScalar(precision, operands[0], operands[2]);
6061 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006062 break;
6063
6064 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006065 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006066 break;
6067 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006068 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006069 break;
6070 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006071 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006072 break;
6073 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006074 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006075 break;
6076 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006077 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006078 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006079 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006080#ifdef AMD_EXTENSIONS
6081 if (typeProxy == glslang::EbtFloat16)
6082 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6083#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006084 libCall = spv::GLSLstd450InterpolateAtSample;
6085 break;
6086 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006087#ifdef AMD_EXTENSIONS
6088 if (typeProxy == glslang::EbtFloat16)
6089 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6090#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006091 libCall = spv::GLSLstd450InterpolateAtOffset;
6092 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006093 case glslang::EOpAddCarry:
6094 opCode = spv::OpIAddCarry;
6095 typeId = builder.makeStructResultType(typeId0, typeId0);
6096 consumedOperands = 2;
6097 break;
6098 case glslang::EOpSubBorrow:
6099 opCode = spv::OpISubBorrow;
6100 typeId = builder.makeStructResultType(typeId0, typeId0);
6101 consumedOperands = 2;
6102 break;
6103 case glslang::EOpUMulExtended:
6104 opCode = spv::OpUMulExtended;
6105 typeId = builder.makeStructResultType(typeId0, typeId0);
6106 consumedOperands = 2;
6107 break;
6108 case glslang::EOpIMulExtended:
6109 opCode = spv::OpSMulExtended;
6110 typeId = builder.makeStructResultType(typeId0, typeId0);
6111 consumedOperands = 2;
6112 break;
6113 case glslang::EOpBitfieldExtract:
6114 if (isUnsigned)
6115 opCode = spv::OpBitFieldUExtract;
6116 else
6117 opCode = spv::OpBitFieldSExtract;
6118 break;
6119 case glslang::EOpBitfieldInsert:
6120 opCode = spv::OpBitFieldInsert;
6121 break;
6122
6123 case glslang::EOpFma:
6124 libCall = spv::GLSLstd450Fma;
6125 break;
6126 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006127 {
6128 libCall = spv::GLSLstd450FrexpStruct;
6129 assert(builder.isPointerType(typeId1));
6130 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006131 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006132#ifdef AMD_EXTENSIONS
6133 if (width == 16)
6134 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6135 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
6136#endif
Rex Xu470026f2017-03-29 17:12:40 +08006137 if (builder.getNumComponents(operands[0]) == 1)
6138 frexpIntType = builder.makeIntegerType(width, true);
6139 else
6140 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6141 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6142 consumedOperands = 1;
6143 }
John Kessenich55e7d112015-11-15 21:33:39 -07006144 break;
6145 case glslang::EOpLdexp:
6146 libCall = spv::GLSLstd450Ldexp;
6147 break;
6148
Rex Xu574ab042016-04-14 16:53:07 +08006149 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08006150 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08006151
John Kessenich66011cb2018-03-06 16:12:04 -07006152 case glslang::EOpSubgroupBroadcast:
6153 case glslang::EOpSubgroupBallotBitExtract:
6154 case glslang::EOpSubgroupShuffle:
6155 case glslang::EOpSubgroupShuffleXor:
6156 case glslang::EOpSubgroupShuffleUp:
6157 case glslang::EOpSubgroupShuffleDown:
6158 case glslang::EOpSubgroupClusteredAdd:
6159 case glslang::EOpSubgroupClusteredMul:
6160 case glslang::EOpSubgroupClusteredMin:
6161 case glslang::EOpSubgroupClusteredMax:
6162 case glslang::EOpSubgroupClusteredAnd:
6163 case glslang::EOpSubgroupClusteredOr:
6164 case glslang::EOpSubgroupClusteredXor:
6165 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006166#ifdef NV_EXTENSIONS
6167 case glslang::EOpSubgroupPartitionedAdd:
6168 case glslang::EOpSubgroupPartitionedMul:
6169 case glslang::EOpSubgroupPartitionedMin:
6170 case glslang::EOpSubgroupPartitionedMax:
6171 case glslang::EOpSubgroupPartitionedAnd:
6172 case glslang::EOpSubgroupPartitionedOr:
6173 case glslang::EOpSubgroupPartitionedXor:
6174 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6175 case glslang::EOpSubgroupPartitionedInclusiveMul:
6176 case glslang::EOpSubgroupPartitionedInclusiveMin:
6177 case glslang::EOpSubgroupPartitionedInclusiveMax:
6178 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6179 case glslang::EOpSubgroupPartitionedInclusiveOr:
6180 case glslang::EOpSubgroupPartitionedInclusiveXor:
6181 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6182 case glslang::EOpSubgroupPartitionedExclusiveMul:
6183 case glslang::EOpSubgroupPartitionedExclusiveMin:
6184 case glslang::EOpSubgroupPartitionedExclusiveMax:
6185 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6186 case glslang::EOpSubgroupPartitionedExclusiveOr:
6187 case glslang::EOpSubgroupPartitionedExclusiveXor:
6188#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006189 return createSubgroupOperation(op, typeId, operands, typeProxy);
6190
Rex Xu9d93a232016-05-05 12:30:44 +08006191#ifdef AMD_EXTENSIONS
6192 case glslang::EOpSwizzleInvocations:
6193 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6194 libCall = spv::SwizzleInvocationsAMD;
6195 break;
6196 case glslang::EOpSwizzleInvocationsMasked:
6197 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6198 libCall = spv::SwizzleInvocationsMaskedAMD;
6199 break;
6200 case glslang::EOpWriteInvocation:
6201 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6202 libCall = spv::WriteInvocationAMD;
6203 break;
6204
6205 case glslang::EOpMin3:
6206 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6207 if (isFloat)
6208 libCall = spv::FMin3AMD;
6209 else {
6210 if (isUnsigned)
6211 libCall = spv::UMin3AMD;
6212 else
6213 libCall = spv::SMin3AMD;
6214 }
6215 break;
6216 case glslang::EOpMax3:
6217 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6218 if (isFloat)
6219 libCall = spv::FMax3AMD;
6220 else {
6221 if (isUnsigned)
6222 libCall = spv::UMax3AMD;
6223 else
6224 libCall = spv::SMax3AMD;
6225 }
6226 break;
6227 case glslang::EOpMid3:
6228 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6229 if (isFloat)
6230 libCall = spv::FMid3AMD;
6231 else {
6232 if (isUnsigned)
6233 libCall = spv::UMid3AMD;
6234 else
6235 libCall = spv::SMid3AMD;
6236 }
6237 break;
6238
6239 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006240 if (typeProxy == glslang::EbtFloat16)
6241 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08006242 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
6243 libCall = spv::InterpolateAtVertexAMD;
6244 break;
6245#endif
6246
John Kessenich140f3df2015-06-26 16:58:36 -06006247 default:
6248 return 0;
6249 }
6250
6251 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07006252 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05006253 // Use an extended instruction from the standard library.
6254 // Construct the call arguments, without modifying the original operands vector.
6255 // We might need the remaining arguments, e.g. in the EOpFrexp case.
6256 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08006257 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07006258 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07006259 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06006260 case 0:
6261 // should all be handled by visitAggregate and createNoArgOperation
6262 assert(0);
6263 return 0;
6264 case 1:
6265 // should all be handled by createUnaryOperation
6266 assert(0);
6267 return 0;
6268 case 2:
6269 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
6270 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006271 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006272 // anything 3 or over doesn't have l-value operands, so all should be consumed
6273 assert(consumedOperands == operands.size());
6274 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06006275 break;
6276 }
6277 }
6278
John Kessenich55e7d112015-11-15 21:33:39 -07006279 // Decode the return types that were structures
6280 switch (op) {
6281 case glslang::EOpAddCarry:
6282 case glslang::EOpSubBorrow:
6283 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6284 id = builder.createCompositeExtract(id, typeId0, 0);
6285 break;
6286 case glslang::EOpUMulExtended:
6287 case glslang::EOpIMulExtended:
6288 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
6289 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6290 break;
6291 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006292 {
6293 assert(operands.size() == 2);
6294 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
6295 // "exp" is floating-point type (from HLSL intrinsic)
6296 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
6297 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
6298 builder.createStore(member1, operands[1]);
6299 } else
6300 // "exp" is integer type (from GLSL built-in function)
6301 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
6302 id = builder.createCompositeExtract(id, typeId0, 0);
6303 }
John Kessenich55e7d112015-11-15 21:33:39 -07006304 break;
6305 default:
6306 break;
6307 }
6308
John Kessenich32cfd492016-02-02 12:37:46 -07006309 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006310}
6311
Rex Xu9d93a232016-05-05 12:30:44 +08006312// Intrinsics with no arguments (or no return value, and no precision).
6313spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06006314{
6315 // TODO: get the barrier operands correct
6316
6317 switch (op) {
6318 case glslang::EOpEmitVertex:
6319 builder.createNoResultOp(spv::OpEmitVertex);
6320 return 0;
6321 case glslang::EOpEndPrimitive:
6322 builder.createNoResultOp(spv::OpEndPrimitive);
6323 return 0;
6324 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006325 if (glslangIntermediate->getStage() == EShLangTessControl) {
6326 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
6327 // TODO: prefer the following, when available:
6328 // builder.createControlBarrier(spv::ScopePatch, spv::ScopePatch,
6329 // spv::MemorySemanticsPatchMask |
6330 // spv::MemorySemanticsAcquireReleaseMask);
6331 } else {
6332 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6333 spv::MemorySemanticsWorkgroupMemoryMask |
6334 spv::MemorySemanticsAcquireReleaseMask);
6335 }
John Kessenich140f3df2015-06-26 16:58:36 -06006336 return 0;
6337 case glslang::EOpMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006338 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory |
6339 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006340 return 0;
6341 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich82979362017-12-11 04:02:24 -07006342 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask |
6343 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006344 return 0;
6345 case glslang::EOpMemoryBarrierBuffer:
John Kessenich82979362017-12-11 04:02:24 -07006346 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6347 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006348 return 0;
6349 case glslang::EOpMemoryBarrierImage:
John Kessenich82979362017-12-11 04:02:24 -07006350 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask |
6351 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006352 return 0;
6353 case glslang::EOpMemoryBarrierShared:
John Kessenich82979362017-12-11 04:02:24 -07006354 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask |
6355 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006356 return 0;
6357 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006358 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
6359 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006360 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06006361 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006362 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07006363 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07006364 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006365 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07006366 case glslang::EOpDeviceMemoryBarrier:
6367 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6368 spv::MemorySemanticsImageMemoryMask |
6369 spv::MemorySemanticsAcquireReleaseMask);
6370 return 0;
6371 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
6372 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6373 spv::MemorySemanticsImageMemoryMask |
6374 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006375 return 0;
6376 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07006377 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6378 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006379 return 0;
6380 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006381 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6382 spv::MemorySemanticsWorkgroupMemoryMask |
6383 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006384 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07006385 case glslang::EOpSubgroupBarrier:
6386 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6387 spv::MemorySemanticsAcquireReleaseMask);
6388 return spv::NoResult;
6389 case glslang::EOpSubgroupMemoryBarrier:
6390 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6391 spv::MemorySemanticsAcquireReleaseMask);
6392 return spv::NoResult;
6393 case glslang::EOpSubgroupMemoryBarrierBuffer:
6394 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
6395 spv::MemorySemanticsAcquireReleaseMask);
6396 return spv::NoResult;
6397 case glslang::EOpSubgroupMemoryBarrierImage:
6398 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
6399 spv::MemorySemanticsAcquireReleaseMask);
6400 return spv::NoResult;
6401 case glslang::EOpSubgroupMemoryBarrierShared:
6402 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6403 spv::MemorySemanticsAcquireReleaseMask);
6404 return spv::NoResult;
6405 case glslang::EOpSubgroupElect: {
6406 std::vector<spv::Id> operands;
6407 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
6408 }
Rex Xu9d93a232016-05-05 12:30:44 +08006409#ifdef AMD_EXTENSIONS
6410 case glslang::EOpTime:
6411 {
6412 std::vector<spv::Id> args; // Dummy arguments
6413 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
6414 return builder.setPrecision(id, precision);
6415 }
6416#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006417 default:
Lei Zhang17535f72016-05-04 15:55:59 -04006418 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06006419 return 0;
6420 }
6421}
6422
6423spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
6424{
John Kessenich2f273362015-07-18 22:34:27 -06006425 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06006426 spv::Id id;
6427 if (symbolValues.end() != iter) {
6428 id = iter->second;
6429 return id;
6430 }
6431
6432 // it was not found, create it
6433 id = createSpvVariable(symbol);
6434 symbolValues[symbol->getId()] = id;
6435
Rex Xuc884b4a2016-06-29 15:03:44 +08006436 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006437 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
6438 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
6439 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07006440 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07006441 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06006442 if (symbol->getQualifier().hasIndex())
6443 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
6444 if (symbol->getQualifier().hasComponent())
6445 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06006446 // atomic counters use this:
6447 if (symbol->getQualifier().hasOffset())
6448 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006449 }
6450
scygan2c864272016-05-18 18:09:17 +02006451 if (symbol->getQualifier().hasLocation())
6452 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07006453 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07006454 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07006455 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06006456 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07006457 }
John Kessenich140f3df2015-06-26 16:58:36 -06006458 if (symbol->getQualifier().hasSet())
6459 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07006460 else if (IsDescriptorResource(symbol->getType())) {
6461 // default to 0
6462 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
6463 }
John Kessenich140f3df2015-06-26 16:58:36 -06006464 if (symbol->getQualifier().hasBinding())
6465 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07006466 if (symbol->getQualifier().hasAttachment())
6467 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06006468 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07006469 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06006470 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06006471 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07006472 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06006473 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07006474 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
6475 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
6476 builder.addDecoration(id, spv::DecorationXfbStride, stride);
6477 }
6478 if (symbol->getQualifier().hasXfbOffset())
6479 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006480 }
6481
Rex Xu1da878f2016-02-21 20:59:01 +08006482 if (symbol->getType().isImage()) {
6483 std::vector<spv::Decoration> memory;
6484 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
6485 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07006486 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08006487 }
6488
John Kessenich140f3df2015-06-26 16:58:36 -06006489 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06006490 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06006491 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07006492 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06006493
John Kessenich5611c6d2018-04-05 11:25:02 -06006494 // nonuniform
6495 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
6496
John Kessenichecba76f2017-01-06 00:34:48 -07006497#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08006498 if (builtIn == spv::BuiltInSampleMask) {
6499 spv::Decoration decoration;
6500 // GL_NV_sample_mask_override_coverage extension
6501 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08006502 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08006503 else
6504 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07006505 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08006506 if (decoration != spv::DecorationMax) {
6507 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
6508 }
6509 }
chaoc771d89f2017-01-13 01:10:53 -08006510 else if (builtIn == spv::BuiltInLayer) {
6511 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06006512 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006513 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08006514 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
6515 builder.addExtension(spv::E_SPV_NV_viewport_array2);
6516 }
John Kessenichb41bff62017-08-11 13:07:17 -06006517 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006518 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
6519 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08006520 builder.addCapability(spv::CapabilityShaderStereoViewNV);
6521 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
6522 }
6523 }
6524
chaoc6e5acae2016-12-20 13:28:52 -08006525 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006526 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08006527 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08006528 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
6529 }
chaoc0ad6a4e2016-12-19 16:29:34 -08006530#endif
6531
John Kessenich5d610ee2018-03-07 18:05:55 -07006532 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
6533 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
6534 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
6535 symbol->getType().getQualifier().semanticName);
6536 }
6537
John Kessenich140f3df2015-06-26 16:58:36 -06006538 return id;
6539}
6540
John Kessenich55e7d112015-11-15 21:33:39 -07006541// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07006542// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07006543//
6544// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
6545//
6546// Recursively walk the nodes. The nodes form a tree whose leaves are
6547// regular constants, which themselves are trees that createSpvConstant()
6548// recursively walks. So, this function walks the "top" of the tree:
6549// - emit specialization constant-building instructions for specConstant
6550// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04006551spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07006552{
John Kessenich7cc0e282016-03-20 00:46:02 -06006553 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07006554
qining4f4bb812016-04-03 23:55:17 -04006555 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07006556 if (! node.getQualifier().specConstant) {
6557 // hand off to the non-spec-constant path
6558 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
6559 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04006560 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07006561 nextConst, false);
6562 }
6563
6564 // We now know we have a specialization constant to build
6565
John Kessenichd94c0032016-05-30 19:29:40 -06006566 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04006567 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
6568 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
6569 std::vector<spv::Id> dimConstId;
6570 for (int dim = 0; dim < 3; ++dim) {
6571 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
6572 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07006573 if (specConst) {
6574 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
6575 glslangIntermediate->getLocalSizeSpecId(dim));
6576 }
qining4f4bb812016-04-03 23:55:17 -04006577 }
6578 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
6579 }
6580
6581 // An AST node labelled as specialization constant should be a symbol node.
6582 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
6583 if (auto* sn = node.getAsSymbolNode()) {
6584 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04006585 // Traverse the constant constructor sub tree like generating normal run-time instructions.
6586 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
6587 // will set the builder into spec constant op instruction generating mode.
6588 sub_tree->traverse(this);
6589 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04006590 } else if (auto* const_union_array = &sn->getConstArray()){
6591 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01006592 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
6593 builder.addName(id, sn->getName().c_str());
6594 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07006595 }
6596 }
qining4f4bb812016-04-03 23:55:17 -04006597
6598 // Neither a front-end constant node, nor a specialization constant node with constant union array or
6599 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04006600 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04006601 exit(1);
6602 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07006603}
6604
John Kessenich140f3df2015-06-26 16:58:36 -06006605// Use 'consts' as the flattened glslang source of scalar constants to recursively
6606// build the aggregate SPIR-V constant.
6607//
6608// If there are not enough elements present in 'consts', 0 will be substituted;
6609// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
6610//
qining08408382016-03-21 09:51:37 -04006611spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06006612{
6613 // vector of constants for SPIR-V
6614 std::vector<spv::Id> spvConsts;
6615
6616 // Type is used for struct and array constants
6617 spv::Id typeId = convertGlslangToSpvType(glslangType);
6618
6619 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006620 glslang::TType elementType(glslangType, 0);
6621 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04006622 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006623 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006624 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06006625 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04006626 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006627 } else if (glslangType.getStruct()) {
6628 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
6629 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04006630 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06006631 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06006632 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
6633 bool zero = nextConst >= consts.size();
6634 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006635 case glslang::EbtInt8:
6636 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
6637 break;
6638 case glslang::EbtUint8:
6639 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
6640 break;
6641 case glslang::EbtInt16:
6642 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
6643 break;
6644 case glslang::EbtUint16:
6645 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
6646 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006647 case glslang::EbtInt:
6648 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
6649 break;
6650 case glslang::EbtUint:
6651 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
6652 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006653 case glslang::EbtInt64:
6654 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
6655 break;
6656 case glslang::EbtUint64:
6657 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
6658 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006659 case glslang::EbtFloat:
6660 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
6661 break;
6662 case glslang::EbtDouble:
6663 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
6664 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006665 case glslang::EbtFloat16:
6666 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
6667 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006668 case glslang::EbtBool:
6669 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
6670 break;
6671 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006672 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06006673 break;
6674 }
6675 ++nextConst;
6676 }
6677 } else {
6678 // we have a non-aggregate (scalar) constant
6679 bool zero = nextConst >= consts.size();
6680 spv::Id scalar = 0;
6681 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006682 case glslang::EbtInt8:
6683 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
6684 break;
6685 case glslang::EbtUint8:
6686 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
6687 break;
6688 case glslang::EbtInt16:
6689 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
6690 break;
6691 case glslang::EbtUint16:
6692 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
6693 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006694 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07006695 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006696 break;
6697 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07006698 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006699 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006700 case glslang::EbtInt64:
6701 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
6702 break;
6703 case glslang::EbtUint64:
6704 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
6705 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006706 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07006707 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006708 break;
6709 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07006710 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006711 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006712 case glslang::EbtFloat16:
6713 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
6714 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006715 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07006716 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006717 break;
6718 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006719 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06006720 break;
6721 }
6722 ++nextConst;
6723 return scalar;
6724 }
6725
6726 return builder.makeCompositeConstant(typeId, spvConsts);
6727}
6728
John Kessenich7c1aa102015-10-15 13:29:11 -06006729// Return true if the node is a constant or symbol whose reading has no
6730// non-trivial observable cost or effect.
6731bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
6732{
6733 // don't know what this is
6734 if (node == nullptr)
6735 return false;
6736
6737 // a constant is safe
6738 if (node->getAsConstantUnion() != nullptr)
6739 return true;
6740
6741 // not a symbol means non-trivial
6742 if (node->getAsSymbolNode() == nullptr)
6743 return false;
6744
6745 // a symbol, depends on what's being read
6746 switch (node->getType().getQualifier().storage) {
6747 case glslang::EvqTemporary:
6748 case glslang::EvqGlobal:
6749 case glslang::EvqIn:
6750 case glslang::EvqInOut:
6751 case glslang::EvqConst:
6752 case glslang::EvqConstReadOnly:
6753 case glslang::EvqUniform:
6754 return true;
6755 default:
6756 return false;
6757 }
qining25262b32016-05-06 17:25:16 -04006758}
John Kessenich7c1aa102015-10-15 13:29:11 -06006759
6760// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06006761// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06006762// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06006763// Return true if trivial.
6764bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
6765{
6766 if (node == nullptr)
6767 return false;
6768
John Kessenich84cc15f2017-05-24 16:44:47 -06006769 // count non scalars as trivial, as well as anything coming from HLSL
6770 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06006771 return true;
6772
John Kessenich7c1aa102015-10-15 13:29:11 -06006773 // symbols and constants are trivial
6774 if (isTrivialLeaf(node))
6775 return true;
6776
6777 // otherwise, it needs to be a simple operation or one or two leaf nodes
6778
6779 // not a simple operation
6780 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
6781 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
6782 if (binaryNode == nullptr && unaryNode == nullptr)
6783 return false;
6784
6785 // not on leaf nodes
6786 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
6787 return false;
6788
6789 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
6790 return false;
6791 }
6792
6793 switch (node->getAsOperator()->getOp()) {
6794 case glslang::EOpLogicalNot:
6795 case glslang::EOpConvIntToBool:
6796 case glslang::EOpConvUintToBool:
6797 case glslang::EOpConvFloatToBool:
6798 case glslang::EOpConvDoubleToBool:
6799 case glslang::EOpEqual:
6800 case glslang::EOpNotEqual:
6801 case glslang::EOpLessThan:
6802 case glslang::EOpGreaterThan:
6803 case glslang::EOpLessThanEqual:
6804 case glslang::EOpGreaterThanEqual:
6805 case glslang::EOpIndexDirect:
6806 case glslang::EOpIndexDirectStruct:
6807 case glslang::EOpLogicalXor:
6808 case glslang::EOpAny:
6809 case glslang::EOpAll:
6810 return true;
6811 default:
6812 return false;
6813 }
6814}
6815
6816// Emit short-circuiting code, where 'right' is never evaluated unless
6817// the left side is true (for &&) or false (for ||).
6818spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
6819{
6820 spv::Id boolTypeId = builder.makeBoolType();
6821
6822 // emit left operand
6823 builder.clearAccessChain();
6824 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006825 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006826
6827 // Operands to accumulate OpPhi operands
6828 std::vector<spv::Id> phiOperands;
6829 // accumulate left operand's phi information
6830 phiOperands.push_back(leftId);
6831 phiOperands.push_back(builder.getBuildPoint()->getId());
6832
6833 // Make the two kinds of operation symmetric with a "!"
6834 // || => emit "if (! left) result = right"
6835 // && => emit "if ( left) result = right"
6836 //
6837 // TODO: this runtime "not" for || could be avoided by adding functionality
6838 // to 'builder' to have an "else" without an "then"
6839 if (op == glslang::EOpLogicalOr)
6840 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
6841
6842 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08006843 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06006844
6845 // emit right operand as the "then" part of the "if"
6846 builder.clearAccessChain();
6847 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006848 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006849
6850 // accumulate left operand's phi information
6851 phiOperands.push_back(rightId);
6852 phiOperands.push_back(builder.getBuildPoint()->getId());
6853
6854 // finish the "if"
6855 ifBuilder.makeEndIf();
6856
6857 // phi together the two results
6858 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
6859}
6860
Frank Henigman541f7bb2018-01-16 00:18:26 -05006861#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08006862// Return type Id of the imported set of extended instructions corresponds to the name.
6863// Import this set if it has not been imported yet.
6864spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
6865{
6866 if (extBuiltinMap.find(name) != extBuiltinMap.end())
6867 return extBuiltinMap[name];
6868 else {
Rex Xu51596642016-09-21 18:56:12 +08006869 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08006870 spv::Id extBuiltins = builder.import(name);
6871 extBuiltinMap[name] = extBuiltins;
6872 return extBuiltins;
6873 }
6874}
Frank Henigman541f7bb2018-01-16 00:18:26 -05006875#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006876
John Kessenich140f3df2015-06-26 16:58:36 -06006877}; // end anonymous namespace
6878
6879namespace glslang {
6880
John Kessenich68d78fd2015-07-12 19:28:10 -06006881void GetSpirvVersion(std::string& version)
6882{
John Kessenich9e55f632015-07-15 10:03:39 -06006883 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06006884 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07006885 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06006886 version = buf;
6887}
6888
John Kessenicha372a3e2017-11-02 22:32:14 -06006889// For low-order part of the generator's magic number. Bump up
6890// when there is a change in the style (e.g., if SSA form changes,
6891// or a different instruction sequence to do something gets used).
6892int GetSpirvGeneratorVersion()
6893{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07006894 // return 1; // start
6895 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07006896 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07006897 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07006898 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06006899 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
6900 // versions 4 and 6 each generate OpArrayLength as it has long been done
6901 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06006902}
6903
John Kessenich140f3df2015-06-26 16:58:36 -06006904// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006905void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06006906{
6907 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06006908 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006909 if (out.fail())
6910 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06006911 for (int i = 0; i < (int)spirv.size(); ++i) {
6912 unsigned int word = spirv[i];
6913 out.write((const char*)&word, 4);
6914 }
6915 out.close();
6916}
6917
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006918// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08006919void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006920{
6921 std::ofstream out;
6922 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006923 if (out.fail())
6924 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07006925 out << "\t// " <<
6926 glslang::GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
6927 std::endl;
Flavio15017db2017-02-15 14:29:33 -08006928 if (varName != nullptr) {
6929 out << "\t #pragma once" << std::endl;
6930 out << "const uint32_t " << varName << "[] = {" << std::endl;
6931 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006932 const int WORDS_PER_LINE = 8;
6933 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
6934 out << "\t";
6935 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
6936 const unsigned int word = spirv[i + j];
6937 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
6938 if (i + j + 1 < (int)spirv.size()) {
6939 out << ",";
6940 }
6941 }
6942 out << std::endl;
6943 }
Flavio15017db2017-02-15 14:29:33 -08006944 if (varName != nullptr) {
6945 out << "};";
6946 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006947 out.close();
6948}
6949
John Kessenich140f3df2015-06-26 16:58:36 -06006950//
6951// Set up the glslang traversal
6952//
John Kessenich121853f2017-05-31 17:11:16 -06006953void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06006954{
Lei Zhang17535f72016-05-04 15:55:59 -04006955 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06006956 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04006957}
6958
John Kessenich121853f2017-05-31 17:11:16 -06006959void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
6960 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04006961{
John Kessenich140f3df2015-06-26 16:58:36 -06006962 TIntermNode* root = intermediate.getTreeRoot();
6963
6964 if (root == 0)
6965 return;
6966
John Kessenich121853f2017-05-31 17:11:16 -06006967 glslang::SpvOptions defaultOptions;
6968 if (options == nullptr)
6969 options = &defaultOptions;
6970
John Kessenich140f3df2015-06-26 16:58:36 -06006971 glslang::GetThreadPoolAllocator().push();
6972
John Kessenich2b5ea9f2018-01-31 18:35:56 -07006973 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06006974 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07006975 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06006976 it.dumpSpv(spirv);
6977
GregFfb03a552018-03-29 11:49:14 -06006978#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06006979 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
6980 // eg. forward and remove memory writes of opaque types.
6981 if ((intermediate.getSource() == EShSourceHlsl ||
6982 options->optimizeSize) &&
6983 !options->disableOptimizer) {
6984 spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
6985
6986 spvtools::Optimizer optimizer(target_env);
6987 optimizer.SetMessageConsumer([](spv_message_level_t level,
6988 const char* source,
6989 const spv_position_t& position,
6990 const char* message) {
6991 std::cerr << StringifyMessage(level, source, position, message)
6992 << std::endl;
6993 });
6994
GregFeecb8742018-03-26 12:11:55 -06006995 optimizer.RegisterPass(CreateMergeReturnPass());
GregFcd1f1692017-09-21 18:40:22 -06006996 optimizer.RegisterPass(CreateInlineExhaustivePass());
GregFe0639282017-12-21 10:55:57 -07006997 optimizer.RegisterPass(CreateEliminateDeadFunctionsPass());
6998 optimizer.RegisterPass(CreateScalarReplacementPass());
GregFcd1f1692017-09-21 18:40:22 -06006999 optimizer.RegisterPass(CreateLocalAccessChainConvertPass());
7000 optimizer.RegisterPass(CreateLocalSingleBlockLoadStoreElimPass());
7001 optimizer.RegisterPass(CreateLocalSingleStoreElimPass());
GregFb0c42b22018-05-31 16:17:18 -06007002 optimizer.RegisterPass(CreateSimplificationPass());
GregFeecb8742018-03-26 12:11:55 -06007003 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFb0c42b22018-05-31 16:17:18 -06007004 optimizer.RegisterPass(CreateVectorDCEPass());
GregF8a4848f2018-02-07 16:04:42 -07007005 optimizer.RegisterPass(CreateDeadInsertElimPass());
GregFcd1f1692017-09-21 18:40:22 -06007006 optimizer.RegisterPass(CreateAggressiveDCEPass());
7007 optimizer.RegisterPass(CreateDeadBranchElimPass());
7008 optimizer.RegisterPass(CreateBlockMergePass());
7009 optimizer.RegisterPass(CreateLocalMultiStoreElimPass());
GregFb0c42b22018-05-31 16:17:18 -06007010 optimizer.RegisterPass(CreateIfConversionPass());
7011 optimizer.RegisterPass(CreateSimplificationPass());
GregFeecb8742018-03-26 12:11:55 -06007012 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFb0c42b22018-05-31 16:17:18 -06007013 optimizer.RegisterPass(CreateVectorDCEPass());
GregF8a4848f2018-02-07 16:04:42 -07007014 optimizer.RegisterPass(CreateDeadInsertElimPass());
7015 if (options->optimizeSize) {
7016 optimizer.RegisterPass(CreateRedundancyEliminationPass());
7017 // TODO(greg-lunarg): Add this when AMD driver issues are resolved
7018 // optimizer.RegisterPass(CreateCommonUniformElimPass());
7019 }
GregFcd1f1692017-09-21 18:40:22 -06007020 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFb0c42b22018-05-31 16:17:18 -06007021 optimizer.RegisterPass(CreateCFGCleanupPass());
GregFcd1f1692017-09-21 18:40:22 -06007022
7023 if (!optimizer.Run(spirv.data(), spirv.size(), &spirv))
7024 return;
GregFcd1f1692017-09-21 18:40:22 -06007025 }
7026#endif
7027
John Kessenich140f3df2015-06-26 16:58:36 -06007028 glslang::GetThreadPoolAllocator().pop();
7029}
7030
7031}; // end namespace glslang