blob: 9cf39144f01cd3f50b4d40787a8f06a501b7f89f [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 Kessenich66011cb2018-03-06 16:12:04 -0700193 spv::Id createConversionOperation(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);
343 if (qualifier.volatil)
344 memory.push_back(spv::DecorationVolatile);
345 if (qualifier.restrict)
346 memory.push_back(spv::DecorationRestrict);
347 if (qualifier.readonly)
348 memory.push_back(spv::DecorationNonWritable);
349 if (qualifier.writeonly)
350 memory.push_back(spv::DecorationNonReadable);
351}
352
John Kessenich140f3df2015-06-26 16:58:36 -0600353// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700354spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600355{
356 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700357 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600358 case glslang::ElmRowMajor:
359 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700360 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600361 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700362 default:
363 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600364 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600365 }
366 } else {
367 switch (type.getBasicType()) {
368 default:
John Kessenich4016e382016-07-15 11:53:56 -0600369 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600370 break;
371 case glslang::EbtBlock:
372 switch (type.getQualifier().storage) {
373 case glslang::EvqUniform:
374 case glslang::EvqBuffer:
375 switch (type.getQualifier().layoutPacking) {
376 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600377 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
378 default:
John Kessenich4016e382016-07-15 11:53:56 -0600379 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600380 }
381 case glslang::EvqVaryingIn:
382 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700383 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600384 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600385 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700386 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600387 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600388 }
389 }
390 }
391}
392
393// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600394// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700395// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800396spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600397{
Rex Xubbceed72016-05-21 09:40:44 +0800398 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700399 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600400 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800401 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700402 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700403 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600404 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800405#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800406 else if (qualifier.explicitInterp) {
407 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800408 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800409 }
Rex Xu9d93a232016-05-05 12:30:44 +0800410#endif
Rex Xubbceed72016-05-21 09:40:44 +0800411 else
John Kessenich4016e382016-07-15 11:53:56 -0600412 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800413}
414
415// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600416// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800417// should be applied.
418spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
419{
420 if (qualifier.patch)
421 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700422 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600423 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700424 else if (qualifier.sample) {
425 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600426 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700427 } else
John Kessenich4016e382016-07-15 11:53:56 -0600428 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600429}
430
John Kessenich92187592016-02-01 13:45:25 -0700431// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700432spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600433{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700434 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600435 return spv::DecorationInvariant;
436 else
John Kessenich4016e382016-07-15 11:53:56 -0600437 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600438}
439
qining9220dbb2016-05-04 17:34:38 -0400440// If glslang type is noContraction, return SPIR-V NoContraction decoration.
441spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
442{
443 if (qualifier.noContraction)
444 return spv::DecorationNoContraction;
445 else
John Kessenich4016e382016-07-15 11:53:56 -0600446 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400447}
448
John Kessenich5611c6d2018-04-05 11:25:02 -0600449// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
450spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
451{
452 if (qualifier.isNonUniform()) {
453 builder.addExtension("SPV_EXT_descriptor_indexing");
454 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
455 return spv::DecorationNonUniformEXT;
456 } else
457 return spv::DecorationMax;
458}
459
David Netoa901ffe2016-06-08 14:11:40 +0100460// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
461// associated capabilities when required. For some built-in variables, a capability
462// is generated only when using the variable in an executable instruction, but not when
463// just declaring a struct member variable with it. This is true for PointSize,
464// ClipDistance, and CullDistance.
465spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600466{
467 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700468 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600469 // Defer adding the capability until the built-in is actually used.
470 if (! memberDeclaration) {
471 switch (glslangIntermediate->getStage()) {
472 case EShLangGeometry:
473 builder.addCapability(spv::CapabilityGeometryPointSize);
474 break;
475 case EShLangTessControl:
476 case EShLangTessEvaluation:
477 builder.addCapability(spv::CapabilityTessellationPointSize);
478 break;
479 default:
480 break;
481 }
John Kessenich92187592016-02-01 13:45:25 -0700482 }
483 return spv::BuiltInPointSize;
484
John Kessenichebb50532016-05-16 19:22:05 -0600485 // These *Distance capabilities logically belong here, but if the member is declared and
486 // then never used, consumers of SPIR-V prefer the capability not be declared.
487 // They are now generated when used, rather than here when declared.
488 // Potentially, the specification should be more clear what the minimum
489 // use needed is to trigger the capability.
490 //
John Kessenich92187592016-02-01 13:45:25 -0700491 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100492 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800493 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700494 return spv::BuiltInClipDistance;
495
496 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100497 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800498 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700499 return spv::BuiltInCullDistance;
500
501 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600502 builder.addCapability(spv::CapabilityMultiViewport);
503 if (glslangIntermediate->getStage() == EShLangVertex ||
504 glslangIntermediate->getStage() == EShLangTessControl ||
505 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800506
John Kessenichba6a3c22017-09-13 13:22:50 -0600507 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
508 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800509 }
John Kessenich92187592016-02-01 13:45:25 -0700510 return spv::BuiltInViewportIndex;
511
John Kessenich5e801132016-02-15 11:09:46 -0700512 case glslang::EbvSampleId:
513 builder.addCapability(spv::CapabilitySampleRateShading);
514 return spv::BuiltInSampleId;
515
516 case glslang::EbvSamplePosition:
517 builder.addCapability(spv::CapabilitySampleRateShading);
518 return spv::BuiltInSamplePosition;
519
520 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700521 return spv::BuiltInSampleMask;
522
John Kessenich78a45572016-07-08 14:05:15 -0600523 case glslang::EbvLayer:
John Kessenichba6a3c22017-09-13 13:22:50 -0600524 builder.addCapability(spv::CapabilityGeometry);
525 if (glslangIntermediate->getStage() == EShLangVertex ||
526 glslangIntermediate->getStage() == EShLangTessControl ||
527 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800528
John Kessenichba6a3c22017-09-13 13:22:50 -0600529 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
530 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800531 }
John Kessenich78a45572016-07-08 14:05:15 -0600532 return spv::BuiltInLayer;
533
John Kessenich140f3df2015-06-26 16:58:36 -0600534 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600535 case glslang::EbvVertexId: return spv::BuiltInVertexId;
536 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700537 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
538 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800539
John Kessenichda581a22015-10-14 14:10:30 -0600540 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700541 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800542 builder.addCapability(spv::CapabilityDrawParameters);
543 return spv::BuiltInBaseVertex;
544
John Kessenichda581a22015-10-14 14:10:30 -0600545 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700546 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800547 builder.addCapability(spv::CapabilityDrawParameters);
548 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200549
John Kessenichda581a22015-10-14 14:10:30 -0600550 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700551 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800552 builder.addCapability(spv::CapabilityDrawParameters);
553 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200554
555 case glslang::EbvPrimitiveId:
556 if (glslangIntermediate->getStage() == EShLangFragment)
557 builder.addCapability(spv::CapabilityGeometry);
558 return spv::BuiltInPrimitiveId;
559
Rex Xu37cdcee2017-06-29 17:46:34 +0800560 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800561 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
562 builder.addCapability(spv::CapabilityStencilExportEXT);
563 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800564
John Kessenich140f3df2015-06-26 16:58:36 -0600565 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600566 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
567 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
568 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
569 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
570 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
571 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
572 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600573 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
574 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
575 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
576 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
577 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
578 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
579 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
580 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800581
Rex Xu574ab042016-04-14 16:53:07 +0800582 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800583 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800584 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
585 return spv::BuiltInSubgroupSize;
586
Rex Xu574ab042016-04-14 16:53:07 +0800587 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800588 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800589 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
590 return spv::BuiltInSubgroupLocalInvocationId;
591
Rex Xu574ab042016-04-14 16:53:07 +0800592 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800593 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
594 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
595 return spv::BuiltInSubgroupEqMaskKHR;
596
Rex Xu574ab042016-04-14 16:53:07 +0800597 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800598 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
599 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
600 return spv::BuiltInSubgroupGeMaskKHR;
601
Rex Xu574ab042016-04-14 16:53:07 +0800602 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800603 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
604 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
605 return spv::BuiltInSubgroupGtMaskKHR;
606
Rex Xu574ab042016-04-14 16:53:07 +0800607 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800608 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
609 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
610 return spv::BuiltInSubgroupLeMaskKHR;
611
Rex Xu574ab042016-04-14 16:53:07 +0800612 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800613 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
614 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
615 return spv::BuiltInSubgroupLtMaskKHR;
616
John Kessenich66011cb2018-03-06 16:12:04 -0700617 case glslang::EbvNumSubgroups:
618 builder.addCapability(spv::CapabilityGroupNonUniform);
619 return spv::BuiltInNumSubgroups;
620
621 case glslang::EbvSubgroupID:
622 builder.addCapability(spv::CapabilityGroupNonUniform);
623 return spv::BuiltInSubgroupId;
624
625 case glslang::EbvSubgroupSize2:
626 builder.addCapability(spv::CapabilityGroupNonUniform);
627 return spv::BuiltInSubgroupSize;
628
629 case glslang::EbvSubgroupInvocation2:
630 builder.addCapability(spv::CapabilityGroupNonUniform);
631 return spv::BuiltInSubgroupLocalInvocationId;
632
633 case glslang::EbvSubgroupEqMask2:
634 builder.addCapability(spv::CapabilityGroupNonUniform);
635 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
636 return spv::BuiltInSubgroupEqMask;
637
638 case glslang::EbvSubgroupGeMask2:
639 builder.addCapability(spv::CapabilityGroupNonUniform);
640 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
641 return spv::BuiltInSubgroupGeMask;
642
643 case glslang::EbvSubgroupGtMask2:
644 builder.addCapability(spv::CapabilityGroupNonUniform);
645 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
646 return spv::BuiltInSubgroupGtMask;
647
648 case glslang::EbvSubgroupLeMask2:
649 builder.addCapability(spv::CapabilityGroupNonUniform);
650 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
651 return spv::BuiltInSubgroupLeMask;
652
653 case glslang::EbvSubgroupLtMask2:
654 builder.addCapability(spv::CapabilityGroupNonUniform);
655 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
656 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800657#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800658 case glslang::EbvBaryCoordNoPersp:
659 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
660 return spv::BuiltInBaryCoordNoPerspAMD;
661
662 case glslang::EbvBaryCoordNoPerspCentroid:
663 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
664 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
665
666 case glslang::EbvBaryCoordNoPerspSample:
667 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
668 return spv::BuiltInBaryCoordNoPerspSampleAMD;
669
670 case glslang::EbvBaryCoordSmooth:
671 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
672 return spv::BuiltInBaryCoordSmoothAMD;
673
674 case glslang::EbvBaryCoordSmoothCentroid:
675 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
676 return spv::BuiltInBaryCoordSmoothCentroidAMD;
677
678 case glslang::EbvBaryCoordSmoothSample:
679 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
680 return spv::BuiltInBaryCoordSmoothSampleAMD;
681
682 case glslang::EbvBaryCoordPullModel:
683 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
684 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800685#endif
chaoc771d89f2017-01-13 01:10:53 -0800686
John Kessenich6c8aaac2017-02-27 01:20:51 -0700687 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700688 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700689 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700690 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700691
692 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700693 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700694 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700695 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700696
chaoc771d89f2017-01-13 01:10:53 -0800697#ifdef NV_EXTENSIONS
698 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800699 if (!memberDeclaration) {
700 builder.addExtension(spv::E_SPV_NV_viewport_array2);
701 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
702 }
chaoc771d89f2017-01-13 01:10:53 -0800703 return spv::BuiltInViewportMaskNV;
704 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800705 if (!memberDeclaration) {
706 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
707 builder.addCapability(spv::CapabilityShaderStereoViewNV);
708 }
chaoc771d89f2017-01-13 01:10:53 -0800709 return spv::BuiltInSecondaryPositionNV;
710 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800711 if (!memberDeclaration) {
712 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
713 builder.addCapability(spv::CapabilityShaderStereoViewNV);
714 }
chaoc771d89f2017-01-13 01:10:53 -0800715 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800716 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800717 if (!memberDeclaration) {
718 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
719 builder.addCapability(spv::CapabilityPerViewAttributesNV);
720 }
chaocdf3956c2017-02-14 14:52:34 -0800721 return spv::BuiltInPositionPerViewNV;
722 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800723 if (!memberDeclaration) {
724 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
725 builder.addCapability(spv::CapabilityPerViewAttributesNV);
726 }
chaocdf3956c2017-02-14 14:52:34 -0800727 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700728 case glslang::EbvFragFullyCoveredNV:
729 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
730 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
731 return spv::BuiltInFullyCoveredEXT;
chaoc771d89f2017-01-13 01:10:53 -0800732#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800733 default:
734 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600735 }
736}
737
Rex Xufc618912015-09-09 16:42:49 +0800738// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700739spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800740{
741 assert(type.getBasicType() == glslang::EbtSampler);
742
John Kessenich5d0fa972016-02-15 11:57:00 -0700743 // Check for capabilities
744 switch (type.getQualifier().layoutFormat) {
745 case glslang::ElfRg32f:
746 case glslang::ElfRg16f:
747 case glslang::ElfR11fG11fB10f:
748 case glslang::ElfR16f:
749 case glslang::ElfRgba16:
750 case glslang::ElfRgb10A2:
751 case glslang::ElfRg16:
752 case glslang::ElfRg8:
753 case glslang::ElfR16:
754 case glslang::ElfR8:
755 case glslang::ElfRgba16Snorm:
756 case glslang::ElfRg16Snorm:
757 case glslang::ElfRg8Snorm:
758 case glslang::ElfR16Snorm:
759 case glslang::ElfR8Snorm:
760
761 case glslang::ElfRg32i:
762 case glslang::ElfRg16i:
763 case glslang::ElfRg8i:
764 case glslang::ElfR16i:
765 case glslang::ElfR8i:
766
767 case glslang::ElfRgb10a2ui:
768 case glslang::ElfRg32ui:
769 case glslang::ElfRg16ui:
770 case glslang::ElfRg8ui:
771 case glslang::ElfR16ui:
772 case glslang::ElfR8ui:
773 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
774 break;
775
776 default:
777 break;
778 }
779
780 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800781 switch (type.getQualifier().layoutFormat) {
782 case glslang::ElfNone: return spv::ImageFormatUnknown;
783 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
784 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
785 case glslang::ElfR32f: return spv::ImageFormatR32f;
786 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
787 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
788 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
789 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
790 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
791 case glslang::ElfR16f: return spv::ImageFormatR16f;
792 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
793 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
794 case glslang::ElfRg16: return spv::ImageFormatRg16;
795 case glslang::ElfRg8: return spv::ImageFormatRg8;
796 case glslang::ElfR16: return spv::ImageFormatR16;
797 case glslang::ElfR8: return spv::ImageFormatR8;
798 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
799 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
800 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
801 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
802 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
803 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
804 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
805 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
806 case glslang::ElfR32i: return spv::ImageFormatR32i;
807 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
808 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
809 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
810 case glslang::ElfR16i: return spv::ImageFormatR16i;
811 case glslang::ElfR8i: return spv::ImageFormatR8i;
812 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
813 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
814 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
815 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
816 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
817 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
818 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
819 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
820 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
821 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600822 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800823 }
824}
825
John Kesseniche18fd202018-01-30 11:01:39 -0700826spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +0800827{
John Kesseniche18fd202018-01-30 11:01:39 -0700828 if (selectionNode.getFlatten())
829 return spv::SelectionControlFlattenMask;
830 if (selectionNode.getDontFlatten())
831 return spv::SelectionControlDontFlattenMask;
832 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +0800833}
834
John Kesseniche18fd202018-01-30 11:01:39 -0700835spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -0600836{
John Kesseniche18fd202018-01-30 11:01:39 -0700837 if (switchNode.getFlatten())
838 return spv::SelectionControlFlattenMask;
839 if (switchNode.getDontFlatten())
840 return spv::SelectionControlDontFlattenMask;
841 return spv::SelectionControlMaskNone;
842}
843
John Kessenicha2858d92018-01-31 08:11:18 -0700844// return a non-0 dependency if the dependency argument must be set
845spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
846 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -0700847{
848 spv::LoopControlMask control = spv::LoopControlMaskNone;
849
850 if (loopNode.getDontUnroll())
851 control = control | spv::LoopControlDontUnrollMask;
852 if (loopNode.getUnroll())
853 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -0700854 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -0700855 control = control | spv::LoopControlDependencyInfiniteMask;
856 else if (loopNode.getLoopDependency() > 0) {
857 control = control | spv::LoopControlDependencyLengthMask;
858 dependencyLength = loopNode.getLoopDependency();
859 }
John Kesseniche18fd202018-01-30 11:01:39 -0700860
861 return control;
steve-lunargf1709e72017-05-02 20:14:50 -0600862}
863
John Kessenicha5c5fb62017-05-05 05:09:58 -0600864// Translate glslang type to SPIR-V storage class.
865spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
866{
867 if (type.getQualifier().isPipeInput())
868 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600869 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -0600870 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600871
872 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
873 type.getQualifier().storage == glslang::EvqUniform) {
874 if (type.getBasicType() == glslang::EbtAtomicUint)
875 return spv::StorageClassAtomicCounter;
876 if (type.containsOpaque())
877 return spv::StorageClassUniformConstant;
878 }
879
880 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -0700881 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -0600882 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600883 }
884
885 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600886 if (type.getQualifier().layoutPushConstant)
887 return spv::StorageClassPushConstant;
888 if (type.getBasicType() == glslang::EbtBlock)
889 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600890 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600891 }
John Kessenichbed4e4f2017-09-08 02:38:07 -0600892
893 switch (type.getQualifier().storage) {
894 case glslang::EvqShared: return spv::StorageClassWorkgroup;
895 case glslang::EvqGlobal: return spv::StorageClassPrivate;
896 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
897 case glslang::EvqTemporary: return spv::StorageClassFunction;
898 default:
899 assert(0);
900 break;
901 }
902
903 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600904}
905
John Kessenich5611c6d2018-04-05 11:25:02 -0600906// Add capabilities pertaining to how an array is indexed.
907void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
908 const glslang::TType& indexType)
909{
910 if (indexType.getQualifier().isNonUniform()) {
911 // deal with an asserted non-uniform index
912 if (baseType.getBasicType() == glslang::EbtSampler) {
913 if (baseType.getQualifier().hasAttachment())
914 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
915 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
916 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
917 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
918 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
919 else if (baseType.isImage())
920 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
921 else if (baseType.isTexture())
922 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
923 } else if (baseType.getBasicType() == glslang::EbtBlock) {
924 if (baseType.getQualifier().storage == glslang::EvqBuffer)
925 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
926 else if (baseType.getQualifier().storage == glslang::EvqUniform)
927 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
928 }
929 } else {
930 // assume a dynamically uniform index
931 if (baseType.getBasicType() == glslang::EbtSampler) {
932 if (baseType.getQualifier().hasAttachment())
933 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
934 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
935 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
936 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
937 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
938 }
939 }
940}
941
qining25262b32016-05-06 17:25:16 -0400942// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700943// descriptor set.
944bool IsDescriptorResource(const glslang::TType& type)
945{
John Kessenichf7497e22016-03-08 21:36:22 -0700946 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700947 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700948 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700949
950 // non block...
951 // basically samplerXXX/subpass/sampler/texture are all included
952 // if they are the global-scope-class, not the function parameter
953 // (or local, if they ever exist) class.
954 if (type.getBasicType() == glslang::EbtSampler)
955 return type.getQualifier().isUniformOrBuffer();
956
957 // None of the above.
958 return false;
959}
960
John Kesseniche0b6cad2015-12-24 10:30:13 -0700961void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
962{
963 if (child.layoutMatrix == glslang::ElmNone)
964 child.layoutMatrix = parent.layoutMatrix;
965
966 if (parent.invariant)
967 child.invariant = true;
968 if (parent.nopersp)
969 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800970#ifdef AMD_EXTENSIONS
971 if (parent.explicitInterp)
972 child.explicitInterp = true;
973#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700974 if (parent.flat)
975 child.flat = true;
976 if (parent.centroid)
977 child.centroid = true;
978 if (parent.patch)
979 child.patch = true;
980 if (parent.sample)
981 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800982 if (parent.coherent)
983 child.coherent = true;
984 if (parent.volatil)
985 child.volatil = true;
986 if (parent.restrict)
987 child.restrict = true;
988 if (parent.readonly)
989 child.readonly = true;
990 if (parent.writeonly)
991 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700992}
993
John Kessenichf2b7f332016-09-01 17:05:23 -0600994bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700995{
John Kessenich7b9fa252016-01-21 18:56:57 -0700996 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600997 // - struct members might inherit from a struct declaration
998 // (note that non-block structs don't explicitly inherit,
999 // only implicitly, meaning no decoration involved)
1000 // - affect decorations on the struct members
1001 // (note smooth does not, and expecting something like volatile
1002 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001003 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001004 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001005}
1006
John Kessenich140f3df2015-06-26 16:58:36 -06001007//
1008// Implement the TGlslangToSpvTraverser class.
1009//
1010
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001011TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001012 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1013 : TIntermTraverser(true, false, true),
1014 options(options),
1015 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001016 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001017 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001018 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001019 glslangIntermediate(glslangIntermediate)
1020{
1021 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1022
1023 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001024 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1025 glslangIntermediate->getVersion());
1026
John Kessenich121853f2017-05-31 17:11:16 -06001027 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001028 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001029 builder.setSourceFile(glslangIntermediate->getSourceFile());
1030
1031 // Set the source shader's text. If for SPV version 1.0, include
1032 // a preamble in comments stating the OpModuleProcessed instructions.
1033 // Otherwise, emit those as actual instructions.
1034 std::string text;
1035 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1036 for (int p = 0; p < (int)processes.size(); ++p) {
1037 if (glslangIntermediate->getSpv().spv < 0x00010100) {
1038 text.append("// OpModuleProcessed ");
1039 text.append(processes[p]);
1040 text.append("\n");
1041 } else
1042 builder.addModuleProcessed(processes[p]);
1043 }
1044 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
1045 text.append("#line 1\n");
1046 text.append(glslangIntermediate->getSourceText());
1047 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -06001048 }
John Kessenich140f3df2015-06-26 16:58:36 -06001049 stdBuiltins = builder.import("GLSL.std.450");
1050 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -06001051 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1052 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001053
1054 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001055 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1056 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001057 builder.addSourceExtension(it->c_str());
1058
1059 // Add the top-level modes for this shader.
1060
John Kessenich92187592016-02-01 13:45:25 -07001061 if (glslangIntermediate->getXfbMode()) {
1062 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001063 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001064 }
John Kessenich140f3df2015-06-26 16:58:36 -06001065
1066 unsigned int mode;
1067 switch (glslangIntermediate->getStage()) {
1068 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001069 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001070 break;
1071
steve-lunarge7412492017-03-23 11:56:07 -06001072 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001073 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001074 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001075
steve-lunarge7412492017-03-23 11:56:07 -06001076 glslang::TLayoutGeometry primitive;
1077
1078 if (glslangIntermediate->getStage() == EShLangTessControl) {
1079 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1080 primitive = glslangIntermediate->getOutputPrimitive();
1081 } else {
1082 primitive = glslangIntermediate->getInputPrimitive();
1083 }
1084
1085 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001086 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1087 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1088 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001089 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001090 }
John Kessenich4016e382016-07-15 11:53:56 -06001091 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001092 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1093
John Kesseniche6903322015-10-13 16:29:02 -06001094 switch (glslangIntermediate->getVertexSpacing()) {
1095 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1096 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1097 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001098 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001099 }
John Kessenich4016e382016-07-15 11:53:56 -06001100 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001101 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1102
1103 switch (glslangIntermediate->getVertexOrder()) {
1104 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1105 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001106 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001107 }
John Kessenich4016e382016-07-15 11:53:56 -06001108 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001109 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1110
1111 if (glslangIntermediate->getPointMode())
1112 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001113 break;
1114
1115 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001116 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001117 switch (glslangIntermediate->getInputPrimitive()) {
1118 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1119 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1120 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001121 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001122 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001123 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001124 }
John Kessenich4016e382016-07-15 11:53:56 -06001125 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001126 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001127
John Kessenich140f3df2015-06-26 16:58:36 -06001128 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1129
1130 switch (glslangIntermediate->getOutputPrimitive()) {
1131 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1132 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1133 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001134 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001135 }
John Kessenich4016e382016-07-15 11:53:56 -06001136 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001137 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1138 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1139 break;
1140
1141 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001142 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001143 if (glslangIntermediate->getPixelCenterInteger())
1144 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001145
John Kessenich140f3df2015-06-26 16:58:36 -06001146 if (glslangIntermediate->getOriginUpperLeft())
1147 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001148 else
1149 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001150
1151 if (glslangIntermediate->getEarlyFragmentTests())
1152 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1153
chaocc1204522017-06-30 17:14:30 -07001154 if (glslangIntermediate->getPostDepthCoverage()) {
1155 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1156 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1157 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1158 }
1159
John Kesseniche6903322015-10-13 16:29:02 -06001160 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001161 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1162 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001163 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001164 }
John Kessenich4016e382016-07-15 11:53:56 -06001165 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001166 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1167
1168 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1169 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001170 break;
1171
1172 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001173 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001174 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1175 glslangIntermediate->getLocalSize(1),
1176 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001177 break;
1178
1179 default:
1180 break;
1181 }
John Kessenich140f3df2015-06-26 16:58:36 -06001182}
1183
John Kessenichfca82622016-11-26 13:23:20 -07001184// Finish creating SPV, after the traversal is complete.
1185void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001186{
John Kessenich517fe7a2016-11-26 13:31:47 -07001187 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001188 builder.setBuildPoint(shaderEntry->getLastBlock());
1189 builder.leaveFunction();
1190 }
1191
John Kessenich7ba63412015-12-20 17:37:07 -07001192 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001193 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1194 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001195
qiningda397332016-03-09 19:54:03 -05001196 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001197}
1198
John Kessenichfca82622016-11-26 13:23:20 -07001199// Write the SPV into 'out'.
1200void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001201{
John Kessenichfca82622016-11-26 13:23:20 -07001202 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001203}
1204
1205//
1206// Implement the traversal functions.
1207//
1208// Return true from interior nodes to have the external traversal
1209// continue on to children. Return false if children were
1210// already processed.
1211//
1212
1213//
qining25262b32016-05-06 17:25:16 -04001214// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001215// - uniform/input reads
1216// - output writes
1217// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1218// - something simple that degenerates into the last bullet
1219//
1220void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1221{
qining75d1d802016-04-06 14:42:01 -04001222 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1223 if (symbol->getType().getQualifier().isSpecConstant())
1224 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1225
John Kessenich140f3df2015-06-26 16:58:36 -06001226 // getSymbolId() will set up all the IO decorations on the first call.
1227 // Formal function parameters were mapped during makeFunctions().
1228 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001229
1230 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1231 if (builder.isPointer(id)) {
1232 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001233 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1234 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1235 iOSet.insert(id);
1236 }
John Kessenich7ba63412015-12-20 17:37:07 -07001237 }
1238
1239 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001240 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001241 // Prepare to generate code for the access
1242
1243 // L-value chains will be computed left to right. We're on the symbol now,
1244 // which is the left-most part of the access chain, so now is "clear" time,
1245 // followed by setting the base.
1246 builder.clearAccessChain();
1247
1248 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001249 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001250 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001251 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001252 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001253 // These are also pure R-values.
1254 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001255 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001256 builder.setAccessChainRValue(id);
1257 else
1258 builder.setAccessChainLValue(id);
1259 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001260
1261 // Process linkage-only nodes for any special additional interface work.
1262 if (linkageOnly) {
1263 if (glslangIntermediate->getHlslFunctionality1()) {
1264 // Map implicit counter buffers to their originating buffers, which should have been
1265 // seen by now, given earlier pruning of unused counters, and preservation of order
1266 // of declaration.
1267 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1268 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1269 // Save possible originating buffers for counter buffers, keyed by
1270 // making the potential counter-buffer name.
1271 std::string keyName = symbol->getName().c_str();
1272 keyName = glslangIntermediate->addCounterBufferName(keyName);
1273 counterOriginator[keyName] = symbol;
1274 } else {
1275 // Handle a counter buffer, by finding the saved originating buffer.
1276 std::string keyName = symbol->getName().c_str();
1277 auto it = counterOriginator.find(keyName);
1278 if (it != counterOriginator.end()) {
1279 id = getSymbolId(it->second);
1280 if (id != spv::NoResult) {
1281 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001282 if (counterId != spv::NoResult) {
1283 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001284 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001285 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001286 }
1287 }
1288 }
1289 }
1290 }
1291 }
John Kessenich140f3df2015-06-26 16:58:36 -06001292}
1293
1294bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1295{
John Kesseniche485c7a2017-05-31 18:50:53 -06001296 builder.setLine(node->getLoc().line);
1297
qining40887662016-04-03 22:20:42 -04001298 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1299 if (node->getType().getQualifier().isSpecConstant())
1300 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1301
John Kessenich140f3df2015-06-26 16:58:36 -06001302 // First, handle special cases
1303 switch (node->getOp()) {
1304 case glslang::EOpAssign:
1305 case glslang::EOpAddAssign:
1306 case glslang::EOpSubAssign:
1307 case glslang::EOpMulAssign:
1308 case glslang::EOpVectorTimesMatrixAssign:
1309 case glslang::EOpVectorTimesScalarAssign:
1310 case glslang::EOpMatrixTimesScalarAssign:
1311 case glslang::EOpMatrixTimesMatrixAssign:
1312 case glslang::EOpDivAssign:
1313 case glslang::EOpModAssign:
1314 case glslang::EOpAndAssign:
1315 case glslang::EOpInclusiveOrAssign:
1316 case glslang::EOpExclusiveOrAssign:
1317 case glslang::EOpLeftShiftAssign:
1318 case glslang::EOpRightShiftAssign:
1319 // A bin-op assign "a += b" means the same thing as "a = a + b"
1320 // where a is evaluated before b. For a simple assignment, GLSL
1321 // says to evaluate the left before the right. So, always, left
1322 // node then right node.
1323 {
1324 // get the left l-value, save it away
1325 builder.clearAccessChain();
1326 node->getLeft()->traverse(this);
1327 spv::Builder::AccessChain lValue = builder.getAccessChain();
1328
1329 // evaluate the right
1330 builder.clearAccessChain();
1331 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001332 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001333
1334 if (node->getOp() != glslang::EOpAssign) {
1335 // the left is also an r-value
1336 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001337 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001338
1339 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001340 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001341 TranslateNoContractionDecoration(node->getType().getQualifier()),
1342 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001343 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001344 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1345 node->getType().getBasicType());
1346
1347 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001348 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001349 }
1350
1351 // store the result
1352 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001353 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001354
1355 // assignments are expressions having an rValue after they are evaluated...
1356 builder.clearAccessChain();
1357 builder.setAccessChainRValue(rValue);
1358 }
1359 return false;
1360 case glslang::EOpIndexDirect:
1361 case glslang::EOpIndexDirectStruct:
1362 {
1363 // Get the left part of the access chain.
1364 node->getLeft()->traverse(this);
1365
1366 // Add the next element in the chain
1367
David Netoa901ffe2016-06-08 14:11:40 +01001368 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001369 if (! node->getLeft()->getType().isArray() &&
1370 node->getLeft()->getType().isVector() &&
1371 node->getOp() == glslang::EOpIndexDirect) {
1372 // This is essentially a hard-coded vector swizzle of size 1,
1373 // so short circuit the access-chain stuff with a swizzle.
1374 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001375 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001376 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001377 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001378 int spvIndex = glslangIndex;
1379 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1380 node->getOp() == glslang::EOpIndexDirectStruct)
1381 {
1382 // This may be, e.g., an anonymous block-member selection, which generally need
1383 // index remapping due to hidden members in anonymous blocks.
1384 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1385 assert(remapper.size() > 0);
1386 spvIndex = remapper[glslangIndex];
1387 }
John Kessenichebb50532016-05-16 19:22:05 -06001388
David Netoa901ffe2016-06-08 14:11:40 +01001389 // normal case for indexing array or structure or block
1390 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1391
1392 // Add capabilities here for accessing PointSize and clip/cull distance.
1393 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001394 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001395 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001396 }
1397 }
1398 return false;
1399 case glslang::EOpIndexIndirect:
1400 {
1401 // Structure or array or vector indirection.
1402 // Will use native SPIR-V access-chain for struct and array indirection;
1403 // matrices are arrays of vectors, so will also work for a matrix.
1404 // Will use the access chain's 'component' for variable index into a vector.
1405
1406 // This adapter is building access chains left to right.
1407 // Set up the access chain to the left.
1408 node->getLeft()->traverse(this);
1409
1410 // save it so that computing the right side doesn't trash it
1411 spv::Builder::AccessChain partial = builder.getAccessChain();
1412
1413 // compute the next index in the chain
1414 builder.clearAccessChain();
1415 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001416 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001417
John Kessenich5611c6d2018-04-05 11:25:02 -06001418 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1419
John Kessenich140f3df2015-06-26 16:58:36 -06001420 // restore the saved access chain
1421 builder.setAccessChain(partial);
1422
1423 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001424 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001425 else
John Kessenichfa668da2015-09-13 14:46:30 -06001426 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001427 }
1428 return false;
1429 case glslang::EOpVectorSwizzle:
1430 {
1431 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001432 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001433 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001434 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001435 }
1436 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001437 case glslang::EOpMatrixSwizzle:
1438 logger->missingFunctionality("matrix swizzle");
1439 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001440 case glslang::EOpLogicalOr:
1441 case glslang::EOpLogicalAnd:
1442 {
1443
1444 // These may require short circuiting, but can sometimes be done as straight
1445 // binary operations. The right operand must be short circuited if it has
1446 // side effects, and should probably be if it is complex.
1447 if (isTrivial(node->getRight()->getAsTyped()))
1448 break; // handle below as a normal binary operation
1449 // otherwise, we need to do dynamic short circuiting on the right operand
1450 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1451 builder.clearAccessChain();
1452 builder.setAccessChainRValue(result);
1453 }
1454 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001455 default:
1456 break;
1457 }
1458
1459 // Assume generic binary op...
1460
John Kessenich32cfd492016-02-02 12:37:46 -07001461 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001462 builder.clearAccessChain();
1463 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001464 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001465
John Kessenich32cfd492016-02-02 12:37:46 -07001466 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001467 builder.clearAccessChain();
1468 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001469 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001470
John Kessenich32cfd492016-02-02 12:37:46 -07001471 // get result
John Kessenichead86222018-03-28 18:01:20 -06001472 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001473 TranslateNoContractionDecoration(node->getType().getQualifier()),
1474 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001475 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001476 convertGlslangToSpvType(node->getType()), left, right,
1477 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001478
John Kessenich50e57562015-12-21 21:21:11 -07001479 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001480 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001481 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001482 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001483 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001484 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001485 return false;
1486 }
John Kessenich140f3df2015-06-26 16:58:36 -06001487}
1488
1489bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1490{
John Kesseniche485c7a2017-05-31 18:50:53 -06001491 builder.setLine(node->getLoc().line);
1492
qining40887662016-04-03 22:20:42 -04001493 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1494 if (node->getType().getQualifier().isSpecConstant())
1495 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1496
John Kessenichfc51d282015-08-19 13:34:18 -06001497 spv::Id result = spv::NoResult;
1498
1499 // try texturing first
1500 result = createImageTextureFunctionCall(node);
1501 if (result != spv::NoResult) {
1502 builder.clearAccessChain();
1503 builder.setAccessChainRValue(result);
1504
1505 return false; // done with this node
1506 }
1507
1508 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001509
1510 if (node->getOp() == glslang::EOpArrayLength) {
1511 // Quite special; won't want to evaluate the operand.
1512
John Kessenich5611c6d2018-04-05 11:25:02 -06001513 // Currently, the front-end does not allow .length() on an array until it is sized,
1514 // except for the last block membeor of an SSBO.
1515 // TODO: If this changes, link-time sized arrays might show up here, and need their
1516 // size extracted.
1517
John Kessenichc9a80832015-09-12 12:17:44 -06001518 // Normal .length() would have been constant folded by the front-end.
1519 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001520 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001521
John Kessenichc9a80832015-09-12 12:17:44 -06001522 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1523 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001524 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1525 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001526
1527 builder.clearAccessChain();
1528 builder.setAccessChainRValue(length);
1529
1530 return false;
1531 }
1532
John Kessenichfc51d282015-08-19 13:34:18 -06001533 // Start by evaluating the operand
1534
John Kessenich8c8505c2016-07-26 12:50:38 -06001535 // Does it need a swizzle inversion? If so, evaluation is inverted;
1536 // operate first on the swizzle base, then apply the swizzle.
1537 spv::Id invertedType = spv::NoType;
1538 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1539 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1540 invertedType = getInvertedSwizzleType(*node->getOperand());
1541
John Kessenich140f3df2015-06-26 16:58:36 -06001542 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001543 if (invertedType != spv::NoType)
1544 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1545 else
1546 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001547
Rex Xufc618912015-09-09 16:42:49 +08001548 spv::Id operand = spv::NoResult;
1549
1550 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1551 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001552 node->getOp() == glslang::EOpAtomicCounter ||
1553 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001554 operand = builder.accessChainGetLValue(); // Special case l-value operands
1555 else
John Kessenich32cfd492016-02-02 12:37:46 -07001556 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001557
John Kessenichead86222018-03-28 18:01:20 -06001558 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001559 TranslateNoContractionDecoration(node->getType().getQualifier()),
1560 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001561
1562 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001563 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001564 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001565
1566 // if not, then possibly an operation
1567 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001568 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001569
1570 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001571 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001572 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001573 builder.addDecoration(result, decorations.nonUniform);
1574 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001575
John Kessenich140f3df2015-06-26 16:58:36 -06001576 builder.clearAccessChain();
1577 builder.setAccessChainRValue(result);
1578
1579 return false; // done with this node
1580 }
1581
1582 // it must be a special case, check...
1583 switch (node->getOp()) {
1584 case glslang::EOpPostIncrement:
1585 case glslang::EOpPostDecrement:
1586 case glslang::EOpPreIncrement:
1587 case glslang::EOpPreDecrement:
1588 {
1589 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001590 spv::Id one = 0;
1591 if (node->getBasicType() == glslang::EbtFloat)
1592 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001593 else if (node->getBasicType() == glslang::EbtDouble)
1594 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001595 else if (node->getBasicType() == glslang::EbtFloat16)
1596 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001597 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1598 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001599 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1600 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001601 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1602 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001603 else
1604 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001605 glslang::TOperator op;
1606 if (node->getOp() == glslang::EOpPreIncrement ||
1607 node->getOp() == glslang::EOpPostIncrement)
1608 op = glslang::EOpAdd;
1609 else
1610 op = glslang::EOpSub;
1611
John Kessenichead86222018-03-28 18:01:20 -06001612 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001613 convertGlslangToSpvType(node->getType()), operand, one,
1614 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001615 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001616
1617 // The result of operation is always stored, but conditionally the
1618 // consumed result. The consumed result is always an r-value.
1619 builder.accessChainStore(result);
1620 builder.clearAccessChain();
1621 if (node->getOp() == glslang::EOpPreIncrement ||
1622 node->getOp() == glslang::EOpPreDecrement)
1623 builder.setAccessChainRValue(result);
1624 else
1625 builder.setAccessChainRValue(operand);
1626 }
1627
1628 return false;
1629
1630 case glslang::EOpEmitStreamVertex:
1631 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1632 return false;
1633 case glslang::EOpEndStreamPrimitive:
1634 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1635 return false;
1636
1637 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001638 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001639 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001640 }
John Kessenich140f3df2015-06-26 16:58:36 -06001641}
1642
1643bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1644{
qining27e04a02016-04-14 16:40:20 -04001645 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1646 if (node->getType().getQualifier().isSpecConstant())
1647 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1648
John Kessenichfc51d282015-08-19 13:34:18 -06001649 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001650 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1651 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001652
1653 // try texturing
1654 result = createImageTextureFunctionCall(node);
1655 if (result != spv::NoResult) {
1656 builder.clearAccessChain();
1657 builder.setAccessChainRValue(result);
1658
1659 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001660#ifdef AMD_EXTENSIONS
1661 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1662#else
John Kessenich56bab042015-09-16 10:54:31 -06001663 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001664#endif
Rex Xufc618912015-09-09 16:42:49 +08001665 // "imageStore" is a special case, which has no result
1666 return false;
1667 }
John Kessenichfc51d282015-08-19 13:34:18 -06001668
John Kessenich140f3df2015-06-26 16:58:36 -06001669 glslang::TOperator binOp = glslang::EOpNull;
1670 bool reduceComparison = true;
1671 bool isMatrix = false;
1672 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001673 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001674
1675 assert(node->getOp());
1676
John Kessenichf6640762016-08-01 19:44:00 -06001677 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001678
1679 switch (node->getOp()) {
1680 case glslang::EOpSequence:
1681 {
1682 if (preVisit)
1683 ++sequenceDepth;
1684 else
1685 --sequenceDepth;
1686
1687 if (sequenceDepth == 1) {
1688 // If this is the parent node of all the functions, we want to see them
1689 // early, so all call points have actual SPIR-V functions to reference.
1690 // In all cases, still let the traverser visit the children for us.
1691 makeFunctions(node->getAsAggregate()->getSequence());
1692
John Kessenich6fccb3c2016-09-19 16:01:41 -06001693 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001694 // anything else gets there, so visit out of order, doing them all now.
1695 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1696
John Kessenich6a60c2f2016-12-08 21:01:59 -07001697 // 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 -06001698 // so do them manually.
1699 visitFunctions(node->getAsAggregate()->getSequence());
1700
1701 return false;
1702 }
1703
1704 return true;
1705 }
1706 case glslang::EOpLinkerObjects:
1707 {
1708 if (visit == glslang::EvPreVisit)
1709 linkageOnly = true;
1710 else
1711 linkageOnly = false;
1712
1713 return true;
1714 }
1715 case glslang::EOpComma:
1716 {
1717 // processing from left to right naturally leaves the right-most
1718 // lying around in the access chain
1719 glslang::TIntermSequence& glslangOperands = node->getSequence();
1720 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1721 glslangOperands[i]->traverse(this);
1722
1723 return false;
1724 }
1725 case glslang::EOpFunction:
1726 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001727 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001728 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001729 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001730 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001731 } else {
1732 handleFunctionEntry(node);
1733 }
1734 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001735 if (inEntryPoint)
1736 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001737 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001738 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001739 }
1740
1741 return true;
1742 case glslang::EOpParameters:
1743 // Parameters will have been consumed by EOpFunction processing, but not
1744 // the body, so we still visited the function node's children, making this
1745 // child redundant.
1746 return false;
1747 case glslang::EOpFunctionCall:
1748 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001749 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001750 if (node->isUserDefined())
1751 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001752 // 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 -07001753 if (result) {
1754 builder.clearAccessChain();
1755 builder.setAccessChainRValue(result);
1756 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001757 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001758
1759 return false;
1760 }
1761 case glslang::EOpConstructMat2x2:
1762 case glslang::EOpConstructMat2x3:
1763 case glslang::EOpConstructMat2x4:
1764 case glslang::EOpConstructMat3x2:
1765 case glslang::EOpConstructMat3x3:
1766 case glslang::EOpConstructMat3x4:
1767 case glslang::EOpConstructMat4x2:
1768 case glslang::EOpConstructMat4x3:
1769 case glslang::EOpConstructMat4x4:
1770 case glslang::EOpConstructDMat2x2:
1771 case glslang::EOpConstructDMat2x3:
1772 case glslang::EOpConstructDMat2x4:
1773 case glslang::EOpConstructDMat3x2:
1774 case glslang::EOpConstructDMat3x3:
1775 case glslang::EOpConstructDMat3x4:
1776 case glslang::EOpConstructDMat4x2:
1777 case glslang::EOpConstructDMat4x3:
1778 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001779 case glslang::EOpConstructIMat2x2:
1780 case glslang::EOpConstructIMat2x3:
1781 case glslang::EOpConstructIMat2x4:
1782 case glslang::EOpConstructIMat3x2:
1783 case glslang::EOpConstructIMat3x3:
1784 case glslang::EOpConstructIMat3x4:
1785 case glslang::EOpConstructIMat4x2:
1786 case glslang::EOpConstructIMat4x3:
1787 case glslang::EOpConstructIMat4x4:
1788 case glslang::EOpConstructUMat2x2:
1789 case glslang::EOpConstructUMat2x3:
1790 case glslang::EOpConstructUMat2x4:
1791 case glslang::EOpConstructUMat3x2:
1792 case glslang::EOpConstructUMat3x3:
1793 case glslang::EOpConstructUMat3x4:
1794 case glslang::EOpConstructUMat4x2:
1795 case glslang::EOpConstructUMat4x3:
1796 case glslang::EOpConstructUMat4x4:
1797 case glslang::EOpConstructBMat2x2:
1798 case glslang::EOpConstructBMat2x3:
1799 case glslang::EOpConstructBMat2x4:
1800 case glslang::EOpConstructBMat3x2:
1801 case glslang::EOpConstructBMat3x3:
1802 case glslang::EOpConstructBMat3x4:
1803 case glslang::EOpConstructBMat4x2:
1804 case glslang::EOpConstructBMat4x3:
1805 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001806 case glslang::EOpConstructF16Mat2x2:
1807 case glslang::EOpConstructF16Mat2x3:
1808 case glslang::EOpConstructF16Mat2x4:
1809 case glslang::EOpConstructF16Mat3x2:
1810 case glslang::EOpConstructF16Mat3x3:
1811 case glslang::EOpConstructF16Mat3x4:
1812 case glslang::EOpConstructF16Mat4x2:
1813 case glslang::EOpConstructF16Mat4x3:
1814 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06001815 isMatrix = true;
1816 // fall through
1817 case glslang::EOpConstructFloat:
1818 case glslang::EOpConstructVec2:
1819 case glslang::EOpConstructVec3:
1820 case glslang::EOpConstructVec4:
1821 case glslang::EOpConstructDouble:
1822 case glslang::EOpConstructDVec2:
1823 case glslang::EOpConstructDVec3:
1824 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001825 case glslang::EOpConstructFloat16:
1826 case glslang::EOpConstructF16Vec2:
1827 case glslang::EOpConstructF16Vec3:
1828 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001829 case glslang::EOpConstructBool:
1830 case glslang::EOpConstructBVec2:
1831 case glslang::EOpConstructBVec3:
1832 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07001833 case glslang::EOpConstructInt8:
1834 case glslang::EOpConstructI8Vec2:
1835 case glslang::EOpConstructI8Vec3:
1836 case glslang::EOpConstructI8Vec4:
1837 case glslang::EOpConstructUint8:
1838 case glslang::EOpConstructU8Vec2:
1839 case glslang::EOpConstructU8Vec3:
1840 case glslang::EOpConstructU8Vec4:
1841 case glslang::EOpConstructInt16:
1842 case glslang::EOpConstructI16Vec2:
1843 case glslang::EOpConstructI16Vec3:
1844 case glslang::EOpConstructI16Vec4:
1845 case glslang::EOpConstructUint16:
1846 case glslang::EOpConstructU16Vec2:
1847 case glslang::EOpConstructU16Vec3:
1848 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001849 case glslang::EOpConstructInt:
1850 case glslang::EOpConstructIVec2:
1851 case glslang::EOpConstructIVec3:
1852 case glslang::EOpConstructIVec4:
1853 case glslang::EOpConstructUint:
1854 case glslang::EOpConstructUVec2:
1855 case glslang::EOpConstructUVec3:
1856 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001857 case glslang::EOpConstructInt64:
1858 case glslang::EOpConstructI64Vec2:
1859 case glslang::EOpConstructI64Vec3:
1860 case glslang::EOpConstructI64Vec4:
1861 case glslang::EOpConstructUint64:
1862 case glslang::EOpConstructU64Vec2:
1863 case glslang::EOpConstructU64Vec3:
1864 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001865 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001866 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001867 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001868 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001869 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001870 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001871 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001872 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001873 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001874 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001875 std::vector<spv::Id> constituents;
1876 for (int c = 0; c < (int)arguments.size(); ++c)
1877 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001878 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001879 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001880 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001881 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001882 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001883
1884 builder.clearAccessChain();
1885 builder.setAccessChainRValue(constructed);
1886
1887 return false;
1888 }
1889
1890 // These six are component-wise compares with component-wise results.
1891 // Forward on to createBinaryOperation(), requesting a vector result.
1892 case glslang::EOpLessThan:
1893 case glslang::EOpGreaterThan:
1894 case glslang::EOpLessThanEqual:
1895 case glslang::EOpGreaterThanEqual:
1896 case glslang::EOpVectorEqual:
1897 case glslang::EOpVectorNotEqual:
1898 {
1899 // Map the operation to a binary
1900 binOp = node->getOp();
1901 reduceComparison = false;
1902 switch (node->getOp()) {
1903 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1904 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1905 default: binOp = node->getOp(); break;
1906 }
1907
1908 break;
1909 }
1910 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001911 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001912 binOp = glslang::EOpMul;
1913 break;
1914 case glslang::EOpOuterProduct:
1915 // two vectors multiplied to make a matrix
1916 binOp = glslang::EOpOuterProduct;
1917 break;
1918 case glslang::EOpDot:
1919 {
qining25262b32016-05-06 17:25:16 -04001920 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001921 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001922 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001923 binOp = glslang::EOpMul;
1924 break;
1925 }
1926 case glslang::EOpMod:
1927 // when an aggregate, this is the floating-point mod built-in function,
1928 // which can be emitted by the one in createBinaryOperation()
1929 binOp = glslang::EOpMod;
1930 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001931 case glslang::EOpEmitVertex:
1932 case glslang::EOpEndPrimitive:
1933 case glslang::EOpBarrier:
1934 case glslang::EOpMemoryBarrier:
1935 case glslang::EOpMemoryBarrierAtomicCounter:
1936 case glslang::EOpMemoryBarrierBuffer:
1937 case glslang::EOpMemoryBarrierImage:
1938 case glslang::EOpMemoryBarrierShared:
1939 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07001940 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001941 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07001942 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001943 case glslang::EOpWorkgroupMemoryBarrier:
1944 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07001945 case glslang::EOpSubgroupBarrier:
1946 case glslang::EOpSubgroupMemoryBarrier:
1947 case glslang::EOpSubgroupMemoryBarrierBuffer:
1948 case glslang::EOpSubgroupMemoryBarrierImage:
1949 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06001950 noReturnValue = true;
1951 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1952 break;
1953
John Kessenich426394d2015-07-23 10:22:48 -06001954 case glslang::EOpAtomicAdd:
1955 case glslang::EOpAtomicMin:
1956 case glslang::EOpAtomicMax:
1957 case glslang::EOpAtomicAnd:
1958 case glslang::EOpAtomicOr:
1959 case glslang::EOpAtomicXor:
1960 case glslang::EOpAtomicExchange:
1961 case glslang::EOpAtomicCompSwap:
1962 atomic = true;
1963 break;
1964
John Kessenich0d0c6d32017-07-23 16:08:26 -06001965 case glslang::EOpAtomicCounterAdd:
1966 case glslang::EOpAtomicCounterSubtract:
1967 case glslang::EOpAtomicCounterMin:
1968 case glslang::EOpAtomicCounterMax:
1969 case glslang::EOpAtomicCounterAnd:
1970 case glslang::EOpAtomicCounterOr:
1971 case glslang::EOpAtomicCounterXor:
1972 case glslang::EOpAtomicCounterExchange:
1973 case glslang::EOpAtomicCounterCompSwap:
1974 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1975 builder.addCapability(spv::CapabilityAtomicStorageOps);
1976 atomic = true;
1977 break;
1978
John Kessenich140f3df2015-06-26 16:58:36 -06001979 default:
1980 break;
1981 }
1982
1983 //
1984 // See if it maps to a regular operation.
1985 //
John Kessenich140f3df2015-06-26 16:58:36 -06001986 if (binOp != glslang::EOpNull) {
1987 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1988 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1989 assert(left && right);
1990
1991 builder.clearAccessChain();
1992 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001993 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001994
1995 builder.clearAccessChain();
1996 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001997 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001998
John Kesseniche485c7a2017-05-31 18:50:53 -06001999 builder.setLine(node->getLoc().line);
John Kessenichead86222018-03-28 18:01:20 -06002000 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002001 TranslateNoContractionDecoration(node->getType().getQualifier()),
2002 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002003 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002004 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002005 left->getType().getBasicType(), reduceComparison);
2006
2007 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002008 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002009 builder.clearAccessChain();
2010 builder.setAccessChainRValue(result);
2011
2012 return false;
2013 }
2014
John Kessenich426394d2015-07-23 10:22:48 -06002015 //
2016 // Create the list of operands.
2017 //
John Kessenich140f3df2015-06-26 16:58:36 -06002018 glslang::TIntermSequence& glslangOperands = node->getSequence();
2019 std::vector<spv::Id> operands;
2020 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002021 // special case l-value operands; there are just a few
2022 bool lvalue = false;
2023 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002024 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002025 case glslang::EOpModf:
2026 if (arg == 1)
2027 lvalue = true;
2028 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002029 case glslang::EOpInterpolateAtSample:
2030 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002031#ifdef AMD_EXTENSIONS
2032 case glslang::EOpInterpolateAtVertex:
2033#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002034 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002035 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002036
2037 // Does it need a swizzle inversion? If so, evaluation is inverted;
2038 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002039 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002040 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2041 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2042 }
Rex Xu7a26c172015-12-08 17:12:09 +08002043 break;
Rex Xud4782c12015-09-06 16:30:11 +08002044 case glslang::EOpAtomicAdd:
2045 case glslang::EOpAtomicMin:
2046 case glslang::EOpAtomicMax:
2047 case glslang::EOpAtomicAnd:
2048 case glslang::EOpAtomicOr:
2049 case glslang::EOpAtomicXor:
2050 case glslang::EOpAtomicExchange:
2051 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002052 case glslang::EOpAtomicCounterAdd:
2053 case glslang::EOpAtomicCounterSubtract:
2054 case glslang::EOpAtomicCounterMin:
2055 case glslang::EOpAtomicCounterMax:
2056 case glslang::EOpAtomicCounterAnd:
2057 case glslang::EOpAtomicCounterOr:
2058 case glslang::EOpAtomicCounterXor:
2059 case glslang::EOpAtomicCounterExchange:
2060 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002061 if (arg == 0)
2062 lvalue = true;
2063 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002064 case glslang::EOpAddCarry:
2065 case glslang::EOpSubBorrow:
2066 if (arg == 2)
2067 lvalue = true;
2068 break;
2069 case glslang::EOpUMulExtended:
2070 case glslang::EOpIMulExtended:
2071 if (arg >= 2)
2072 lvalue = true;
2073 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002074 default:
2075 break;
2076 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002077 builder.clearAccessChain();
2078 if (invertedType != spv::NoType && arg == 0)
2079 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2080 else
2081 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002082 if (lvalue)
2083 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002084 else {
2085 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07002086 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002087 }
John Kessenich140f3df2015-06-26 16:58:36 -06002088 }
John Kessenich426394d2015-07-23 10:22:48 -06002089
John Kesseniche485c7a2017-05-31 18:50:53 -06002090 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06002091 if (atomic) {
2092 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002093 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002094 } else {
2095 // Pass through to generic operations.
2096 switch (glslangOperands.size()) {
2097 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002098 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002099 break;
2100 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002101 {
2102 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002103 TranslateNoContractionDecoration(node->getType().getQualifier()),
2104 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002105 result = createUnaryOperation(
2106 node->getOp(), decorations,
2107 resultType(), operands.front(),
2108 glslangOperands[0]->getAsTyped()->getBasicType());
2109 }
John Kessenich426394d2015-07-23 10:22:48 -06002110 break;
2111 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002112 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002113 break;
2114 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002115 if (invertedType)
2116 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002117 }
2118
2119 if (noReturnValue)
2120 return false;
2121
2122 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002123 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002124 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002125 } else {
2126 builder.clearAccessChain();
2127 builder.setAccessChainRValue(result);
2128 return false;
2129 }
2130}
2131
John Kessenich433e9ff2017-01-26 20:31:11 -07002132// This path handles both if-then-else and ?:
2133// The if-then-else has a node type of void, while
2134// ?: has either a void or a non-void node type
2135//
2136// Leaving the result, when not void:
2137// GLSL only has r-values as the result of a :?, but
2138// if we have an l-value, that can be more efficient if it will
2139// become the base of a complex r-value expression, because the
2140// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002141bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2142{
John Kessenich4bee5312018-02-20 21:29:05 -07002143 // See if it simple and safe, or required, to execute both sides.
2144 // Crucially, side effects must be either semantically required or avoided,
2145 // and there are performance trade-offs.
2146 // Return true if required or a good idea (and safe) to execute both sides,
2147 // false otherwise.
2148 const auto bothSidesPolicy = [&]() -> bool {
2149 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002150 if (node->getTrueBlock() == nullptr ||
2151 node->getFalseBlock() == nullptr)
2152 return false;
2153
John Kessenich4bee5312018-02-20 21:29:05 -07002154 // required? (unless we write additional code to look for side effects
2155 // and make performance trade-offs if none are present)
2156 if (!node->getShortCircuit())
2157 return true;
2158
2159 // if not required to execute both, decide based on performance/practicality...
2160
2161 // see if OpSelect can handle it
2162 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2163 node->getBasicType() == glslang::EbtVoid)
2164 return false;
2165
John Kessenich433e9ff2017-01-26 20:31:11 -07002166 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2167 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2168
2169 // return true if a single operand to ? : is okay for OpSelect
2170 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002171 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002172 };
2173
2174 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2175 operandOkay(node->getFalseBlock()->getAsTyped());
2176 };
2177
John Kessenich4bee5312018-02-20 21:29:05 -07002178 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2179 // emit the condition before doing anything with selection
2180 node->getCondition()->traverse(this);
2181 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2182
2183 // Find a way of executing both sides and selecting the right result.
2184 const auto executeBothSides = [&]() -> void {
2185 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002186 node->getTrueBlock()->traverse(this);
2187 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2188 node->getFalseBlock()->traverse(this);
2189 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2190
John Kesseniche485c7a2017-05-31 18:50:53 -06002191 builder.setLine(node->getLoc().line);
2192
John Kessenich4bee5312018-02-20 21:29:05 -07002193 // done if void
2194 if (node->getBasicType() == glslang::EbtVoid)
2195 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002196
John Kessenich4bee5312018-02-20 21:29:05 -07002197 // emit code to select between trueValue and falseValue
2198
2199 // see if OpSelect can handle it
2200 if (node->getType().isScalar() || node->getType().isVector()) {
2201 // Emit OpSelect for this selection.
2202
2203 // smear condition to vector, if necessary (AST is always scalar)
2204 if (builder.isVector(trueValue))
2205 condition = builder.smearScalar(spv::NoPrecision, condition,
2206 builder.makeVectorType(builder.makeBoolType(),
2207 builder.getNumComponents(trueValue)));
2208
2209 // OpSelect
2210 result = builder.createTriOp(spv::OpSelect,
2211 convertGlslangToSpvType(node->getType()), condition,
2212 trueValue, falseValue);
2213
2214 builder.clearAccessChain();
2215 builder.setAccessChainRValue(result);
2216 } else {
2217 // We need control flow to select the result.
2218 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2219 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2220
2221 // Selection control:
2222 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2223
2224 // make an "if" based on the value created by the condition
2225 spv::Builder::If ifBuilder(condition, control, builder);
2226
2227 // emit the "then" statement
2228 builder.createStore(trueValue, result);
2229 ifBuilder.makeBeginElse();
2230 // emit the "else" statement
2231 builder.createStore(falseValue, result);
2232
2233 // finish off the control flow
2234 ifBuilder.makeEndIf();
2235
2236 builder.clearAccessChain();
2237 builder.setAccessChainLValue(result);
2238 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002239 };
2240
John Kessenich4bee5312018-02-20 21:29:05 -07002241 // Execute the one side needed, as per the condition
2242 const auto executeOneSide = [&]() {
2243 // Always emit control flow.
2244 if (node->getBasicType() != glslang::EbtVoid)
2245 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002246
John Kessenich4bee5312018-02-20 21:29:05 -07002247 // Selection control:
2248 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2249
2250 // make an "if" based on the value created by the condition
2251 spv::Builder::If ifBuilder(condition, control, builder);
2252
2253 // emit the "then" statement
2254 if (node->getTrueBlock() != nullptr) {
2255 node->getTrueBlock()->traverse(this);
2256 if (result != spv::NoResult)
2257 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2258 }
2259
2260 if (node->getFalseBlock() != nullptr) {
2261 ifBuilder.makeBeginElse();
2262 // emit the "else" statement
2263 node->getFalseBlock()->traverse(this);
2264 if (result != spv::NoResult)
2265 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2266 }
2267
2268 // finish off the control flow
2269 ifBuilder.makeEndIf();
2270
2271 if (result != spv::NoResult) {
2272 builder.clearAccessChain();
2273 builder.setAccessChainLValue(result);
2274 }
2275 };
2276
2277 // Try for OpSelect (or a requirement to execute both sides)
2278 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002279 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2280 if (node->getType().getQualifier().isSpecConstant())
2281 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002282 executeBothSides();
2283 } else
2284 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002285
2286 return false;
2287}
2288
2289bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2290{
2291 // emit and get the condition before doing anything with switch
2292 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002293 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002294
Rex Xu57e65922017-07-04 23:23:40 +08002295 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002296 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002297
John Kessenich140f3df2015-06-26 16:58:36 -06002298 // browse the children to sort out code segments
2299 int defaultSegment = -1;
2300 std::vector<TIntermNode*> codeSegments;
2301 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2302 std::vector<int> caseValues;
2303 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2304 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2305 TIntermNode* child = *c;
2306 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002307 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002308 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002309 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002310 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2311 } else
2312 codeSegments.push_back(child);
2313 }
2314
qining25262b32016-05-06 17:25:16 -04002315 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002316 // statements between the last case and the end of the switch statement
2317 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2318 (int)codeSegments.size() == defaultSegment)
2319 codeSegments.push_back(nullptr);
2320
2321 // make the switch statement
2322 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002323 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002324
2325 // emit all the code in the segments
2326 breakForLoop.push(false);
2327 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2328 builder.nextSwitchSegment(segmentBlocks, s);
2329 if (codeSegments[s])
2330 codeSegments[s]->traverse(this);
2331 else
2332 builder.addSwitchBreak();
2333 }
2334 breakForLoop.pop();
2335
2336 builder.endSwitch(segmentBlocks);
2337
2338 return false;
2339}
2340
2341void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2342{
2343 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002344 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002345
2346 builder.clearAccessChain();
2347 builder.setAccessChainRValue(constant);
2348}
2349
2350bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2351{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002352 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002353 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002354
2355 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002356 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2357 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002358
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002359 // Spec requires back edges to target header blocks, and every header block
2360 // must dominate its merge block. Make a header block first to ensure these
2361 // conditions are met. By definition, it will contain OpLoopMerge, followed
2362 // by a block-ending branch. But we don't want to put any other body/test
2363 // instructions in it, since the body/test may have arbitrary instructions,
2364 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002365 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002366 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002367 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002368 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002369 spv::Block& test = builder.makeNewBlock();
2370 builder.createBranch(&test);
2371
2372 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002373 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002374 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002375 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2376
2377 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002378 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002379 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002380 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002381 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002382 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002383
2384 builder.setBuildPoint(&blocks.continue_target);
2385 if (node->getTerminal())
2386 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002387 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002388 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002389 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002390 builder.createBranch(&blocks.body);
2391
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002392 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002393 builder.setBuildPoint(&blocks.body);
2394 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002395 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002396 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002397 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002398
2399 builder.setBuildPoint(&blocks.continue_target);
2400 if (node->getTerminal())
2401 node->getTerminal()->traverse(this);
2402 if (node->getTest()) {
2403 node->getTest()->traverse(this);
2404 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002405 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002406 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002407 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002408 // TODO: unless there was a break/return/discard instruction
2409 // somewhere in the body, this is an infinite loop, so we should
2410 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002411 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002412 }
John Kessenich140f3df2015-06-26 16:58:36 -06002413 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002414 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002415 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002416 return false;
2417}
2418
2419bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2420{
2421 if (node->getExpression())
2422 node->getExpression()->traverse(this);
2423
John Kesseniche485c7a2017-05-31 18:50:53 -06002424 builder.setLine(node->getLoc().line);
2425
John Kessenich140f3df2015-06-26 16:58:36 -06002426 switch (node->getFlowOp()) {
2427 case glslang::EOpKill:
2428 builder.makeDiscard();
2429 break;
2430 case glslang::EOpBreak:
2431 if (breakForLoop.top())
2432 builder.createLoopExit();
2433 else
2434 builder.addSwitchBreak();
2435 break;
2436 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002437 builder.createLoopContinue();
2438 break;
2439 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002440 if (node->getExpression()) {
2441 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2442 spv::Id returnId = accessChainLoad(glslangReturnType);
2443 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2444 builder.clearAccessChain();
2445 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2446 builder.setAccessChainLValue(copyId);
2447 multiTypeStore(glslangReturnType, returnId);
2448 returnId = builder.createLoad(copyId);
2449 }
2450 builder.makeReturn(false, returnId);
2451 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002452 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002453
2454 builder.clearAccessChain();
2455 break;
2456
2457 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002458 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002459 break;
2460 }
2461
2462 return false;
2463}
2464
2465spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2466{
qining25262b32016-05-06 17:25:16 -04002467 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002468 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002469 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002470 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002471 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002472 }
2473
2474 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002475 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002476 spv::Id spvType = convertGlslangToSpvType(node->getType());
2477
Rex Xucabbb782017-03-24 13:41:14 +08002478 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2479 node->getType().containsBasicType(glslang::EbtInt16) ||
2480 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002481 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002482 switch (storageClass) {
2483 case spv::StorageClassInput:
2484 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002485 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002486 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002487 break;
2488 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07002489 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002490 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06002491 break;
2492 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07002493 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002494 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2495 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06002496 else
2497 builder.addCapability(spv::CapabilityStorageUniform16);
2498 break;
2499 case spv::StorageClassStorageBuffer:
2500 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
2501 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2502 break;
2503 default:
2504 break;
Rex Xuf89ad982017-04-07 23:22:33 +08002505 }
2506 }
Rex Xuf89ad982017-04-07 23:22:33 +08002507
John Kessenich140f3df2015-06-26 16:58:36 -06002508 const char* name = node->getName().c_str();
2509 if (glslang::IsAnonymous(name))
2510 name = "";
2511
2512 return builder.createVariable(storageClass, spvType, name);
2513}
2514
2515// Return type Id of the sampled type.
2516spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2517{
2518 switch (sampler.type) {
2519 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08002520#ifdef AMD_EXTENSIONS
2521 case glslang::EbtFloat16:
2522 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
2523 builder.addCapability(spv::CapabilityFloat16ImageAMD);
2524 return builder.makeFloatType(16);
2525#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002526 case glslang::EbtInt: return builder.makeIntType(32);
2527 case glslang::EbtUint: return builder.makeUintType(32);
2528 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002529 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002530 return builder.makeFloatType(32);
2531 }
2532}
2533
John Kessenich8c8505c2016-07-26 12:50:38 -06002534// If node is a swizzle operation, return the type that should be used if
2535// the swizzle base is first consumed by another operation, before the swizzle
2536// is applied.
2537spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2538{
John Kessenichecba76f2017-01-06 00:34:48 -07002539 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002540 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2541 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2542 else
2543 return spv::NoType;
2544}
2545
2546// When inverting a swizzle with a parent op, this function
2547// will apply the swizzle operation to a completed parent operation.
2548spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2549{
2550 std::vector<unsigned> swizzle;
2551 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2552 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2553}
2554
John Kessenich8c8505c2016-07-26 12:50:38 -06002555// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2556void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2557{
2558 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2559 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2560 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2561}
2562
John Kessenich3ac051e2015-12-20 11:29:16 -07002563// Convert from a glslang type to an SPV type, by calling into a
2564// recursive version of this function. This establishes the inherited
2565// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002566spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2567{
John Kessenichead86222018-03-28 18:01:20 -06002568 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false);
John Kessenich31ed4832015-09-09 17:51:38 -06002569}
2570
2571// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002572// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002573// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06002574spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
2575 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier, bool lastBufferBlockMember)
John Kessenich31ed4832015-09-09 17:51:38 -06002576{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002577 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002578
2579 switch (type.getBasicType()) {
2580 case glslang::EbtVoid:
2581 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002582 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002583 break;
2584 case glslang::EbtFloat:
2585 spvType = builder.makeFloatType(32);
2586 break;
2587 case glslang::EbtDouble:
2588 spvType = builder.makeFloatType(64);
2589 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002590 case glslang::EbtFloat16:
John Kessenich66011cb2018-03-06 16:12:04 -07002591 builder.addCapability(spv::CapabilityFloat16);
2592#if AMD_EXTENSIONS
2593 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2594 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
2595#endif
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002596 spvType = builder.makeFloatType(16);
2597 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002598 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002599 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2600 // a 32-bit int where non-0 means true.
2601 if (explicitLayout != glslang::ElpNone)
2602 spvType = builder.makeUintType(32);
2603 else
2604 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002605 break;
John Kessenich66011cb2018-03-06 16:12:04 -07002606 case glslang::EbtInt8:
2607 builder.addCapability(spv::CapabilityInt8);
2608 spvType = builder.makeIntType(8);
2609 break;
2610 case glslang::EbtUint8:
2611 builder.addCapability(spv::CapabilityInt8);
2612 spvType = builder.makeUintType(8);
2613 break;
2614 case glslang::EbtInt16:
2615 builder.addCapability(spv::CapabilityInt16);
2616#ifdef AMD_EXTENSIONS
2617 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2618 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2619#endif
2620 spvType = builder.makeIntType(16);
2621 break;
2622 case glslang::EbtUint16:
2623 builder.addCapability(spv::CapabilityInt16);
2624#ifdef AMD_EXTENSIONS
2625 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2626 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2627#endif
2628 spvType = builder.makeUintType(16);
2629 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002630 case glslang::EbtInt:
2631 spvType = builder.makeIntType(32);
2632 break;
2633 case glslang::EbtUint:
2634 spvType = builder.makeUintType(32);
2635 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002636 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002637 spvType = builder.makeIntType(64);
2638 break;
2639 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002640 spvType = builder.makeUintType(64);
2641 break;
John Kessenich426394d2015-07-23 10:22:48 -06002642 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002643 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002644 spvType = builder.makeUintType(32);
2645 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002646 case glslang::EbtSampler:
2647 {
2648 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002649 if (sampler.sampler) {
2650 // pure sampler
2651 spvType = builder.makeSamplerType();
2652 } else {
2653 // an image is present, make its type
2654 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2655 sampler.image ? 2 : 1, TranslateImageFormat(type));
2656 if (sampler.combined) {
2657 // already has both image and sampler, make the combined type
2658 spvType = builder.makeSampledImageType(spvType);
2659 }
John Kessenich55e7d112015-11-15 21:33:39 -07002660 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002661 }
John Kessenich140f3df2015-06-26 16:58:36 -06002662 break;
2663 case glslang::EbtStruct:
2664 case glslang::EbtBlock:
2665 {
2666 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002667 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002668
2669 // Try to share structs for different layouts, but not yet for other
2670 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002671 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002672 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002673 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002674 break;
2675
2676 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002677 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002678 memberRemapper[glslangMembers].resize(glslangMembers->size());
2679 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002680 }
2681 break;
2682 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002683 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002684 break;
2685 }
2686
2687 if (type.isMatrix())
2688 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2689 else {
2690 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2691 if (type.getVectorSize() > 1)
2692 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2693 }
2694
2695 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002696 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2697
John Kessenichc9a80832015-09-12 12:17:44 -06002698 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002699 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002700 // We need to decorate array strides for types needing explicit layout, except blocks.
2701 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002702 // Use a dummy glslang type for querying internal strides of
2703 // arrays of arrays, but using just a one-dimensional array.
2704 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06002705 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
2706 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07002707
2708 // Will compute the higher-order strides here, rather than making a whole
2709 // pile of types and doing repetitive recursion on their contents.
2710 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2711 }
John Kessenichf8842e52016-01-04 19:22:56 -07002712
2713 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002714 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002715 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002716 if (stride > 0)
2717 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002718 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002719 }
2720 } else {
2721 // single-dimensional array, and don't yet have stride
2722
John Kessenichf8842e52016-01-04 19:22:56 -07002723 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002724 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2725 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002726 }
John Kessenich31ed4832015-09-09 17:51:38 -06002727
John Kessenichead86222018-03-28 18:01:20 -06002728 // Do the outer dimension, which might not be known for a runtime-sized array.
2729 // (Unsized arrays that survive through linking will be runtime-sized arrays)
2730 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07002731 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06002732 else {
2733 if (!lastBufferBlockMember) {
2734 builder.addExtension("SPV_EXT_descriptor_indexing");
2735 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
2736 }
John Kessenichead86222018-03-28 18:01:20 -06002737 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06002738 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002739 if (stride > 0)
2740 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002741 }
2742
2743 return spvType;
2744}
2745
John Kessenich0e737842017-03-24 18:38:16 -06002746// TODO: this functionality should exist at a higher level, in creating the AST
2747//
2748// Identify interface members that don't have their required extension turned on.
2749//
2750bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2751{
2752 auto& extensions = glslangIntermediate->getRequestedExtensions();
2753
Rex Xubcf291a2017-03-29 23:01:36 +08002754 if (member.getFieldName() == "gl_ViewportMask" &&
2755 extensions.find("GL_NV_viewport_array2") == extensions.end())
2756 return true;
2757 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2758 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2759 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002760 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2761 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2762 return true;
2763 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2764 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2765 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002766 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2767 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2768 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002769
2770 return false;
2771};
2772
John Kessenich6090df02016-06-30 21:18:02 -06002773// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2774// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2775// Mutually recursive with convertGlslangToSpvType().
2776spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2777 const glslang::TTypeList* glslangMembers,
2778 glslang::TLayoutPacking explicitLayout,
2779 const glslang::TQualifier& qualifier)
2780{
2781 // Create a vector of struct types for SPIR-V to consume
2782 std::vector<spv::Id> spvMembers;
2783 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 -06002784 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2785 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2786 if (glslangMember.hiddenMember()) {
2787 ++memberDelta;
2788 if (type.getBasicType() == glslang::EbtBlock)
2789 memberRemapper[glslangMembers][i] = -1;
2790 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002791 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002792 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002793 if (filterMember(glslangMember))
2794 continue;
2795 }
John Kessenich6090df02016-06-30 21:18:02 -06002796 // modify just this child's view of the qualifier
2797 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2798 InheritQualifiers(memberQualifier, qualifier);
2799
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002800 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002801 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002802 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002803
2804 // recurse
John Kessenichead86222018-03-28 18:01:20 -06002805 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
2806 i == (int)glslangMembers->size() - 1;
2807 spvMembers.push_back(
2808 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember));
John Kessenich6090df02016-06-30 21:18:02 -06002809 }
2810 }
2811
2812 // Make the SPIR-V type
2813 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002814 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002815 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2816
2817 // Decorate it
2818 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2819
2820 return spvType;
2821}
2822
2823void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2824 const glslang::TTypeList* glslangMembers,
2825 glslang::TLayoutPacking explicitLayout,
2826 const glslang::TQualifier& qualifier,
2827 spv::Id spvType)
2828{
2829 // Name and decorate the non-hidden members
2830 int offset = -1;
2831 int locationOffset = 0; // for use within the members of this struct
2832 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2833 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2834 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002835 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002836 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002837 if (filterMember(glslangMember))
2838 continue;
2839 }
John Kessenich6090df02016-06-30 21:18:02 -06002840
2841 // modify just this child's view of the qualifier
2842 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2843 InheritQualifiers(memberQualifier, qualifier);
2844
2845 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07002846 if (member < 0)
2847 continue;
2848
2849 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2850 builder.addMemberDecoration(spvType, member,
2851 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2852 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2853 // Add interpolation and auxiliary storage decorations only to
2854 // top-level members of Input and Output storage classes
2855 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2856 type.getQualifier().storage == glslang::EvqVaryingOut) {
2857 if (type.getBasicType() == glslang::EbtBlock ||
2858 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
2859 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2860 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002861 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002862 }
2863 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002864
John Kessenich5d610ee2018-03-07 18:05:55 -07002865 if (type.getBasicType() == glslang::EbtBlock &&
2866 qualifier.storage == glslang::EvqBuffer) {
2867 // Add memory decorations only to top-level members of shader storage block
2868 std::vector<spv::Decoration> memory;
2869 TranslateMemoryDecoration(memberQualifier, memory);
2870 for (unsigned int i = 0; i < memory.size(); ++i)
2871 builder.addMemberDecoration(spvType, member, memory[i]);
2872 }
John Kessenich6090df02016-06-30 21:18:02 -06002873
John Kessenich5d610ee2018-03-07 18:05:55 -07002874 // Location assignment was already completed correctly by the front end,
2875 // just track whether a member needs to be decorated.
2876 // Ignore member locations if the container is an array, as that's
2877 // ill-specified and decisions have been made to not allow this.
2878 if (! type.isArray() && memberQualifier.hasLocation())
2879 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002880
John Kessenich5d610ee2018-03-07 18:05:55 -07002881 if (qualifier.hasLocation()) // track for upcoming inheritance
2882 locationOffset += glslangIntermediate->computeTypeLocationSize(
2883 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06002884
John Kessenich5d610ee2018-03-07 18:05:55 -07002885 // component, XFB, others
2886 if (glslangMember.getQualifier().hasComponent())
2887 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
2888 glslangMember.getQualifier().layoutComponent);
2889 if (glslangMember.getQualifier().hasXfbOffset())
2890 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
2891 glslangMember.getQualifier().layoutXfbOffset);
2892 else if (explicitLayout != glslang::ElpNone) {
2893 // figure out what to do with offset, which is accumulating
2894 int nextOffset;
2895 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2896 if (offset >= 0)
2897 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2898 offset = nextOffset;
2899 }
John Kessenich6090df02016-06-30 21:18:02 -06002900
John Kessenich5d610ee2018-03-07 18:05:55 -07002901 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2902 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
2903 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06002904
John Kessenich5d610ee2018-03-07 18:05:55 -07002905 // built-in variable decorations
2906 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
2907 if (builtIn != spv::BuiltInMax)
2908 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002909
John Kessenich5611c6d2018-04-05 11:25:02 -06002910 // nonuniform
2911 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
2912
John Kessenichead86222018-03-28 18:01:20 -06002913 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
2914 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
2915 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
2916 memberQualifier.semanticName);
2917 }
2918
chaoc771d89f2017-01-13 01:10:53 -08002919#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07002920 if (builtIn == spv::BuiltInLayer) {
2921 // SPV_NV_viewport_array2 extension
2922 if (glslangMember.getQualifier().layoutViewportRelative){
2923 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2924 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2925 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08002926 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002927 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2928 builder.addMemberDecoration(spvType, member,
2929 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
2930 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2931 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2932 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08002933 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002934 }
2935 if (glslangMember.getQualifier().layoutPassthrough) {
2936 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2937 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2938 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2939 }
chaoc771d89f2017-01-13 01:10:53 -08002940#endif
John Kessenich6090df02016-06-30 21:18:02 -06002941 }
2942
2943 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07002944 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2945 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002946 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2947 builder.addCapability(spv::CapabilityGeometryStreams);
2948 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2949 }
John Kessenich6090df02016-06-30 21:18:02 -06002950}
2951
John Kessenich6c292d32016-02-15 20:58:50 -07002952// Turn the expression forming the array size into an id.
2953// This is not quite trivial, because of specialization constants.
2954// Sometimes, a raw constant is turned into an Id, and sometimes
2955// a specialization constant expression is.
2956spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2957{
2958 // First, see if this is sized with a node, meaning a specialization constant:
2959 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2960 if (specNode != nullptr) {
2961 builder.clearAccessChain();
2962 specNode->traverse(this);
2963 return accessChainLoad(specNode->getAsTyped()->getType());
2964 }
qining25262b32016-05-06 17:25:16 -04002965
John Kessenich6c292d32016-02-15 20:58:50 -07002966 // Otherwise, need a compile-time (front end) size, get it:
2967 int size = arraySizes.getDimSize(dim);
2968 assert(size > 0);
2969 return builder.makeUintConstant(size);
2970}
2971
John Kessenich103bef92016-02-08 21:38:15 -07002972// Wrap the builder's accessChainLoad to:
2973// - localize handling of RelaxedPrecision
2974// - use the SPIR-V inferred type instead of another conversion of the glslang type
2975// (avoids unnecessary work and possible type punning for structures)
2976// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002977spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2978{
John Kessenich103bef92016-02-08 21:38:15 -07002979 spv::Id nominalTypeId = builder.accessChainGetInferredType();
John Kessenich5611c6d2018-04-05 11:25:02 -06002980 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
2981 TranslateNonUniformDecoration(type.getQualifier()), nominalTypeId);
John Kessenich103bef92016-02-08 21:38:15 -07002982
2983 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002984 if (type.getBasicType() == glslang::EbtBool) {
2985 if (builder.isScalarType(nominalTypeId)) {
2986 // Conversion for bool
2987 spv::Id boolType = builder.makeBoolType();
2988 if (nominalTypeId != boolType)
2989 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2990 } else if (builder.isVectorType(nominalTypeId)) {
2991 // Conversion for bvec
2992 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2993 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2994 if (nominalTypeId != bvecType)
2995 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2996 }
2997 }
John Kessenich103bef92016-02-08 21:38:15 -07002998
2999 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003000}
3001
Rex Xu27253232016-02-23 17:51:09 +08003002// Wrap the builder's accessChainStore to:
3003// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003004//
3005// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003006void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3007{
3008 // Need to convert to abstract types when necessary
3009 if (type.getBasicType() == glslang::EbtBool) {
3010 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3011
3012 if (builder.isScalarType(nominalTypeId)) {
3013 // Conversion for bool
3014 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003015 if (nominalTypeId != boolType) {
3016 // keep these outside arguments, for determinant order-of-evaluation
3017 spv::Id one = builder.makeUintConstant(1);
3018 spv::Id zero = builder.makeUintConstant(0);
3019 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3020 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003021 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003022 } else if (builder.isVectorType(nominalTypeId)) {
3023 // Conversion for bvec
3024 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3025 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003026 if (nominalTypeId != bvecType) {
3027 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003028 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3029 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3030 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003031 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003032 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3033 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003034 }
3035 }
3036
3037 builder.accessChainStore(rvalue);
3038}
3039
John Kessenich4bf71552016-09-02 11:20:21 -06003040// For storing when types match at the glslang level, but not might match at the
3041// SPIR-V level.
3042//
3043// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003044// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003045// as in a member-decorated way.
3046//
3047// NOTE: This function can handle any store request; if it's not special it
3048// simplifies to a simple OpStore.
3049//
3050// Implicitly uses the existing builder.accessChain as the storage target.
3051void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3052{
John Kessenichb3e24e42016-09-11 12:33:43 -06003053 // we only do the complex path here if it's an aggregate
3054 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003055 accessChainStore(type, rValue);
3056 return;
3057 }
3058
John Kessenichb3e24e42016-09-11 12:33:43 -06003059 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003060 spv::Id rType = builder.getTypeId(rValue);
3061 spv::Id lValue = builder.accessChainGetLValue();
3062 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3063 if (lType == rType) {
3064 accessChainStore(type, rValue);
3065 return;
3066 }
3067
John Kessenichb3e24e42016-09-11 12:33:43 -06003068 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003069 // where the two types were the same type in GLSL. This requires member
3070 // by member copy, recursively.
3071
John Kessenichb3e24e42016-09-11 12:33:43 -06003072 // If an array, copy element by element.
3073 if (type.isArray()) {
3074 glslang::TType glslangElementType(type, 0);
3075 spv::Id elementRType = builder.getContainedTypeId(rType);
3076 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3077 // get the source member
3078 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003079
John Kessenichb3e24e42016-09-11 12:33:43 -06003080 // set up the target storage
3081 builder.clearAccessChain();
3082 builder.setAccessChainLValue(lValue);
3083 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06003084
John Kessenichb3e24e42016-09-11 12:33:43 -06003085 // store the member
3086 multiTypeStore(glslangElementType, elementRValue);
3087 }
3088 } else {
3089 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003090
John Kessenichb3e24e42016-09-11 12:33:43 -06003091 // loop over structure members
3092 const glslang::TTypeList& members = *type.getStruct();
3093 for (int m = 0; m < (int)members.size(); ++m) {
3094 const glslang::TType& glslangMemberType = *members[m].type;
3095
3096 // get the source member
3097 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3098 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3099
3100 // set up the target storage
3101 builder.clearAccessChain();
3102 builder.setAccessChainLValue(lValue);
3103 builder.accessChainPush(builder.makeIntConstant(m));
3104
3105 // store the member
3106 multiTypeStore(glslangMemberType, memberRValue);
3107 }
John Kessenich4bf71552016-09-02 11:20:21 -06003108 }
3109}
3110
John Kessenichf85e8062015-12-19 13:57:10 -07003111// Decide whether or not this type should be
3112// decorated with offsets and strides, and if so
3113// whether std140 or std430 rules should be applied.
3114glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003115{
John Kessenichf85e8062015-12-19 13:57:10 -07003116 // has to be a block
3117 if (type.getBasicType() != glslang::EbtBlock)
3118 return glslang::ElpNone;
3119
3120 // has to be a uniform or buffer block
3121 if (type.getQualifier().storage != glslang::EvqUniform &&
3122 type.getQualifier().storage != glslang::EvqBuffer)
3123 return glslang::ElpNone;
3124
3125 // return the layout to use
3126 switch (type.getQualifier().layoutPacking) {
3127 case glslang::ElpStd140:
3128 case glslang::ElpStd430:
3129 return type.getQualifier().layoutPacking;
3130 default:
3131 return glslang::ElpNone;
3132 }
John Kessenich31ed4832015-09-09 17:51:38 -06003133}
3134
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003135// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003136int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003137{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003138 int size;
John Kessenich49987892015-12-29 17:11:44 -07003139 int stride;
3140 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003141
3142 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003143}
3144
John Kessenich49987892015-12-29 17:11:44 -07003145// 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 -07003146// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003147int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003148{
John Kessenich49987892015-12-29 17:11:44 -07003149 glslang::TType elementType;
3150 elementType.shallowCopy(matrixType);
3151 elementType.clearArraySizes();
3152
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003153 int size;
John Kessenich49987892015-12-29 17:11:44 -07003154 int stride;
3155 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
3156
3157 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003158}
3159
John Kessenich5e4b1242015-08-06 22:53:06 -06003160// Given a member type of a struct, realign the current offset for it, and compute
3161// the next (not yet aligned) offset for the next member, which will get aligned
3162// on the next call.
3163// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3164// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3165// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003166void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003167 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003168{
3169 // this will get a positive value when deemed necessary
3170 nextOffset = -1;
3171
John Kessenich5e4b1242015-08-06 22:53:06 -06003172 // override anything in currentOffset with user-set offset
3173 if (memberType.getQualifier().hasOffset())
3174 currentOffset = memberType.getQualifier().layoutOffset;
3175
3176 // It could be that current linker usage in glslang updated all the layoutOffset,
3177 // in which case the following code does not matter. But, that's not quite right
3178 // once cross-compilation unit GLSL validation is done, as the original user
3179 // settings are needed in layoutOffset, and then the following will come into play.
3180
John Kessenichf85e8062015-12-19 13:57:10 -07003181 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003182 if (! memberType.getQualifier().hasOffset())
3183 currentOffset = -1;
3184
3185 return;
3186 }
3187
John Kessenichf85e8062015-12-19 13:57:10 -07003188 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003189 if (currentOffset < 0)
3190 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003191
John Kessenich5e4b1242015-08-06 22:53:06 -06003192 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3193 // but possibly not yet correctly aligned.
3194
3195 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003196 int dummyStride;
3197 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003198
3199 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003200 // TODO: make this consistent in early phases of code:
3201 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3202 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3203 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06003204 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003205 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003206 int dummySize;
3207 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3208 if (componentAlignment <= 4)
3209 memberAlignment = componentAlignment;
3210 }
3211
3212 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003213 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003214
3215 // Bump up to vec4 if there is a bad straddle
3216 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
3217 glslang::RoundToPow2(currentOffset, 16);
3218
John Kessenich5e4b1242015-08-06 22:53:06 -06003219 nextOffset = currentOffset + memberSize;
3220}
3221
David Netoa901ffe2016-06-08 14:11:40 +01003222void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003223{
David Netoa901ffe2016-06-08 14:11:40 +01003224 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3225 switch (glslangBuiltIn)
3226 {
3227 case glslang::EbvClipDistance:
3228 case glslang::EbvCullDistance:
3229 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003230#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003231 case glslang::EbvViewportMaskNV:
3232 case glslang::EbvSecondaryPositionNV:
3233 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003234 case glslang::EbvPositionPerViewNV:
3235 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08003236#endif
David Netoa901ffe2016-06-08 14:11:40 +01003237 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3238 // Alternately, we could just call this for any glslang built-in, since the
3239 // capability already guards against duplicates.
3240 TranslateBuiltInDecoration(glslangBuiltIn, false);
3241 break;
3242 default:
3243 // Capabilities were already generated when the struct was declared.
3244 break;
3245 }
John Kessenichebb50532016-05-16 19:22:05 -06003246}
3247
John Kessenich6fccb3c2016-09-19 16:01:41 -06003248bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003249{
John Kessenicheee9d532016-09-19 18:09:30 -06003250 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003251}
3252
John Kessenichd41993d2017-09-10 15:21:05 -06003253// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003254// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3255// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003256bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003257{
John Kessenich6a14f782017-12-04 02:48:10 -07003258 assert(qualifier == glslang::EvqIn ||
3259 qualifier == glslang::EvqOut ||
3260 qualifier == glslang::EvqInOut ||
3261 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003262 return qualifier != glslang::EvqConstReadOnly;
3263}
3264
3265// Is parameter pass-by-original?
3266bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3267 bool implicitThisParam)
3268{
3269 if (implicitThisParam) // implicit this
3270 return true;
3271 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003272 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003273 return paramType.containsOpaque() || // sampler, etc.
3274 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3275}
3276
John Kessenich140f3df2015-06-26 16:58:36 -06003277// Make all the functions, skeletally, without actually visiting their bodies.
3278void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3279{
John Kessenichfad62972017-07-18 02:35:46 -06003280 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
3281 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3282 if (paramPrecision != spv::NoPrecision)
3283 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06003284 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06003285 };
3286
John Kessenich140f3df2015-06-26 16:58:36 -06003287 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3288 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003289 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003290 continue;
3291
3292 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003293 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003294 //
qining25262b32016-05-06 17:25:16 -04003295 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003296 // function. What it is an address of varies:
3297 //
John Kessenich4bf71552016-09-02 11:20:21 -06003298 // - "in" parameters not marked as "const" can be written to without modifying the calling
3299 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003300 //
3301 // - "const in" parameters can just be the r-value, as no writes need occur.
3302 //
John Kessenich4bf71552016-09-02 11:20:21 -06003303 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3304 // 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 -06003305
3306 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003307 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003308 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3309
John Kessenichfad62972017-07-18 02:35:46 -06003310 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3311 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003312
John Kessenichfad62972017-07-18 02:35:46 -06003313 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003314 for (int p = 0; p < (int)parameters.size(); ++p) {
3315 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3316 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003317 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003318 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003319 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003320 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3321 else
John Kessenich4bf71552016-09-02 11:20:21 -06003322 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003323 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003324 paramTypes.push_back(typeId);
3325 }
3326
3327 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003328 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3329 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003330 glslFunction->getName().c_str(), paramTypes,
3331 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003332 if (implicitThis)
3333 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003334
3335 // Track function to emit/call later
3336 functionMap[glslFunction->getName().c_str()] = function;
3337
3338 // Set the parameter id's
3339 for (int p = 0; p < (int)parameters.size(); ++p) {
3340 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3341 // give a name too
3342 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3343 }
3344 }
3345}
3346
3347// Process all the initializers, while skipping the functions and link objects
3348void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3349{
3350 builder.setBuildPoint(shaderEntry->getLastBlock());
3351 for (int i = 0; i < (int)initializers.size(); ++i) {
3352 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3353 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3354
3355 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003356 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003357 initializer->traverse(this);
3358 }
3359 }
3360}
3361
3362// Process all the functions, while skipping initializers.
3363void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3364{
3365 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3366 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003367 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003368 node->traverse(this);
3369 }
3370}
3371
3372void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3373{
qining25262b32016-05-06 17:25:16 -04003374 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003375 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003376 currentFunction = functionMap[node->getName().c_str()];
3377 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003378 builder.setBuildPoint(functionBlock);
3379}
3380
Rex Xu04db3f52015-09-16 11:44:02 +08003381void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003382{
Rex Xufc618912015-09-09 16:42:49 +08003383 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003384
3385 glslang::TSampler sampler = {};
3386 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003387#ifdef AMD_EXTENSIONS
3388 bool f16ShadowCompare = false;
3389#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003390 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003391 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3392 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003393#ifdef AMD_EXTENSIONS
3394 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3395#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003396 }
3397
John Kessenich140f3df2015-06-26 16:58:36 -06003398 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3399 builder.clearAccessChain();
3400 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003401
3402 // Special case l-value operands
3403 bool lvalue = false;
3404 switch (node.getOp()) {
3405 case glslang::EOpImageAtomicAdd:
3406 case glslang::EOpImageAtomicMin:
3407 case glslang::EOpImageAtomicMax:
3408 case glslang::EOpImageAtomicAnd:
3409 case glslang::EOpImageAtomicOr:
3410 case glslang::EOpImageAtomicXor:
3411 case glslang::EOpImageAtomicExchange:
3412 case glslang::EOpImageAtomicCompSwap:
3413 if (i == 0)
3414 lvalue = true;
3415 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003416 case glslang::EOpSparseImageLoad:
3417 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3418 lvalue = true;
3419 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003420#ifdef AMD_EXTENSIONS
3421 case glslang::EOpSparseTexture:
3422 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3423 lvalue = true;
3424 break;
3425 case glslang::EOpSparseTextureClamp:
3426 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3427 lvalue = true;
3428 break;
3429 case glslang::EOpSparseTextureLod:
3430 case glslang::EOpSparseTextureOffset:
3431 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
3432 lvalue = true;
3433 break;
3434#else
Rex Xu48edadf2015-12-31 16:11:41 +08003435 case glslang::EOpSparseTexture:
3436 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3437 lvalue = true;
3438 break;
3439 case glslang::EOpSparseTextureClamp:
3440 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3441 lvalue = true;
3442 break;
3443 case glslang::EOpSparseTextureLod:
3444 case glslang::EOpSparseTextureOffset:
3445 if (i == 3)
3446 lvalue = true;
3447 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003448#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003449 case glslang::EOpSparseTextureFetch:
3450 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3451 lvalue = true;
3452 break;
3453 case glslang::EOpSparseTextureFetchOffset:
3454 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3455 lvalue = true;
3456 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003457#ifdef AMD_EXTENSIONS
3458 case glslang::EOpSparseTextureLodOffset:
3459 case glslang::EOpSparseTextureGrad:
3460 case glslang::EOpSparseTextureOffsetClamp:
3461 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
3462 lvalue = true;
3463 break;
3464 case glslang::EOpSparseTextureGradOffset:
3465 case glslang::EOpSparseTextureGradClamp:
3466 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
3467 lvalue = true;
3468 break;
3469 case glslang::EOpSparseTextureGradOffsetClamp:
3470 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
3471 lvalue = true;
3472 break;
3473#else
Rex Xu48edadf2015-12-31 16:11:41 +08003474 case glslang::EOpSparseTextureLodOffset:
3475 case glslang::EOpSparseTextureGrad:
3476 case glslang::EOpSparseTextureOffsetClamp:
3477 if (i == 4)
3478 lvalue = true;
3479 break;
3480 case glslang::EOpSparseTextureGradOffset:
3481 case glslang::EOpSparseTextureGradClamp:
3482 if (i == 5)
3483 lvalue = true;
3484 break;
3485 case glslang::EOpSparseTextureGradOffsetClamp:
3486 if (i == 6)
3487 lvalue = true;
3488 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003489#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08003490 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003491 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3492 lvalue = true;
3493 break;
3494 case glslang::EOpSparseTextureGatherOffset:
3495 case glslang::EOpSparseTextureGatherOffsets:
3496 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3497 lvalue = true;
3498 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003499#ifdef AMD_EXTENSIONS
3500 case glslang::EOpSparseTextureGatherLod:
3501 if (i == 3)
3502 lvalue = true;
3503 break;
3504 case glslang::EOpSparseTextureGatherLodOffset:
3505 case glslang::EOpSparseTextureGatherLodOffsets:
3506 if (i == 4)
3507 lvalue = true;
3508 break;
Rex Xu129799a2017-07-05 17:23:28 +08003509 case glslang::EOpSparseImageLoadLod:
3510 if (i == 3)
3511 lvalue = true;
3512 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003513#endif
Rex Xufc618912015-09-09 16:42:49 +08003514 default:
3515 break;
3516 }
3517
Rex Xu6b86d492015-09-16 17:48:22 +08003518 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003519 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003520 else
John Kessenich32cfd492016-02-02 12:37:46 -07003521 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003522 }
3523}
3524
John Kessenichfc51d282015-08-19 13:34:18 -06003525void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003526{
John Kessenichfc51d282015-08-19 13:34:18 -06003527 builder.clearAccessChain();
3528 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003529 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003530}
John Kessenich140f3df2015-06-26 16:58:36 -06003531
John Kessenichfc51d282015-08-19 13:34:18 -06003532spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3533{
John Kesseniche485c7a2017-05-31 18:50:53 -06003534 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003535 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003536
3537 builder.setLine(node->getLoc().line);
3538
John Kessenichfc51d282015-08-19 13:34:18 -06003539 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003540 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3541 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08003542#ifdef AMD_EXTENSIONS
3543 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
3544 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
3545 : false;
3546#endif
3547
John Kessenichfc51d282015-08-19 13:34:18 -06003548 std::vector<spv::Id> arguments;
3549 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003550 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003551 else
3552 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003553 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003554
3555 spv::Builder::TextureParameters params = { };
3556 params.sampler = arguments[0];
3557
Rex Xu04db3f52015-09-16 11:44:02 +08003558 glslang::TCrackedTextureOp cracked;
3559 node->crackTexture(sampler, cracked);
3560
amhagan05506bb2017-06-13 16:53:02 -04003561 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003562
John Kessenichfc51d282015-08-19 13:34:18 -06003563 // Check for queries
3564 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003565 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3566 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003567 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003568
John Kessenichfc51d282015-08-19 13:34:18 -06003569 switch (node->getOp()) {
3570 case glslang::EOpImageQuerySize:
3571 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003572 if (arguments.size() > 1) {
3573 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003574 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003575 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003576 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003577 case glslang::EOpImageQuerySamples:
3578 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003579 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003580 case glslang::EOpTextureQueryLod:
3581 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003582 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003583 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003584 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003585 case glslang::EOpSparseTexelsResident:
3586 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003587 default:
3588 assert(0);
3589 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003590 }
John Kessenich140f3df2015-06-26 16:58:36 -06003591 }
3592
LoopDawg4425f242018-02-18 11:40:01 -07003593 int components = node->getType().getVectorSize();
3594
3595 if (node->getOp() == glslang::EOpTextureFetch) {
3596 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3597 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3598 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3599 // here around e.g. which ones return scalars or other types.
3600 components = 4;
3601 }
3602
3603 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3604
3605 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3606
Rex Xufc618912015-09-09 16:42:49 +08003607 // Check for image functions other than queries
3608 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003609 std::vector<spv::Id> operands;
3610 auto opIt = arguments.begin();
3611 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003612
3613 // Handle subpass operations
3614 // TODO: GLSL should change to have the "MS" only on the type rather than the
3615 // built-in function.
3616 if (cracked.subpass) {
3617 // add on the (0,0) coordinate
3618 spv::Id zero = builder.makeIntConstant(0);
3619 std::vector<spv::Id> comps;
3620 comps.push_back(zero);
3621 comps.push_back(zero);
3622 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3623 if (sampler.ms) {
3624 operands.push_back(spv::ImageOperandsSampleMask);
3625 operands.push_back(*(opIt++));
3626 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003627 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3628 builder.setPrecision(result, precision);
3629 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003630 }
3631
John Kessenich56bab042015-09-16 10:54:31 -06003632 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003633#ifdef AMD_EXTENSIONS
3634 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3635#else
John Kessenich56bab042015-09-16 10:54:31 -06003636 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003637#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003638 if (sampler.ms) {
3639 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003640 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003641#ifdef AMD_EXTENSIONS
3642 } else if (cracked.lod) {
3643 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3644 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3645
3646 operands.push_back(spv::ImageOperandsLodMask);
3647 operands.push_back(*opIt);
3648#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003649 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003650 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3651 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003652
St0fFa1184dd2018-04-09 21:08:14 +02003653 std::vector<spv::Id> result( 1, builder.createOp(spv::OpImageRead, resultType(), operands) );
LoopDawg4425f242018-02-18 11:40:01 -07003654 builder.setPrecision(result[0], precision);
3655
3656 // If needed, add a conversion constructor to the proper size.
3657 if (components != node->getType().getVectorSize())
3658 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3659
3660 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08003661#ifdef AMD_EXTENSIONS
3662 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3663#else
John Kessenich56bab042015-09-16 10:54:31 -06003664 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003665#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003666 if (sampler.ms) {
3667 operands.push_back(*(opIt + 1));
3668 operands.push_back(spv::ImageOperandsSampleMask);
3669 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003670#ifdef AMD_EXTENSIONS
3671 } else if (cracked.lod) {
3672 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3673 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3674
3675 operands.push_back(*(opIt + 1));
3676 operands.push_back(spv::ImageOperandsLodMask);
3677 operands.push_back(*opIt);
3678#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003679 } else
3680 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003681 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003682 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3683 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003684 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003685#ifdef AMD_EXTENSIONS
3686 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3687#else
Rex Xu5eafa472016-02-19 22:24:03 +08003688 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003689#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003690 builder.addCapability(spv::CapabilitySparseResidency);
3691 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3692 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3693
3694 if (sampler.ms) {
3695 operands.push_back(spv::ImageOperandsSampleMask);
3696 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003697#ifdef AMD_EXTENSIONS
3698 } else if (cracked.lod) {
3699 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3700 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3701
3702 operands.push_back(spv::ImageOperandsLodMask);
3703 operands.push_back(*opIt++);
3704#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003705 }
3706
3707 // Create the return type that was a special structure
3708 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003709 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003710 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3711 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3712
3713 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3714
3715 // Decode the return type
3716 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3717 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003718 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003719 // Process image atomic operations
3720
3721 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3722 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003723 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003724
John Kessenich8c8505c2016-07-26 12:50:38 -06003725 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003726 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003727
3728 std::vector<spv::Id> operands;
3729 operands.push_back(pointer);
3730 for (; opIt != arguments.end(); ++opIt)
3731 operands.push_back(*opIt);
3732
John Kessenich8c8505c2016-07-26 12:50:38 -06003733 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003734 }
3735 }
3736
amhagan05506bb2017-06-13 16:53:02 -04003737#ifdef AMD_EXTENSIONS
3738 // Check for fragment mask functions other than queries
3739 if (cracked.fragMask) {
3740 assert(sampler.ms);
3741
3742 auto opIt = arguments.begin();
3743 std::vector<spv::Id> operands;
3744
3745 // Extract the image if necessary
3746 if (builder.isSampledImage(params.sampler))
3747 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3748
3749 operands.push_back(params.sampler);
3750 ++opIt;
3751
3752 if (sampler.isSubpass()) {
3753 // add on the (0,0) coordinate
3754 spv::Id zero = builder.makeIntConstant(0);
3755 std::vector<spv::Id> comps;
3756 comps.push_back(zero);
3757 comps.push_back(zero);
3758 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3759 }
3760
3761 for (; opIt != arguments.end(); ++opIt)
3762 operands.push_back(*opIt);
3763
3764 spv::Op fragMaskOp = spv::OpNop;
3765 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3766 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3767 else if (node->getOp() == glslang::EOpFragmentFetch)
3768 fragMaskOp = spv::OpFragmentFetchAMD;
3769
3770 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3771 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3772 return builder.createOp(fragMaskOp, resultType(), operands);
3773 }
3774#endif
3775
Rex Xufc618912015-09-09 16:42:49 +08003776 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003777 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003778 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3779
John Kessenichfc51d282015-08-19 13:34:18 -06003780 // check for bias argument
3781 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003782#ifdef AMD_EXTENSIONS
3783 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3784#else
Rex Xu71519fe2015-11-11 15:35:47 +08003785 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003786#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003787 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003788#ifdef AMD_EXTENSIONS
3789 if (cracked.gather)
3790 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08003791
3792 if (f16ShadowCompare)
3793 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003794#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003795 if (cracked.offset)
3796 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003797#ifdef AMD_EXTENSIONS
3798 else if (cracked.offsets)
3799 ++nonBiasArgCount;
3800#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003801 if (cracked.grad)
3802 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003803 if (cracked.lodClamp)
3804 ++nonBiasArgCount;
3805 if (sparse)
3806 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003807
3808 if ((int)arguments.size() > nonBiasArgCount)
3809 bias = true;
3810 }
3811
John Kessenicha5c33d62016-06-02 23:45:21 -06003812 // See if the sampler param should really be just the SPV image part
3813 if (cracked.fetch) {
3814 // a fetch needs to have the image extracted first
3815 if (builder.isSampledImage(params.sampler))
3816 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3817 }
3818
Rex Xu225e0fc2016-11-17 17:47:59 +08003819#ifdef AMD_EXTENSIONS
3820 if (cracked.gather) {
3821 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3822 if (bias || cracked.lod ||
3823 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3824 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003825 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003826 }
3827 }
3828#endif
3829
John Kessenichfc51d282015-08-19 13:34:18 -06003830 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003831
John Kessenichfc51d282015-08-19 13:34:18 -06003832 params.coords = arguments[1];
3833 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003834 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003835
3836 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08003837#ifdef AMD_EXTENSIONS
3838 if (cubeCompare || f16ShadowCompare) {
3839#else
Rex Xu48edadf2015-12-31 16:11:41 +08003840 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08003841#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003842 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003843 ++extraArgs;
3844 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003845 params.Dref = arguments[2];
3846 ++extraArgs;
3847 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003848 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003849 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003850 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003851 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003852 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003853 dRefComp = builder.getNumComponents(params.coords) - 1;
3854 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003855 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3856 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003857
3858 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003859 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003860 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003861 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003862 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3863 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3864 noImplicitLod = true;
3865 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003866
3867 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003868 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003869 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003870 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003871 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003872
3873 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003874 if (cracked.grad) {
3875 params.gradX = arguments[2 + extraArgs];
3876 params.gradY = arguments[3 + extraArgs];
3877 extraArgs += 2;
3878 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003879
3880 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003881 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003882 params.offset = arguments[2 + extraArgs];
3883 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003884 } else if (cracked.offsets) {
3885 params.offsets = arguments[2 + extraArgs];
3886 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003887 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003888
3889 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003890 if (cracked.lodClamp) {
3891 params.lodClamp = arguments[2 + extraArgs];
3892 ++extraArgs;
3893 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003894
3895 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003896 if (sparse) {
3897 params.texelOut = arguments[2 + extraArgs];
3898 ++extraArgs;
3899 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003900
John Kessenich76d4dfc2016-06-16 12:43:23 -06003901 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003902 if (cracked.gather && ! sampler.shadow) {
3903 // default component is 0, if missing, otherwise an argument
3904 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003905 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003906 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003907 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003908 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003909 }
3910
3911 // bias
3912 if (bias) {
3913 params.bias = arguments[2 + extraArgs];
3914 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003915 }
John Kessenichfc51d282015-08-19 13:34:18 -06003916
John Kessenich65336482016-06-16 14:06:26 -06003917 // projective component (might not to move)
3918 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3919 // are divided by the last component of P."
3920 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3921 // unused components will appear after all used components."
3922 if (cracked.proj) {
3923 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3924 int projTargetComp;
3925 switch (sampler.dim) {
3926 case glslang::Esd1D: projTargetComp = 1; break;
3927 case glslang::Esd2D: projTargetComp = 2; break;
3928 case glslang::EsdRect: projTargetComp = 2; break;
3929 default: projTargetComp = projSourceComp; break;
3930 }
3931 // copy the projective coordinate if we have to
3932 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003933 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003934 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3935 projSourceComp);
3936 params.coords = builder.createCompositeInsert(projComp, params.coords,
3937 builder.getTypeId(params.coords), projTargetComp);
3938 }
3939 }
3940
St0fFa1184dd2018-04-09 21:08:14 +02003941 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07003942 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02003943 );
LoopDawg4425f242018-02-18 11:40:01 -07003944
3945 if (components != node->getType().getVectorSize())
3946 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3947
3948 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06003949}
3950
3951spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3952{
3953 // Grab the function's pointer from the previously created function
3954 spv::Function* function = functionMap[node->getName().c_str()];
3955 if (! function)
3956 return 0;
3957
3958 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3959 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3960
3961 // See comments in makeFunctions() for details about the semantics for parameter passing.
3962 //
3963 // These imply we need a four step process:
3964 // 1. Evaluate the arguments
3965 // 2. Allocate and make copies of in, out, and inout arguments
3966 // 3. Make the call
3967 // 4. Copy back the results
3968
John Kessenichd3ed90b2018-05-04 11:43:03 -06003969 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06003970 std::vector<spv::Builder::AccessChain> lValues;
3971 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003972 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003973 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06003974 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003975 // build l-value
3976 builder.clearAccessChain();
3977 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06003978 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06003979 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07003980 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003981 // save l-value
3982 lValues.push_back(builder.getAccessChain());
3983 } else {
3984 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003985 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003986 }
3987 }
3988
3989 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3990 // copy the original into that space.
3991 //
3992 // Also, build up the list of actual arguments to pass in for the call
3993 int lValueCount = 0;
3994 int rValueCount = 0;
3995 std::vector<spv::Id> spvArgs;
3996 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
3997 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06003998 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003999 builder.setAccessChain(lValues[lValueCount]);
4000 arg = builder.accessChainGetLValue();
4001 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004002 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004003 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004004 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004005 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4006 // need to copy the input into output space
4007 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004008 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004009 builder.clearAccessChain();
4010 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004011 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004012 }
4013 ++lValueCount;
4014 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004015 // process r-value, which involves a copy for a type mismatch
4016 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4017 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4018 builder.clearAccessChain();
4019 builder.setAccessChainLValue(argCopy);
4020 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4021 arg = builder.createLoad(argCopy);
4022 } else
4023 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004024 ++rValueCount;
4025 }
4026 spvArgs.push_back(arg);
4027 }
4028
4029 // 3. Make the call.
4030 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004031 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004032
4033 // 4. Copy back out an "out" arguments.
4034 lValueCount = 0;
4035 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004036 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004037 ++lValueCount;
4038 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004039 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4040 spv::Id copy = builder.createLoad(spvArgs[a]);
4041 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004042 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004043 }
4044 ++lValueCount;
4045 }
4046 }
4047
4048 return result;
4049}
4050
4051// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004052spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004053 spv::Id typeId, spv::Id left, spv::Id right,
4054 glslang::TBasicType typeProxy, bool reduceComparison)
4055{
John Kessenich66011cb2018-03-06 16:12:04 -07004056 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4057 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004058 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004059
4060 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004061 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004062 bool comparison = false;
4063
4064 switch (op) {
4065 case glslang::EOpAdd:
4066 case glslang::EOpAddAssign:
4067 if (isFloat)
4068 binOp = spv::OpFAdd;
4069 else
4070 binOp = spv::OpIAdd;
4071 break;
4072 case glslang::EOpSub:
4073 case glslang::EOpSubAssign:
4074 if (isFloat)
4075 binOp = spv::OpFSub;
4076 else
4077 binOp = spv::OpISub;
4078 break;
4079 case glslang::EOpMul:
4080 case glslang::EOpMulAssign:
4081 if (isFloat)
4082 binOp = spv::OpFMul;
4083 else
4084 binOp = spv::OpIMul;
4085 break;
4086 case glslang::EOpVectorTimesScalar:
4087 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004088 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004089 if (builder.isVector(right))
4090 std::swap(left, right);
4091 assert(builder.isScalar(right));
4092 needMatchingVectors = false;
4093 binOp = spv::OpVectorTimesScalar;
4094 } else
4095 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004096 break;
4097 case glslang::EOpVectorTimesMatrix:
4098 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004099 binOp = spv::OpVectorTimesMatrix;
4100 break;
4101 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004102 binOp = spv::OpMatrixTimesVector;
4103 break;
4104 case glslang::EOpMatrixTimesScalar:
4105 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004106 binOp = spv::OpMatrixTimesScalar;
4107 break;
4108 case glslang::EOpMatrixTimesMatrix:
4109 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004110 binOp = spv::OpMatrixTimesMatrix;
4111 break;
4112 case glslang::EOpOuterProduct:
4113 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004114 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004115 break;
4116
4117 case glslang::EOpDiv:
4118 case glslang::EOpDivAssign:
4119 if (isFloat)
4120 binOp = spv::OpFDiv;
4121 else if (isUnsigned)
4122 binOp = spv::OpUDiv;
4123 else
4124 binOp = spv::OpSDiv;
4125 break;
4126 case glslang::EOpMod:
4127 case glslang::EOpModAssign:
4128 if (isFloat)
4129 binOp = spv::OpFMod;
4130 else if (isUnsigned)
4131 binOp = spv::OpUMod;
4132 else
4133 binOp = spv::OpSMod;
4134 break;
4135 case glslang::EOpRightShift:
4136 case glslang::EOpRightShiftAssign:
4137 if (isUnsigned)
4138 binOp = spv::OpShiftRightLogical;
4139 else
4140 binOp = spv::OpShiftRightArithmetic;
4141 break;
4142 case glslang::EOpLeftShift:
4143 case glslang::EOpLeftShiftAssign:
4144 binOp = spv::OpShiftLeftLogical;
4145 break;
4146 case glslang::EOpAnd:
4147 case glslang::EOpAndAssign:
4148 binOp = spv::OpBitwiseAnd;
4149 break;
4150 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004151 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004152 binOp = spv::OpLogicalAnd;
4153 break;
4154 case glslang::EOpInclusiveOr:
4155 case glslang::EOpInclusiveOrAssign:
4156 binOp = spv::OpBitwiseOr;
4157 break;
4158 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004159 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004160 binOp = spv::OpLogicalOr;
4161 break;
4162 case glslang::EOpExclusiveOr:
4163 case glslang::EOpExclusiveOrAssign:
4164 binOp = spv::OpBitwiseXor;
4165 break;
4166 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004167 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004168 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004169 break;
4170
4171 case glslang::EOpLessThan:
4172 case glslang::EOpGreaterThan:
4173 case glslang::EOpLessThanEqual:
4174 case glslang::EOpGreaterThanEqual:
4175 case glslang::EOpEqual:
4176 case glslang::EOpNotEqual:
4177 case glslang::EOpVectorEqual:
4178 case glslang::EOpVectorNotEqual:
4179 comparison = true;
4180 break;
4181 default:
4182 break;
4183 }
4184
John Kessenich7c1aa102015-10-15 13:29:11 -06004185 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004186 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004187 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07004188 if (builder.isMatrix(left) || builder.isMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004189 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004190
4191 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004192 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004193 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004194
qining25262b32016-05-06 17:25:16 -04004195 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004196 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004197 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004198 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004199 }
4200
4201 if (! comparison)
4202 return 0;
4203
John Kessenich7c1aa102015-10-15 13:29:11 -06004204 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004205
John Kessenich4583b612016-08-07 19:14:22 -06004206 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004207 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4208 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004209 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004210 return result;
4211 }
John Kessenich140f3df2015-06-26 16:58:36 -06004212
4213 switch (op) {
4214 case glslang::EOpLessThan:
4215 if (isFloat)
4216 binOp = spv::OpFOrdLessThan;
4217 else if (isUnsigned)
4218 binOp = spv::OpULessThan;
4219 else
4220 binOp = spv::OpSLessThan;
4221 break;
4222 case glslang::EOpGreaterThan:
4223 if (isFloat)
4224 binOp = spv::OpFOrdGreaterThan;
4225 else if (isUnsigned)
4226 binOp = spv::OpUGreaterThan;
4227 else
4228 binOp = spv::OpSGreaterThan;
4229 break;
4230 case glslang::EOpLessThanEqual:
4231 if (isFloat)
4232 binOp = spv::OpFOrdLessThanEqual;
4233 else if (isUnsigned)
4234 binOp = spv::OpULessThanEqual;
4235 else
4236 binOp = spv::OpSLessThanEqual;
4237 break;
4238 case glslang::EOpGreaterThanEqual:
4239 if (isFloat)
4240 binOp = spv::OpFOrdGreaterThanEqual;
4241 else if (isUnsigned)
4242 binOp = spv::OpUGreaterThanEqual;
4243 else
4244 binOp = spv::OpSGreaterThanEqual;
4245 break;
4246 case glslang::EOpEqual:
4247 case glslang::EOpVectorEqual:
4248 if (isFloat)
4249 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004250 else if (isBool)
4251 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004252 else
4253 binOp = spv::OpIEqual;
4254 break;
4255 case glslang::EOpNotEqual:
4256 case glslang::EOpVectorNotEqual:
4257 if (isFloat)
4258 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004259 else if (isBool)
4260 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004261 else
4262 binOp = spv::OpINotEqual;
4263 break;
4264 default:
4265 break;
4266 }
4267
qining25262b32016-05-06 17:25:16 -04004268 if (binOp != spv::OpNop) {
4269 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004270 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004271 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004272 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004273 }
John Kessenich140f3df2015-06-26 16:58:36 -06004274
4275 return 0;
4276}
4277
John Kessenich04bb8a02015-12-12 12:28:14 -07004278//
4279// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
4280// These can be any of:
4281//
4282// matrix * scalar
4283// scalar * matrix
4284// matrix * matrix linear algebraic
4285// matrix * vector
4286// vector * matrix
4287// matrix * matrix componentwise
4288// matrix op matrix op in {+, -, /}
4289// matrix op scalar op in {+, -, /}
4290// scalar op matrix op in {+, -, /}
4291//
John Kessenichead86222018-03-28 18:01:20 -06004292spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4293 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07004294{
4295 bool firstClass = true;
4296
4297 // First, handle first-class matrix operations (* and matrix/scalar)
4298 switch (op) {
4299 case spv::OpFDiv:
4300 if (builder.isMatrix(left) && builder.isScalar(right)) {
4301 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01004302 spv::Id resultType = builder.getTypeId(right);
4303 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07004304 op = spv::OpMatrixTimesScalar;
4305 } else
4306 firstClass = false;
4307 break;
4308 case spv::OpMatrixTimesScalar:
4309 if (builder.isMatrix(right))
4310 std::swap(left, right);
4311 assert(builder.isScalar(right));
4312 break;
4313 case spv::OpVectorTimesMatrix:
4314 assert(builder.isVector(left));
4315 assert(builder.isMatrix(right));
4316 break;
4317 case spv::OpMatrixTimesVector:
4318 assert(builder.isMatrix(left));
4319 assert(builder.isVector(right));
4320 break;
4321 case spv::OpMatrixTimesMatrix:
4322 assert(builder.isMatrix(left));
4323 assert(builder.isMatrix(right));
4324 break;
4325 default:
4326 firstClass = false;
4327 break;
4328 }
4329
qining25262b32016-05-06 17:25:16 -04004330 if (firstClass) {
4331 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004332 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004333 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004334 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004335 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004336
LoopDawg592860c2016-06-09 08:57:35 -06004337 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004338 // The result type of all of them is the same type as the (a) matrix operand.
4339 // The algorithm is to:
4340 // - break the matrix(es) into vectors
4341 // - smear any scalar to a vector
4342 // - do vector operations
4343 // - make a matrix out the vector results
4344 switch (op) {
4345 case spv::OpFAdd:
4346 case spv::OpFSub:
4347 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004348 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004349 case spv::OpFMul:
4350 {
4351 // one time set up...
4352 bool leftMat = builder.isMatrix(left);
4353 bool rightMat = builder.isMatrix(right);
4354 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4355 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4356 spv::Id scalarType = builder.getScalarTypeId(typeId);
4357 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4358 std::vector<spv::Id> results;
4359 spv::Id smearVec = spv::NoResult;
4360 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06004361 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004362 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06004363 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004364
4365 // do each vector op
4366 for (unsigned int c = 0; c < numCols; ++c) {
4367 std::vector<unsigned int> indexes;
4368 indexes.push_back(c);
4369 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4370 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004371 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06004372 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004373 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004374 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004375 }
4376
4377 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004378 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004379 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004380 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07004381 }
4382 default:
4383 assert(0);
4384 return spv::NoResult;
4385 }
4386}
4387
John Kessenichead86222018-03-28 18:01:20 -06004388spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
4389 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004390{
4391 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004392 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004393 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07004394 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4395 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004396
4397 switch (op) {
4398 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004399 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004400 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004401 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06004402 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004403 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004404 unaryOp = spv::OpSNegate;
4405 break;
4406
4407 case glslang::EOpLogicalNot:
4408 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004409 unaryOp = spv::OpLogicalNot;
4410 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004411 case glslang::EOpBitwiseNot:
4412 unaryOp = spv::OpNot;
4413 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004414
John Kessenich140f3df2015-06-26 16:58:36 -06004415 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004416 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004417 break;
4418 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004419 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004420 break;
4421 case glslang::EOpTranspose:
4422 unaryOp = spv::OpTranspose;
4423 break;
4424
4425 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004426 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004427 break;
4428 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004429 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004430 break;
4431 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004432 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004433 break;
4434 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004435 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004436 break;
4437 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004438 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004439 break;
4440 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004441 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004442 break;
4443 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004444 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004445 break;
4446 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004447 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004448 break;
4449
4450 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004451 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004452 break;
4453 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004454 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004455 break;
4456 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004457 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004458 break;
4459 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004460 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004461 break;
4462 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004463 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004464 break;
4465 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004466 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004467 break;
4468
4469 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004470 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004471 break;
4472 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004473 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004474 break;
4475
4476 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004477 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004478 break;
4479 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004480 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004481 break;
4482 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004483 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004484 break;
4485 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004486 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004487 break;
4488 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004489 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004490 break;
4491 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004492 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004493 break;
4494
4495 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004496 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004497 break;
4498 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004499 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004500 break;
4501 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004502 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004503 break;
4504 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004505 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004506 break;
4507 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004508 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004509 break;
4510 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004511 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004512 break;
4513
4514 case glslang::EOpIsNan:
4515 unaryOp = spv::OpIsNan;
4516 break;
4517 case glslang::EOpIsInf:
4518 unaryOp = spv::OpIsInf;
4519 break;
LoopDawg592860c2016-06-09 08:57:35 -06004520 case glslang::EOpIsFinite:
4521 unaryOp = spv::OpIsFinite;
4522 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004523
Rex Xucbc426e2015-12-15 16:03:10 +08004524 case glslang::EOpFloatBitsToInt:
4525 case glslang::EOpFloatBitsToUint:
4526 case glslang::EOpIntBitsToFloat:
4527 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004528 case glslang::EOpDoubleBitsToInt64:
4529 case glslang::EOpDoubleBitsToUint64:
4530 case glslang::EOpInt64BitsToDouble:
4531 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004532 case glslang::EOpFloat16BitsToInt16:
4533 case glslang::EOpFloat16BitsToUint16:
4534 case glslang::EOpInt16BitsToFloat16:
4535 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08004536 unaryOp = spv::OpBitcast;
4537 break;
4538
John Kessenich140f3df2015-06-26 16:58:36 -06004539 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004540 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004541 break;
4542 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004543 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004544 break;
4545 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004546 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004547 break;
4548 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004549 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004550 break;
4551 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004552 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004553 break;
4554 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004555 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004556 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004557 case glslang::EOpPackSnorm4x8:
4558 libCall = spv::GLSLstd450PackSnorm4x8;
4559 break;
4560 case glslang::EOpUnpackSnorm4x8:
4561 libCall = spv::GLSLstd450UnpackSnorm4x8;
4562 break;
4563 case glslang::EOpPackUnorm4x8:
4564 libCall = spv::GLSLstd450PackUnorm4x8;
4565 break;
4566 case glslang::EOpUnpackUnorm4x8:
4567 libCall = spv::GLSLstd450UnpackUnorm4x8;
4568 break;
4569 case glslang::EOpPackDouble2x32:
4570 libCall = spv::GLSLstd450PackDouble2x32;
4571 break;
4572 case glslang::EOpUnpackDouble2x32:
4573 libCall = spv::GLSLstd450UnpackDouble2x32;
4574 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004575
Rex Xu8ff43de2016-04-22 16:51:45 +08004576 case glslang::EOpPackInt2x32:
4577 case glslang::EOpUnpackInt2x32:
4578 case glslang::EOpPackUint2x32:
4579 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07004580 case glslang::EOpPack16:
4581 case glslang::EOpPack32:
4582 case glslang::EOpPack64:
4583 case glslang::EOpUnpack32:
4584 case glslang::EOpUnpack16:
4585 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08004586 case glslang::EOpPackInt2x16:
4587 case glslang::EOpUnpackInt2x16:
4588 case glslang::EOpPackUint2x16:
4589 case glslang::EOpUnpackUint2x16:
4590 case glslang::EOpPackInt4x16:
4591 case glslang::EOpUnpackInt4x16:
4592 case glslang::EOpPackUint4x16:
4593 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004594 case glslang::EOpPackFloat2x16:
4595 case glslang::EOpUnpackFloat2x16:
4596 unaryOp = spv::OpBitcast;
4597 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004598
John Kessenich140f3df2015-06-26 16:58:36 -06004599 case glslang::EOpDPdx:
4600 unaryOp = spv::OpDPdx;
4601 break;
4602 case glslang::EOpDPdy:
4603 unaryOp = spv::OpDPdy;
4604 break;
4605 case glslang::EOpFwidth:
4606 unaryOp = spv::OpFwidth;
4607 break;
4608 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004609 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004610 unaryOp = spv::OpDPdxFine;
4611 break;
4612 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004613 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004614 unaryOp = spv::OpDPdyFine;
4615 break;
4616 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004617 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004618 unaryOp = spv::OpFwidthFine;
4619 break;
4620 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004621 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004622 unaryOp = spv::OpDPdxCoarse;
4623 break;
4624 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004625 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004626 unaryOp = spv::OpDPdyCoarse;
4627 break;
4628 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004629 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004630 unaryOp = spv::OpFwidthCoarse;
4631 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004632 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08004633#ifdef AMD_EXTENSIONS
4634 if (typeProxy == glslang::EbtFloat16)
4635 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
4636#endif
John Kessenich92187592016-02-01 13:45:25 -07004637 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004638 libCall = spv::GLSLstd450InterpolateAtCentroid;
4639 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004640 case glslang::EOpAny:
4641 unaryOp = spv::OpAny;
4642 break;
4643 case glslang::EOpAll:
4644 unaryOp = spv::OpAll;
4645 break;
4646
4647 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004648 if (isFloat)
4649 libCall = spv::GLSLstd450FAbs;
4650 else
4651 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004652 break;
4653 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004654 if (isFloat)
4655 libCall = spv::GLSLstd450FSign;
4656 else
4657 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004658 break;
4659
John Kessenichfc51d282015-08-19 13:34:18 -06004660 case glslang::EOpAtomicCounterIncrement:
4661 case glslang::EOpAtomicCounterDecrement:
4662 case glslang::EOpAtomicCounter:
4663 {
4664 // Handle all of the atomics in one place, in createAtomicOperation()
4665 std::vector<spv::Id> operands;
4666 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06004667 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004668 }
4669
John Kessenichfc51d282015-08-19 13:34:18 -06004670 case glslang::EOpBitFieldReverse:
4671 unaryOp = spv::OpBitReverse;
4672 break;
4673 case glslang::EOpBitCount:
4674 unaryOp = spv::OpBitCount;
4675 break;
4676 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004677 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004678 break;
4679 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004680 if (isUnsigned)
4681 libCall = spv::GLSLstd450FindUMsb;
4682 else
4683 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004684 break;
4685
Rex Xu574ab042016-04-14 16:53:07 +08004686 case glslang::EOpBallot:
4687 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004688 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004689 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004690 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004691#ifdef AMD_EXTENSIONS
4692 case glslang::EOpMinInvocations:
4693 case glslang::EOpMaxInvocations:
4694 case glslang::EOpAddInvocations:
4695 case glslang::EOpMinInvocationsNonUniform:
4696 case glslang::EOpMaxInvocationsNonUniform:
4697 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004698 case glslang::EOpMinInvocationsInclusiveScan:
4699 case glslang::EOpMaxInvocationsInclusiveScan:
4700 case glslang::EOpAddInvocationsInclusiveScan:
4701 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4702 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4703 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4704 case glslang::EOpMinInvocationsExclusiveScan:
4705 case glslang::EOpMaxInvocationsExclusiveScan:
4706 case glslang::EOpAddInvocationsExclusiveScan:
4707 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4708 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4709 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004710#endif
Rex Xu51596642016-09-21 18:56:12 +08004711 {
4712 std::vector<spv::Id> operands;
4713 operands.push_back(operand);
4714 return createInvocationsOperation(op, typeId, operands, typeProxy);
4715 }
John Kessenich66011cb2018-03-06 16:12:04 -07004716 case glslang::EOpSubgroupAll:
4717 case glslang::EOpSubgroupAny:
4718 case glslang::EOpSubgroupAllEqual:
4719 case glslang::EOpSubgroupBroadcastFirst:
4720 case glslang::EOpSubgroupBallot:
4721 case glslang::EOpSubgroupInverseBallot:
4722 case glslang::EOpSubgroupBallotBitCount:
4723 case glslang::EOpSubgroupBallotInclusiveBitCount:
4724 case glslang::EOpSubgroupBallotExclusiveBitCount:
4725 case glslang::EOpSubgroupBallotFindLSB:
4726 case glslang::EOpSubgroupBallotFindMSB:
4727 case glslang::EOpSubgroupAdd:
4728 case glslang::EOpSubgroupMul:
4729 case glslang::EOpSubgroupMin:
4730 case glslang::EOpSubgroupMax:
4731 case glslang::EOpSubgroupAnd:
4732 case glslang::EOpSubgroupOr:
4733 case glslang::EOpSubgroupXor:
4734 case glslang::EOpSubgroupInclusiveAdd:
4735 case glslang::EOpSubgroupInclusiveMul:
4736 case glslang::EOpSubgroupInclusiveMin:
4737 case glslang::EOpSubgroupInclusiveMax:
4738 case glslang::EOpSubgroupInclusiveAnd:
4739 case glslang::EOpSubgroupInclusiveOr:
4740 case glslang::EOpSubgroupInclusiveXor:
4741 case glslang::EOpSubgroupExclusiveAdd:
4742 case glslang::EOpSubgroupExclusiveMul:
4743 case glslang::EOpSubgroupExclusiveMin:
4744 case glslang::EOpSubgroupExclusiveMax:
4745 case glslang::EOpSubgroupExclusiveAnd:
4746 case glslang::EOpSubgroupExclusiveOr:
4747 case glslang::EOpSubgroupExclusiveXor:
4748 case glslang::EOpSubgroupQuadSwapHorizontal:
4749 case glslang::EOpSubgroupQuadSwapVertical:
4750 case glslang::EOpSubgroupQuadSwapDiagonal: {
4751 std::vector<spv::Id> operands;
4752 operands.push_back(operand);
4753 return createSubgroupOperation(op, typeId, operands, typeProxy);
4754 }
Rex Xu9d93a232016-05-05 12:30:44 +08004755#ifdef AMD_EXTENSIONS
4756 case glslang::EOpMbcnt:
4757 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4758 libCall = spv::MbcntAMD;
4759 break;
4760
4761 case glslang::EOpCubeFaceIndex:
4762 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4763 libCall = spv::CubeFaceIndexAMD;
4764 break;
4765
4766 case glslang::EOpCubeFaceCoord:
4767 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4768 libCall = spv::CubeFaceCoordAMD;
4769 break;
4770#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05004771#ifdef NV_EXTENSIONS
4772 case glslang::EOpSubgroupPartition:
4773 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
4774 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
4775 unaryOp = spv::OpGroupNonUniformPartitionNV;
4776 break;
4777#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004778 default:
4779 return 0;
4780 }
4781
4782 spv::Id id;
4783 if (libCall >= 0) {
4784 std::vector<spv::Id> args;
4785 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004786 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004787 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004788 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004789 }
John Kessenich140f3df2015-06-26 16:58:36 -06004790
John Kessenichead86222018-03-28 18:01:20 -06004791 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004792 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004793 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004794}
4795
John Kessenich7a53f762016-01-20 11:19:27 -07004796// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06004797spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4798 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07004799{
4800 // Handle unary operations vector by vector.
4801 // The result type is the same type as the original type.
4802 // The algorithm is to:
4803 // - break the matrix into vectors
4804 // - apply the operation to each vector
4805 // - make a matrix out the vector results
4806
4807 // get the types sorted out
4808 int numCols = builder.getNumColumns(operand);
4809 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004810 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4811 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004812 std::vector<spv::Id> results;
4813
4814 // do each vector op
4815 for (int c = 0; c < numCols; ++c) {
4816 std::vector<unsigned int> indexes;
4817 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004818 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4819 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06004820 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004821 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004822 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004823 }
4824
4825 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004826 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004827 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004828 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07004829}
4830
John Kessenich66011cb2018-03-06 16:12:04 -07004831spv::Id TGlslangToSpvTraverser::createConversionOperation(glslang::TOperator op, spv::Id operand, int vectorSize)
4832{
4833 spv::Op convOp = spv::OpNop;
4834 spv::Id type = 0;
4835
4836 spv::Id result = 0;
4837
4838 switch(op) {
4839 case glslang::EOpConvInt8ToUint16:
4840 convOp = spv::OpSConvert;
4841 type = builder.makeIntType(16);
4842 break;
4843 case glslang::EOpConvInt8ToUint:
4844 convOp = spv::OpSConvert;
4845 type = builder.makeIntType(32);
4846 break;
4847 case glslang::EOpConvInt8ToUint64:
4848 convOp = spv::OpSConvert;
4849 type = builder.makeIntType(64);
4850 break;
4851 case glslang::EOpConvInt16ToUint8:
4852 convOp = spv::OpSConvert;
4853 type = builder.makeIntType(8);
4854 break;
4855 case glslang::EOpConvInt16ToUint:
4856 convOp = spv::OpSConvert;
4857 type = builder.makeIntType(32);
4858 break;
4859 case glslang::EOpConvInt16ToUint64:
4860 convOp = spv::OpSConvert;
4861 type = builder.makeIntType(64);
4862 break;
4863 case glslang::EOpConvIntToUint8:
4864 convOp = spv::OpSConvert;
4865 type = builder.makeIntType(8);
4866 break;
4867 case glslang::EOpConvIntToUint16:
4868 convOp = spv::OpSConvert;
4869 type = builder.makeIntType(16);
4870 break;
4871 case glslang::EOpConvIntToUint64:
4872 convOp = spv::OpSConvert;
4873 type = builder.makeIntType(64);
4874 break;
4875 case glslang::EOpConvInt64ToUint8:
4876 convOp = spv::OpSConvert;
4877 type = builder.makeIntType(8);
4878 break;
4879 case glslang::EOpConvInt64ToUint16:
4880 convOp = spv::OpSConvert;
4881 type = builder.makeIntType(16);
4882 break;
4883 case glslang::EOpConvInt64ToUint:
4884 convOp = spv::OpSConvert;
4885 type = builder.makeIntType(32);
4886 break;
4887 case glslang::EOpConvUint8ToInt16:
4888 convOp = spv::OpUConvert;
4889 type = builder.makeIntType(16);
4890 break;
4891 case glslang::EOpConvUint8ToInt:
4892 convOp = spv::OpUConvert;
4893 type = builder.makeIntType(32);
4894 break;
4895 case glslang::EOpConvUint8ToInt64:
4896 convOp = spv::OpUConvert;
4897 type = builder.makeIntType(64);
4898 break;
4899 case glslang::EOpConvUint16ToInt8:
4900 convOp = spv::OpUConvert;
4901 type = builder.makeIntType(8);
4902 break;
4903 case glslang::EOpConvUint16ToInt:
4904 convOp = spv::OpUConvert;
4905 type = builder.makeIntType(32);
4906 break;
4907 case glslang::EOpConvUint16ToInt64:
4908 convOp = spv::OpUConvert;
4909 type = builder.makeIntType(64);
4910 break;
4911 case glslang::EOpConvUintToInt8:
4912 convOp = spv::OpUConvert;
4913 type = builder.makeIntType(8);
4914 break;
4915 case glslang::EOpConvUintToInt16:
4916 convOp = spv::OpUConvert;
4917 type = builder.makeIntType(16);
4918 break;
4919 case glslang::EOpConvUintToInt64:
4920 convOp = spv::OpUConvert;
4921 type = builder.makeIntType(64);
4922 break;
4923 case glslang::EOpConvUint64ToInt8:
4924 convOp = spv::OpUConvert;
4925 type = builder.makeIntType(8);
4926 break;
4927 case glslang::EOpConvUint64ToInt16:
4928 convOp = spv::OpUConvert;
4929 type = builder.makeIntType(16);
4930 break;
4931 case glslang::EOpConvUint64ToInt:
4932 convOp = spv::OpUConvert;
4933 type = builder.makeIntType(32);
4934 break;
4935
4936 default:
4937 assert(false && "Default missing");
4938 break;
4939 }
4940
4941 if (vectorSize > 0)
4942 type = builder.makeVectorType(type, vectorSize);
4943
4944 result = builder.createUnaryOp(convOp, type, operand);
4945 return result;
4946}
4947
John Kessenichead86222018-03-28 18:01:20 -06004948spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
4949 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004950{
4951 spv::Op convOp = spv::OpNop;
4952 spv::Id zero = 0;
4953 spv::Id one = 0;
4954
4955 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4956
4957 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07004958 case glslang::EOpConvInt8ToBool:
4959 case glslang::EOpConvUint8ToBool:
4960 zero = builder.makeUint8Constant(0);
4961 zero = makeSmearedConstant(zero, vectorSize);
4962 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08004963 case glslang::EOpConvInt16ToBool:
4964 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07004965 zero = builder.makeUint16Constant(0);
4966 zero = makeSmearedConstant(zero, vectorSize);
4967 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4968 case glslang::EOpConvIntToBool:
4969 case glslang::EOpConvUintToBool:
4970 zero = builder.makeUintConstant(0);
4971 zero = makeSmearedConstant(zero, vectorSize);
4972 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4973 case glslang::EOpConvInt64ToBool:
4974 case glslang::EOpConvUint64ToBool:
4975 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004976 zero = makeSmearedConstant(zero, vectorSize);
4977 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4978
4979 case glslang::EOpConvFloatToBool:
4980 zero = builder.makeFloatConstant(0.0F);
4981 zero = makeSmearedConstant(zero, vectorSize);
4982 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4983
4984 case glslang::EOpConvDoubleToBool:
4985 zero = builder.makeDoubleConstant(0.0);
4986 zero = makeSmearedConstant(zero, vectorSize);
4987 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4988
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004989 case glslang::EOpConvFloat16ToBool:
4990 zero = builder.makeFloat16Constant(0.0F);
4991 zero = makeSmearedConstant(zero, vectorSize);
4992 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004993
John Kessenich140f3df2015-06-26 16:58:36 -06004994 case glslang::EOpConvBoolToFloat:
4995 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004996 zero = builder.makeFloatConstant(0.0F);
4997 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004998 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004999
John Kessenich140f3df2015-06-26 16:58:36 -06005000 case glslang::EOpConvBoolToDouble:
5001 convOp = spv::OpSelect;
5002 zero = builder.makeDoubleConstant(0.0);
5003 one = builder.makeDoubleConstant(1.0);
5004 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005005
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005006 case glslang::EOpConvBoolToFloat16:
5007 convOp = spv::OpSelect;
5008 zero = builder.makeFloat16Constant(0.0F);
5009 one = builder.makeFloat16Constant(1.0F);
5010 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005011
5012 case glslang::EOpConvBoolToInt8:
5013 zero = builder.makeInt8Constant(0);
5014 one = builder.makeInt8Constant(1);
5015 convOp = spv::OpSelect;
5016 break;
5017
5018 case glslang::EOpConvBoolToUint8:
5019 zero = builder.makeUint8Constant(0);
5020 one = builder.makeUint8Constant(1);
5021 convOp = spv::OpSelect;
5022 break;
5023
5024 case glslang::EOpConvBoolToInt16:
5025 zero = builder.makeInt16Constant(0);
5026 one = builder.makeInt16Constant(1);
5027 convOp = spv::OpSelect;
5028 break;
5029
5030 case glslang::EOpConvBoolToUint16:
5031 zero = builder.makeUint16Constant(0);
5032 one = builder.makeUint16Constant(1);
5033 convOp = spv::OpSelect;
5034 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005035
John Kessenich140f3df2015-06-26 16:58:36 -06005036 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005037 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005038 if (op == glslang::EOpConvBoolToInt64)
5039 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005040 else
5041 zero = builder.makeIntConstant(0);
5042
5043 if (op == glslang::EOpConvBoolToInt64)
5044 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005045 else
5046 one = builder.makeIntConstant(1);
5047
John Kessenich140f3df2015-06-26 16:58:36 -06005048 convOp = spv::OpSelect;
5049 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005050
John Kessenich140f3df2015-06-26 16:58:36 -06005051 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005052 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005053 if (op == glslang::EOpConvBoolToUint64)
5054 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005055 else
5056 zero = builder.makeUintConstant(0);
5057
5058 if (op == glslang::EOpConvBoolToUint64)
5059 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005060 else
5061 one = builder.makeUintConstant(1);
5062
John Kessenich140f3df2015-06-26 16:58:36 -06005063 convOp = spv::OpSelect;
5064 break;
5065
John Kessenich66011cb2018-03-06 16:12:04 -07005066 case glslang::EOpConvInt8ToFloat16:
5067 case glslang::EOpConvInt8ToFloat:
5068 case glslang::EOpConvInt8ToDouble:
5069 case glslang::EOpConvInt16ToFloat16:
5070 case glslang::EOpConvInt16ToFloat:
5071 case glslang::EOpConvInt16ToDouble:
5072 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005073 case glslang::EOpConvIntToFloat:
5074 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005075 case glslang::EOpConvInt64ToFloat:
5076 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005077 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005078 convOp = spv::OpConvertSToF;
5079 break;
5080
John Kessenich66011cb2018-03-06 16:12:04 -07005081 case glslang::EOpConvUint8ToFloat16:
5082 case glslang::EOpConvUint8ToFloat:
5083 case glslang::EOpConvUint8ToDouble:
5084 case glslang::EOpConvUint16ToFloat16:
5085 case glslang::EOpConvUint16ToFloat:
5086 case glslang::EOpConvUint16ToDouble:
5087 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005088 case glslang::EOpConvUintToFloat:
5089 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005090 case glslang::EOpConvUint64ToFloat:
5091 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005092 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005093 convOp = spv::OpConvertUToF;
5094 break;
5095
5096 case glslang::EOpConvDoubleToFloat:
5097 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005098 case glslang::EOpConvDoubleToFloat16:
5099 case glslang::EOpConvFloat16ToDouble:
5100 case glslang::EOpConvFloatToFloat16:
5101 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005102 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005103 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005104 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005105 break;
5106
John Kessenich66011cb2018-03-06 16:12:04 -07005107 case glslang::EOpConvFloat16ToInt8:
5108 case glslang::EOpConvFloatToInt8:
5109 case glslang::EOpConvDoubleToInt8:
5110 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005111 case glslang::EOpConvFloatToInt16:
5112 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005113 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005114 case glslang::EOpConvFloatToInt:
5115 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005116 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005117 case glslang::EOpConvFloatToInt64:
5118 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005119 convOp = spv::OpConvertFToS;
5120 break;
5121
John Kessenich66011cb2018-03-06 16:12:04 -07005122 case glslang::EOpConvUint8ToInt8:
5123 case glslang::EOpConvInt8ToUint8:
5124 case glslang::EOpConvUint16ToInt16:
5125 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005126 case glslang::EOpConvUintToInt:
5127 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005128 case glslang::EOpConvUint64ToInt64:
5129 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005130 if (builder.isInSpecConstCodeGenMode()) {
5131 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005132 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5133 zero = builder.makeUint8Constant(0);
5134 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005135 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005136 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5137 zero = builder.makeUint64Constant(0);
5138 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005139 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005140 }
qining189b2032016-04-12 23:16:20 -04005141 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005142 // Use OpIAdd, instead of OpBitcast to do the conversion when
5143 // generating for OpSpecConstantOp instruction.
5144 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5145 }
5146 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005147 convOp = spv::OpBitcast;
5148 break;
5149
John Kessenich66011cb2018-03-06 16:12:04 -07005150 case glslang::EOpConvFloat16ToUint8:
5151 case glslang::EOpConvFloatToUint8:
5152 case glslang::EOpConvDoubleToUint8:
5153 case glslang::EOpConvFloat16ToUint16:
5154 case glslang::EOpConvFloatToUint16:
5155 case glslang::EOpConvDoubleToUint16:
5156 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005157 case glslang::EOpConvFloatToUint:
5158 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005159 case glslang::EOpConvFloatToUint64:
5160 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005161 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005162 convOp = spv::OpConvertFToU;
5163 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005164
John Kessenich66011cb2018-03-06 16:12:04 -07005165 case glslang::EOpConvInt8ToInt16:
5166 case glslang::EOpConvInt8ToInt:
5167 case glslang::EOpConvInt8ToInt64:
5168 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005169 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005170 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005171 case glslang::EOpConvIntToInt8:
5172 case glslang::EOpConvIntToInt16:
5173 case glslang::EOpConvIntToInt64:
5174 case glslang::EOpConvInt64ToInt8:
5175 case glslang::EOpConvInt64ToInt16:
5176 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005177 convOp = spv::OpSConvert;
5178 break;
5179
John Kessenich66011cb2018-03-06 16:12:04 -07005180 case glslang::EOpConvUint8ToUint16:
5181 case glslang::EOpConvUint8ToUint:
5182 case glslang::EOpConvUint8ToUint64:
5183 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005184 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005185 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005186 case glslang::EOpConvUintToUint8:
5187 case glslang::EOpConvUintToUint16:
5188 case glslang::EOpConvUintToUint64:
5189 case glslang::EOpConvUint64ToUint8:
5190 case glslang::EOpConvUint64ToUint16:
5191 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005192 convOp = spv::OpUConvert;
5193 break;
5194
John Kessenich66011cb2018-03-06 16:12:04 -07005195 case glslang::EOpConvInt8ToUint16:
5196 case glslang::EOpConvInt8ToUint:
5197 case glslang::EOpConvInt8ToUint64:
5198 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005199 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005200 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005201 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005202 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005203 case glslang::EOpConvIntToUint64:
5204 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005205 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005206 case glslang::EOpConvInt64ToUint:
5207 case glslang::EOpConvUint8ToInt16:
5208 case glslang::EOpConvUint8ToInt:
5209 case glslang::EOpConvUint8ToInt64:
5210 case glslang::EOpConvUint16ToInt8:
5211 case glslang::EOpConvUint16ToInt:
5212 case glslang::EOpConvUint16ToInt64:
5213 case glslang::EOpConvUintToInt8:
5214 case glslang::EOpConvUintToInt16:
5215 case glslang::EOpConvUintToInt64:
5216 case glslang::EOpConvUint64ToInt8:
5217 case glslang::EOpConvUint64ToInt16:
5218 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005219 // OpSConvert/OpUConvert + OpBitCast
John Kessenich66011cb2018-03-06 16:12:04 -07005220 operand = createConversionOperation(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005221
5222 if (builder.isInSpecConstCodeGenMode()) {
5223 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005224 switch(op) {
5225 case glslang::EOpConvInt16ToUint8:
5226 case glslang::EOpConvIntToUint8:
5227 case glslang::EOpConvInt64ToUint8:
5228 case glslang::EOpConvUint16ToInt8:
5229 case glslang::EOpConvUintToInt8:
5230 case glslang::EOpConvUint64ToInt8:
5231 zero = builder.makeUint8Constant(0);
5232 break;
5233 case glslang::EOpConvInt8ToUint16:
5234 case glslang::EOpConvIntToUint16:
5235 case glslang::EOpConvInt64ToUint16:
5236 case glslang::EOpConvUint8ToInt16:
5237 case glslang::EOpConvUintToInt16:
5238 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005239 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005240 break;
5241 case glslang::EOpConvInt8ToUint:
5242 case glslang::EOpConvInt16ToUint:
5243 case glslang::EOpConvInt64ToUint:
5244 case glslang::EOpConvUint8ToInt:
5245 case glslang::EOpConvUint16ToInt:
5246 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005247 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005248 break;
5249 case glslang::EOpConvInt8ToUint64:
5250 case glslang::EOpConvInt16ToUint64:
5251 case glslang::EOpConvIntToUint64:
5252 case glslang::EOpConvUint8ToInt64:
5253 case glslang::EOpConvUint16ToInt64:
5254 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005255 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005256 break;
5257 default:
5258 assert(false && "Default missing");
5259 break;
5260 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005261 zero = makeSmearedConstant(zero, vectorSize);
5262 // Use OpIAdd, instead of OpBitcast to do the conversion when
5263 // generating for OpSpecConstantOp instruction.
5264 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5265 }
5266 // For normal run-time conversion instruction, use OpBitcast.
5267 convOp = spv::OpBitcast;
5268 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005269 default:
5270 break;
5271 }
5272
5273 spv::Id result = 0;
5274 if (convOp == spv::OpNop)
5275 return result;
5276
5277 if (convOp == spv::OpSelect) {
5278 zero = makeSmearedConstant(zero, vectorSize);
5279 one = makeSmearedConstant(one, vectorSize);
5280 result = builder.createTriOp(convOp, destType, operand, one, zero);
5281 } else
5282 result = builder.createUnaryOp(convOp, destType, operand);
5283
John Kessenichead86222018-03-28 18:01:20 -06005284 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005285 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005286 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06005287}
5288
5289spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
5290{
5291 if (vectorSize == 0)
5292 return constant;
5293
5294 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
5295 std::vector<spv::Id> components;
5296 for (int c = 0; c < vectorSize; ++c)
5297 components.push_back(constant);
5298 return builder.makeCompositeConstant(vectorTypeId, components);
5299}
5300
John Kessenich426394d2015-07-23 10:22:48 -06005301// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07005302spv::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 -06005303{
5304 spv::Op opCode = spv::OpNop;
5305
5306 switch (op) {
5307 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08005308 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005309 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06005310 opCode = spv::OpAtomicIAdd;
5311 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06005312 case glslang::EOpAtomicCounterSubtract:
5313 opCode = spv::OpAtomicISub;
5314 break;
John Kessenich426394d2015-07-23 10:22:48 -06005315 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08005316 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005317 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08005318 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06005319 break;
5320 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08005321 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005322 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08005323 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06005324 break;
5325 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08005326 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005327 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06005328 opCode = spv::OpAtomicAnd;
5329 break;
5330 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08005331 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005332 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06005333 opCode = spv::OpAtomicOr;
5334 break;
5335 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08005336 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005337 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06005338 opCode = spv::OpAtomicXor;
5339 break;
5340 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08005341 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005342 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06005343 opCode = spv::OpAtomicExchange;
5344 break;
5345 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08005346 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005347 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06005348 opCode = spv::OpAtomicCompareExchange;
5349 break;
5350 case glslang::EOpAtomicCounterIncrement:
5351 opCode = spv::OpAtomicIIncrement;
5352 break;
5353 case glslang::EOpAtomicCounterDecrement:
5354 opCode = spv::OpAtomicIDecrement;
5355 break;
5356 case glslang::EOpAtomicCounter:
5357 opCode = spv::OpAtomicLoad;
5358 break;
5359 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005360 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06005361 break;
5362 }
5363
Rex Xue8fe8b02017-09-26 15:42:56 +08005364 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
5365 builder.addCapability(spv::CapabilityInt64Atomics);
5366
John Kessenich426394d2015-07-23 10:22:48 -06005367 // Sort out the operands
5368 // - mapping from glslang -> SPV
5369 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06005370 // - compare-exchange swaps the value and comparator
5371 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06005372 // - EOpAtomicCounterDecrement needs a post decrement
John Kessenich426394d2015-07-23 10:22:48 -06005373 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
5374 auto opIt = operands.begin(); // walk the glslang operands
5375 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08005376 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
5377 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
5378 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08005379 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
5380 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08005381 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06005382 spvAtomicOperands.push_back(*(opIt + 1));
5383 spvAtomicOperands.push_back(*opIt);
5384 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08005385 }
John Kessenich426394d2015-07-23 10:22:48 -06005386
John Kessenich3e60a6f2015-09-14 22:45:16 -06005387 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06005388 for (; opIt != operands.end(); ++opIt)
5389 spvAtomicOperands.push_back(*opIt);
5390
John Kessenich48d6e792017-10-06 21:21:48 -06005391 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
5392
5393 // GLSL and HLSL atomic-counter decrement return post-decrement value,
5394 // while SPIR-V returns pre-decrement value. Translate between these semantics.
5395 if (op == glslang::EOpAtomicCounterDecrement)
5396 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
5397
5398 return resultId;
John Kessenich426394d2015-07-23 10:22:48 -06005399}
5400
John Kessenich91cef522016-05-05 16:45:40 -06005401// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08005402spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06005403{
John Kessenich66011cb2018-03-06 16:12:04 -07005404 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5405 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08005406
Rex Xu51596642016-09-21 18:56:12 +08005407 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08005408 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08005409 spv::GroupOperation groupOperation = spv::GroupOperationMax;
5410
chaocf200da82016-12-20 12:44:35 -08005411 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
5412 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08005413 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
5414 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005415 } else if (op == glslang::EOpAnyInvocation ||
5416 op == glslang::EOpAllInvocations ||
5417 op == glslang::EOpAllInvocationsEqual) {
5418 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
5419 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08005420 } else {
5421 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04005422#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08005423 if (op == glslang::EOpMinInvocationsNonUniform ||
5424 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08005425 op == glslang::EOpAddInvocationsNonUniform ||
5426 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5427 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5428 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
5429 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
5430 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
5431 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08005432 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04005433#endif
Rex Xu51596642016-09-21 18:56:12 +08005434
5435 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08005436#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08005437 switch (op) {
5438 case glslang::EOpMinInvocations:
5439 case glslang::EOpMaxInvocations:
5440 case glslang::EOpAddInvocations:
5441 case glslang::EOpMinInvocationsNonUniform:
5442 case glslang::EOpMaxInvocationsNonUniform:
5443 case glslang::EOpAddInvocationsNonUniform:
5444 groupOperation = spv::GroupOperationReduce;
5445 spvGroupOperands.push_back(groupOperation);
5446 break;
5447 case glslang::EOpMinInvocationsInclusiveScan:
5448 case glslang::EOpMaxInvocationsInclusiveScan:
5449 case glslang::EOpAddInvocationsInclusiveScan:
5450 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5451 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5452 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5453 groupOperation = spv::GroupOperationInclusiveScan;
5454 spvGroupOperands.push_back(groupOperation);
5455 break;
5456 case glslang::EOpMinInvocationsExclusiveScan:
5457 case glslang::EOpMaxInvocationsExclusiveScan:
5458 case glslang::EOpAddInvocationsExclusiveScan:
5459 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5460 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5461 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5462 groupOperation = spv::GroupOperationExclusiveScan;
5463 spvGroupOperands.push_back(groupOperation);
5464 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07005465 default:
5466 break;
Rex Xu430ef402016-10-14 17:22:23 +08005467 }
Rex Xu9d93a232016-05-05 12:30:44 +08005468#endif
Rex Xu51596642016-09-21 18:56:12 +08005469 }
5470
5471 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
5472 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06005473
5474 switch (op) {
5475 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005476 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08005477 break;
John Kessenich91cef522016-05-05 16:45:40 -06005478 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005479 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08005480 break;
John Kessenich91cef522016-05-05 16:45:40 -06005481 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005482 opCode = spv::OpSubgroupAllEqualKHR;
5483 break;
Rex Xu51596642016-09-21 18:56:12 +08005484 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08005485 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08005486 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005487 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005488 break;
5489 case glslang::EOpReadFirstInvocation:
5490 opCode = spv::OpSubgroupFirstInvocationKHR;
5491 break;
5492 case glslang::EOpBallot:
5493 {
5494 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
5495 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
5496 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
5497 //
5498 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
5499 //
5500 spv::Id uintType = builder.makeUintType(32);
5501 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
5502 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
5503
5504 std::vector<spv::Id> components;
5505 components.push_back(builder.createCompositeExtract(result, uintType, 0));
5506 components.push_back(builder.createCompositeExtract(result, uintType, 1));
5507
5508 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
5509 return builder.createUnaryOp(spv::OpBitcast, typeId,
5510 builder.createCompositeConstruct(uvec2Type, components));
5511 }
5512
Rex Xu9d93a232016-05-05 12:30:44 +08005513#ifdef AMD_EXTENSIONS
5514 case glslang::EOpMinInvocations:
5515 case glslang::EOpMaxInvocations:
5516 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08005517 case glslang::EOpMinInvocationsInclusiveScan:
5518 case glslang::EOpMaxInvocationsInclusiveScan:
5519 case glslang::EOpAddInvocationsInclusiveScan:
5520 case glslang::EOpMinInvocationsExclusiveScan:
5521 case glslang::EOpMaxInvocationsExclusiveScan:
5522 case glslang::EOpAddInvocationsExclusiveScan:
5523 if (op == glslang::EOpMinInvocations ||
5524 op == glslang::EOpMinInvocationsInclusiveScan ||
5525 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005526 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005527 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005528 else {
5529 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005530 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005531 else
Rex Xu51596642016-09-21 18:56:12 +08005532 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005533 }
Rex Xu430ef402016-10-14 17:22:23 +08005534 } else if (op == glslang::EOpMaxInvocations ||
5535 op == glslang::EOpMaxInvocationsInclusiveScan ||
5536 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005537 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005538 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005539 else {
5540 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005541 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005542 else
Rex Xu51596642016-09-21 18:56:12 +08005543 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005544 }
5545 } else {
5546 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005547 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005548 else
Rex Xu51596642016-09-21 18:56:12 +08005549 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005550 }
5551
Rex Xu2bbbe062016-08-23 15:41:05 +08005552 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005553 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005554
5555 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005556 case glslang::EOpMinInvocationsNonUniform:
5557 case glslang::EOpMaxInvocationsNonUniform:
5558 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005559 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5560 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5561 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5562 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5563 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5564 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5565 if (op == glslang::EOpMinInvocationsNonUniform ||
5566 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5567 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005568 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005569 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005570 else {
5571 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005572 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005573 else
Rex Xu51596642016-09-21 18:56:12 +08005574 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005575 }
5576 }
Rex Xu430ef402016-10-14 17:22:23 +08005577 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5578 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5579 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005580 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005581 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005582 else {
5583 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005584 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005585 else
Rex Xu51596642016-09-21 18:56:12 +08005586 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005587 }
5588 }
5589 else {
5590 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005591 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005592 else
Rex Xu51596642016-09-21 18:56:12 +08005593 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005594 }
5595
Rex Xu2bbbe062016-08-23 15:41:05 +08005596 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005597 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005598
5599 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005600#endif
John Kessenich91cef522016-05-05 16:45:40 -06005601 default:
5602 logger->missingFunctionality("invocation operation");
5603 return spv::NoResult;
5604 }
Rex Xu51596642016-09-21 18:56:12 +08005605
5606 assert(opCode != spv::OpNop);
5607 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005608}
5609
Rex Xu2bbbe062016-08-23 15:41:05 +08005610// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005611spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005612{
Rex Xub7072052016-09-26 15:53:40 +08005613#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005614 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5615 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005616 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005617 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005618 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5619 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5620 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005621#else
5622 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5623 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005624 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5625 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005626#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005627
5628 // Handle group invocation operations scalar by scalar.
5629 // The result type is the same type as the original type.
5630 // The algorithm is to:
5631 // - break the vector into scalars
5632 // - apply the operation to each scalar
5633 // - make a vector out the scalar results
5634
5635 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005636 int numComponents = builder.getNumComponents(operands[0]);
5637 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005638 std::vector<spv::Id> results;
5639
5640 // do each scalar op
5641 for (int comp = 0; comp < numComponents; ++comp) {
5642 std::vector<unsigned int> indexes;
5643 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005644 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005645 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005646 if (op == spv::OpSubgroupReadInvocationKHR) {
5647 spvGroupOperands.push_back(scalar);
5648 spvGroupOperands.push_back(operands[1]);
5649 } else if (op == spv::OpGroupBroadcast) {
5650 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005651 spvGroupOperands.push_back(scalar);
5652 spvGroupOperands.push_back(operands[1]);
5653 } else {
chaocf200da82016-12-20 12:44:35 -08005654 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005655 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005656 spvGroupOperands.push_back(scalar);
5657 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005658
Rex Xub7072052016-09-26 15:53:40 +08005659 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005660 }
5661
5662 // put the pieces together
5663 return builder.createCompositeConstruct(typeId, results);
5664}
Rex Xu2bbbe062016-08-23 15:41:05 +08005665
John Kessenich66011cb2018-03-06 16:12:04 -07005666// Create subgroup invocation operations.
5667spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
5668{
5669 // Add the required capabilities.
5670 switch (op) {
5671 case glslang::EOpSubgroupElect:
5672 builder.addCapability(spv::CapabilityGroupNonUniform);
5673 break;
5674 case glslang::EOpSubgroupAll:
5675 case glslang::EOpSubgroupAny:
5676 case glslang::EOpSubgroupAllEqual:
5677 builder.addCapability(spv::CapabilityGroupNonUniform);
5678 builder.addCapability(spv::CapabilityGroupNonUniformVote);
5679 break;
5680 case glslang::EOpSubgroupBroadcast:
5681 case glslang::EOpSubgroupBroadcastFirst:
5682 case glslang::EOpSubgroupBallot:
5683 case glslang::EOpSubgroupInverseBallot:
5684 case glslang::EOpSubgroupBallotBitExtract:
5685 case glslang::EOpSubgroupBallotBitCount:
5686 case glslang::EOpSubgroupBallotInclusiveBitCount:
5687 case glslang::EOpSubgroupBallotExclusiveBitCount:
5688 case glslang::EOpSubgroupBallotFindLSB:
5689 case glslang::EOpSubgroupBallotFindMSB:
5690 builder.addCapability(spv::CapabilityGroupNonUniform);
5691 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
5692 break;
5693 case glslang::EOpSubgroupShuffle:
5694 case glslang::EOpSubgroupShuffleXor:
5695 builder.addCapability(spv::CapabilityGroupNonUniform);
5696 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
5697 break;
5698 case glslang::EOpSubgroupShuffleUp:
5699 case glslang::EOpSubgroupShuffleDown:
5700 builder.addCapability(spv::CapabilityGroupNonUniform);
5701 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
5702 break;
5703 case glslang::EOpSubgroupAdd:
5704 case glslang::EOpSubgroupMul:
5705 case glslang::EOpSubgroupMin:
5706 case glslang::EOpSubgroupMax:
5707 case glslang::EOpSubgroupAnd:
5708 case glslang::EOpSubgroupOr:
5709 case glslang::EOpSubgroupXor:
5710 case glslang::EOpSubgroupInclusiveAdd:
5711 case glslang::EOpSubgroupInclusiveMul:
5712 case glslang::EOpSubgroupInclusiveMin:
5713 case glslang::EOpSubgroupInclusiveMax:
5714 case glslang::EOpSubgroupInclusiveAnd:
5715 case glslang::EOpSubgroupInclusiveOr:
5716 case glslang::EOpSubgroupInclusiveXor:
5717 case glslang::EOpSubgroupExclusiveAdd:
5718 case glslang::EOpSubgroupExclusiveMul:
5719 case glslang::EOpSubgroupExclusiveMin:
5720 case glslang::EOpSubgroupExclusiveMax:
5721 case glslang::EOpSubgroupExclusiveAnd:
5722 case glslang::EOpSubgroupExclusiveOr:
5723 case glslang::EOpSubgroupExclusiveXor:
5724 builder.addCapability(spv::CapabilityGroupNonUniform);
5725 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
5726 break;
5727 case glslang::EOpSubgroupClusteredAdd:
5728 case glslang::EOpSubgroupClusteredMul:
5729 case glslang::EOpSubgroupClusteredMin:
5730 case glslang::EOpSubgroupClusteredMax:
5731 case glslang::EOpSubgroupClusteredAnd:
5732 case glslang::EOpSubgroupClusteredOr:
5733 case glslang::EOpSubgroupClusteredXor:
5734 builder.addCapability(spv::CapabilityGroupNonUniform);
5735 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
5736 break;
5737 case glslang::EOpSubgroupQuadBroadcast:
5738 case glslang::EOpSubgroupQuadSwapHorizontal:
5739 case glslang::EOpSubgroupQuadSwapVertical:
5740 case glslang::EOpSubgroupQuadSwapDiagonal:
5741 builder.addCapability(spv::CapabilityGroupNonUniform);
5742 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
5743 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005744#ifdef NV_EXTENSIONS
5745 case glslang::EOpSubgroupPartitionedAdd:
5746 case glslang::EOpSubgroupPartitionedMul:
5747 case glslang::EOpSubgroupPartitionedMin:
5748 case glslang::EOpSubgroupPartitionedMax:
5749 case glslang::EOpSubgroupPartitionedAnd:
5750 case glslang::EOpSubgroupPartitionedOr:
5751 case glslang::EOpSubgroupPartitionedXor:
5752 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5753 case glslang::EOpSubgroupPartitionedInclusiveMul:
5754 case glslang::EOpSubgroupPartitionedInclusiveMin:
5755 case glslang::EOpSubgroupPartitionedInclusiveMax:
5756 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5757 case glslang::EOpSubgroupPartitionedInclusiveOr:
5758 case glslang::EOpSubgroupPartitionedInclusiveXor:
5759 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5760 case glslang::EOpSubgroupPartitionedExclusiveMul:
5761 case glslang::EOpSubgroupPartitionedExclusiveMin:
5762 case glslang::EOpSubgroupPartitionedExclusiveMax:
5763 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5764 case glslang::EOpSubgroupPartitionedExclusiveOr:
5765 case glslang::EOpSubgroupPartitionedExclusiveXor:
5766 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
5767 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
5768 break;
5769#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005770 default: assert(0 && "Unhandled subgroup operation!");
5771 }
5772
5773 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
5774 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
5775 const bool isBool = typeProxy == glslang::EbtBool;
5776
5777 spv::Op opCode = spv::OpNop;
5778
5779 // Figure out which opcode to use.
5780 switch (op) {
5781 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
5782 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
5783 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
5784 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
5785 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
5786 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
5787 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
5788 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
5789 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
5790 case glslang::EOpSubgroupBallotBitCount:
5791 case glslang::EOpSubgroupBallotInclusiveBitCount:
5792 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
5793 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
5794 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
5795 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
5796 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
5797 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
5798 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
5799 case glslang::EOpSubgroupAdd:
5800 case glslang::EOpSubgroupInclusiveAdd:
5801 case glslang::EOpSubgroupExclusiveAdd:
5802 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005803#ifdef NV_EXTENSIONS
5804 case glslang::EOpSubgroupPartitionedAdd:
5805 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5806 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5807#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005808 if (isFloat) {
5809 opCode = spv::OpGroupNonUniformFAdd;
5810 } else {
5811 opCode = spv::OpGroupNonUniformIAdd;
5812 }
5813 break;
5814 case glslang::EOpSubgroupMul:
5815 case glslang::EOpSubgroupInclusiveMul:
5816 case glslang::EOpSubgroupExclusiveMul:
5817 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005818#ifdef NV_EXTENSIONS
5819 case glslang::EOpSubgroupPartitionedMul:
5820 case glslang::EOpSubgroupPartitionedInclusiveMul:
5821 case glslang::EOpSubgroupPartitionedExclusiveMul:
5822#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005823 if (isFloat) {
5824 opCode = spv::OpGroupNonUniformFMul;
5825 } else {
5826 opCode = spv::OpGroupNonUniformIMul;
5827 }
5828 break;
5829 case glslang::EOpSubgroupMin:
5830 case glslang::EOpSubgroupInclusiveMin:
5831 case glslang::EOpSubgroupExclusiveMin:
5832 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005833#ifdef NV_EXTENSIONS
5834 case glslang::EOpSubgroupPartitionedMin:
5835 case glslang::EOpSubgroupPartitionedInclusiveMin:
5836 case glslang::EOpSubgroupPartitionedExclusiveMin:
5837#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005838 if (isFloat) {
5839 opCode = spv::OpGroupNonUniformFMin;
5840 } else if (isUnsigned) {
5841 opCode = spv::OpGroupNonUniformUMin;
5842 } else {
5843 opCode = spv::OpGroupNonUniformSMin;
5844 }
5845 break;
5846 case glslang::EOpSubgroupMax:
5847 case glslang::EOpSubgroupInclusiveMax:
5848 case glslang::EOpSubgroupExclusiveMax:
5849 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005850#ifdef NV_EXTENSIONS
5851 case glslang::EOpSubgroupPartitionedMax:
5852 case glslang::EOpSubgroupPartitionedInclusiveMax:
5853 case glslang::EOpSubgroupPartitionedExclusiveMax:
5854#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005855 if (isFloat) {
5856 opCode = spv::OpGroupNonUniformFMax;
5857 } else if (isUnsigned) {
5858 opCode = spv::OpGroupNonUniformUMax;
5859 } else {
5860 opCode = spv::OpGroupNonUniformSMax;
5861 }
5862 break;
5863 case glslang::EOpSubgroupAnd:
5864 case glslang::EOpSubgroupInclusiveAnd:
5865 case glslang::EOpSubgroupExclusiveAnd:
5866 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005867#ifdef NV_EXTENSIONS
5868 case glslang::EOpSubgroupPartitionedAnd:
5869 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5870 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5871#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005872 if (isBool) {
5873 opCode = spv::OpGroupNonUniformLogicalAnd;
5874 } else {
5875 opCode = spv::OpGroupNonUniformBitwiseAnd;
5876 }
5877 break;
5878 case glslang::EOpSubgroupOr:
5879 case glslang::EOpSubgroupInclusiveOr:
5880 case glslang::EOpSubgroupExclusiveOr:
5881 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005882#ifdef NV_EXTENSIONS
5883 case glslang::EOpSubgroupPartitionedOr:
5884 case glslang::EOpSubgroupPartitionedInclusiveOr:
5885 case glslang::EOpSubgroupPartitionedExclusiveOr:
5886#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005887 if (isBool) {
5888 opCode = spv::OpGroupNonUniformLogicalOr;
5889 } else {
5890 opCode = spv::OpGroupNonUniformBitwiseOr;
5891 }
5892 break;
5893 case glslang::EOpSubgroupXor:
5894 case glslang::EOpSubgroupInclusiveXor:
5895 case glslang::EOpSubgroupExclusiveXor:
5896 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005897#ifdef NV_EXTENSIONS
5898 case glslang::EOpSubgroupPartitionedXor:
5899 case glslang::EOpSubgroupPartitionedInclusiveXor:
5900 case glslang::EOpSubgroupPartitionedExclusiveXor:
5901#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005902 if (isBool) {
5903 opCode = spv::OpGroupNonUniformLogicalXor;
5904 } else {
5905 opCode = spv::OpGroupNonUniformBitwiseXor;
5906 }
5907 break;
5908 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
5909 case glslang::EOpSubgroupQuadSwapHorizontal:
5910 case glslang::EOpSubgroupQuadSwapVertical:
5911 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
5912 default: assert(0 && "Unhandled subgroup operation!");
5913 }
5914
5915 std::vector<spv::Id> spvGroupOperands;
5916
5917 // Every operation begins with the Execution Scope operand.
5918 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
5919
5920 // Next, for all operations that use a Group Operation, push that as an operand.
5921 switch (op) {
5922 default: break;
5923 case glslang::EOpSubgroupBallotBitCount:
5924 case glslang::EOpSubgroupAdd:
5925 case glslang::EOpSubgroupMul:
5926 case glslang::EOpSubgroupMin:
5927 case glslang::EOpSubgroupMax:
5928 case glslang::EOpSubgroupAnd:
5929 case glslang::EOpSubgroupOr:
5930 case glslang::EOpSubgroupXor:
5931 spvGroupOperands.push_back(spv::GroupOperationReduce);
5932 break;
5933 case glslang::EOpSubgroupBallotInclusiveBitCount:
5934 case glslang::EOpSubgroupInclusiveAdd:
5935 case glslang::EOpSubgroupInclusiveMul:
5936 case glslang::EOpSubgroupInclusiveMin:
5937 case glslang::EOpSubgroupInclusiveMax:
5938 case glslang::EOpSubgroupInclusiveAnd:
5939 case glslang::EOpSubgroupInclusiveOr:
5940 case glslang::EOpSubgroupInclusiveXor:
5941 spvGroupOperands.push_back(spv::GroupOperationInclusiveScan);
5942 break;
5943 case glslang::EOpSubgroupBallotExclusiveBitCount:
5944 case glslang::EOpSubgroupExclusiveAdd:
5945 case glslang::EOpSubgroupExclusiveMul:
5946 case glslang::EOpSubgroupExclusiveMin:
5947 case glslang::EOpSubgroupExclusiveMax:
5948 case glslang::EOpSubgroupExclusiveAnd:
5949 case glslang::EOpSubgroupExclusiveOr:
5950 case glslang::EOpSubgroupExclusiveXor:
5951 spvGroupOperands.push_back(spv::GroupOperationExclusiveScan);
5952 break;
5953 case glslang::EOpSubgroupClusteredAdd:
5954 case glslang::EOpSubgroupClusteredMul:
5955 case glslang::EOpSubgroupClusteredMin:
5956 case glslang::EOpSubgroupClusteredMax:
5957 case glslang::EOpSubgroupClusteredAnd:
5958 case glslang::EOpSubgroupClusteredOr:
5959 case glslang::EOpSubgroupClusteredXor:
5960 spvGroupOperands.push_back(spv::GroupOperationClusteredReduce);
5961 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005962#ifdef NV_EXTENSIONS
5963 case glslang::EOpSubgroupPartitionedAdd:
5964 case glslang::EOpSubgroupPartitionedMul:
5965 case glslang::EOpSubgroupPartitionedMin:
5966 case glslang::EOpSubgroupPartitionedMax:
5967 case glslang::EOpSubgroupPartitionedAnd:
5968 case glslang::EOpSubgroupPartitionedOr:
5969 case glslang::EOpSubgroupPartitionedXor:
5970 spvGroupOperands.push_back(spv::GroupOperationPartitionedReduceNV);
5971 break;
5972 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5973 case glslang::EOpSubgroupPartitionedInclusiveMul:
5974 case glslang::EOpSubgroupPartitionedInclusiveMin:
5975 case glslang::EOpSubgroupPartitionedInclusiveMax:
5976 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5977 case glslang::EOpSubgroupPartitionedInclusiveOr:
5978 case glslang::EOpSubgroupPartitionedInclusiveXor:
5979 spvGroupOperands.push_back(spv::GroupOperationPartitionedInclusiveScanNV);
5980 break;
5981 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5982 case glslang::EOpSubgroupPartitionedExclusiveMul:
5983 case glslang::EOpSubgroupPartitionedExclusiveMin:
5984 case glslang::EOpSubgroupPartitionedExclusiveMax:
5985 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5986 case glslang::EOpSubgroupPartitionedExclusiveOr:
5987 case glslang::EOpSubgroupPartitionedExclusiveXor:
5988 spvGroupOperands.push_back(spv::GroupOperationPartitionedExclusiveScanNV);
5989 break;
5990#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005991 }
5992
5993 // Push back the operands next.
5994 for (auto opIt : operands) {
5995 spvGroupOperands.push_back(opIt);
5996 }
5997
5998 // Some opcodes have additional operands.
5999 switch (op) {
6000 default: break;
6001 case glslang::EOpSubgroupQuadSwapHorizontal: spvGroupOperands.push_back(builder.makeUintConstant(0)); break;
6002 case glslang::EOpSubgroupQuadSwapVertical: spvGroupOperands.push_back(builder.makeUintConstant(1)); break;
6003 case glslang::EOpSubgroupQuadSwapDiagonal: spvGroupOperands.push_back(builder.makeUintConstant(2)); break;
6004 }
6005
6006 return builder.createOp(opCode, typeId, spvGroupOperands);
6007}
6008
John Kessenich5e4b1242015-08-06 22:53:06 -06006009spv::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 -06006010{
John Kessenich66011cb2018-03-06 16:12:04 -07006011 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6012 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006013
John Kessenich140f3df2015-06-26 16:58:36 -06006014 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006015 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006016 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006017 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006018 spv::Id typeId0 = 0;
6019 if (consumedOperands > 0)
6020 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006021 spv::Id typeId1 = 0;
6022 if (consumedOperands > 1)
6023 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006024 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006025
6026 switch (op) {
6027 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006028 if (isFloat)
6029 libCall = spv::GLSLstd450FMin;
6030 else if (isUnsigned)
6031 libCall = spv::GLSLstd450UMin;
6032 else
6033 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006034 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006035 break;
6036 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006037 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006038 break;
6039 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006040 if (isFloat)
6041 libCall = spv::GLSLstd450FMax;
6042 else if (isUnsigned)
6043 libCall = spv::GLSLstd450UMax;
6044 else
6045 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006046 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006047 break;
6048 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006049 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006050 break;
6051 case glslang::EOpDot:
6052 opCode = spv::OpDot;
6053 break;
6054 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006055 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006056 break;
6057
6058 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006059 if (isFloat)
6060 libCall = spv::GLSLstd450FClamp;
6061 else if (isUnsigned)
6062 libCall = spv::GLSLstd450UClamp;
6063 else
6064 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006065 builder.promoteScalar(precision, operands.front(), operands[1]);
6066 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006067 break;
6068 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006069 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6070 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006071 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006072 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006073 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006074 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006075 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006076 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006077 break;
6078 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006079 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006080 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006081 break;
6082 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006083 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006084 builder.promoteScalar(precision, operands[0], operands[2]);
6085 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006086 break;
6087
6088 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006089 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006090 break;
6091 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006092 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006093 break;
6094 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006095 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006096 break;
6097 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006098 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006099 break;
6100 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006101 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006102 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006103 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006104#ifdef AMD_EXTENSIONS
6105 if (typeProxy == glslang::EbtFloat16)
6106 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6107#endif
John Kessenich92187592016-02-01 13:45:25 -07006108 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08006109 libCall = spv::GLSLstd450InterpolateAtSample;
6110 break;
6111 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006112#ifdef AMD_EXTENSIONS
6113 if (typeProxy == glslang::EbtFloat16)
6114 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6115#endif
John Kessenich92187592016-02-01 13:45:25 -07006116 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08006117 libCall = spv::GLSLstd450InterpolateAtOffset;
6118 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006119 case glslang::EOpAddCarry:
6120 opCode = spv::OpIAddCarry;
6121 typeId = builder.makeStructResultType(typeId0, typeId0);
6122 consumedOperands = 2;
6123 break;
6124 case glslang::EOpSubBorrow:
6125 opCode = spv::OpISubBorrow;
6126 typeId = builder.makeStructResultType(typeId0, typeId0);
6127 consumedOperands = 2;
6128 break;
6129 case glslang::EOpUMulExtended:
6130 opCode = spv::OpUMulExtended;
6131 typeId = builder.makeStructResultType(typeId0, typeId0);
6132 consumedOperands = 2;
6133 break;
6134 case glslang::EOpIMulExtended:
6135 opCode = spv::OpSMulExtended;
6136 typeId = builder.makeStructResultType(typeId0, typeId0);
6137 consumedOperands = 2;
6138 break;
6139 case glslang::EOpBitfieldExtract:
6140 if (isUnsigned)
6141 opCode = spv::OpBitFieldUExtract;
6142 else
6143 opCode = spv::OpBitFieldSExtract;
6144 break;
6145 case glslang::EOpBitfieldInsert:
6146 opCode = spv::OpBitFieldInsert;
6147 break;
6148
6149 case glslang::EOpFma:
6150 libCall = spv::GLSLstd450Fma;
6151 break;
6152 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006153 {
6154 libCall = spv::GLSLstd450FrexpStruct;
6155 assert(builder.isPointerType(typeId1));
6156 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006157 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006158#ifdef AMD_EXTENSIONS
6159 if (width == 16)
6160 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6161 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
6162#endif
Rex Xu470026f2017-03-29 17:12:40 +08006163 if (builder.getNumComponents(operands[0]) == 1)
6164 frexpIntType = builder.makeIntegerType(width, true);
6165 else
6166 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6167 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6168 consumedOperands = 1;
6169 }
John Kessenich55e7d112015-11-15 21:33:39 -07006170 break;
6171 case glslang::EOpLdexp:
6172 libCall = spv::GLSLstd450Ldexp;
6173 break;
6174
Rex Xu574ab042016-04-14 16:53:07 +08006175 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08006176 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08006177
John Kessenich66011cb2018-03-06 16:12:04 -07006178 case glslang::EOpSubgroupBroadcast:
6179 case glslang::EOpSubgroupBallotBitExtract:
6180 case glslang::EOpSubgroupShuffle:
6181 case glslang::EOpSubgroupShuffleXor:
6182 case glslang::EOpSubgroupShuffleUp:
6183 case glslang::EOpSubgroupShuffleDown:
6184 case glslang::EOpSubgroupClusteredAdd:
6185 case glslang::EOpSubgroupClusteredMul:
6186 case glslang::EOpSubgroupClusteredMin:
6187 case glslang::EOpSubgroupClusteredMax:
6188 case glslang::EOpSubgroupClusteredAnd:
6189 case glslang::EOpSubgroupClusteredOr:
6190 case glslang::EOpSubgroupClusteredXor:
6191 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006192#ifdef NV_EXTENSIONS
6193 case glslang::EOpSubgroupPartitionedAdd:
6194 case glslang::EOpSubgroupPartitionedMul:
6195 case glslang::EOpSubgroupPartitionedMin:
6196 case glslang::EOpSubgroupPartitionedMax:
6197 case glslang::EOpSubgroupPartitionedAnd:
6198 case glslang::EOpSubgroupPartitionedOr:
6199 case glslang::EOpSubgroupPartitionedXor:
6200 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6201 case glslang::EOpSubgroupPartitionedInclusiveMul:
6202 case glslang::EOpSubgroupPartitionedInclusiveMin:
6203 case glslang::EOpSubgroupPartitionedInclusiveMax:
6204 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6205 case glslang::EOpSubgroupPartitionedInclusiveOr:
6206 case glslang::EOpSubgroupPartitionedInclusiveXor:
6207 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6208 case glslang::EOpSubgroupPartitionedExclusiveMul:
6209 case glslang::EOpSubgroupPartitionedExclusiveMin:
6210 case glslang::EOpSubgroupPartitionedExclusiveMax:
6211 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6212 case glslang::EOpSubgroupPartitionedExclusiveOr:
6213 case glslang::EOpSubgroupPartitionedExclusiveXor:
6214#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006215 return createSubgroupOperation(op, typeId, operands, typeProxy);
6216
Rex Xu9d93a232016-05-05 12:30:44 +08006217#ifdef AMD_EXTENSIONS
6218 case glslang::EOpSwizzleInvocations:
6219 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6220 libCall = spv::SwizzleInvocationsAMD;
6221 break;
6222 case glslang::EOpSwizzleInvocationsMasked:
6223 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6224 libCall = spv::SwizzleInvocationsMaskedAMD;
6225 break;
6226 case glslang::EOpWriteInvocation:
6227 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6228 libCall = spv::WriteInvocationAMD;
6229 break;
6230
6231 case glslang::EOpMin3:
6232 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6233 if (isFloat)
6234 libCall = spv::FMin3AMD;
6235 else {
6236 if (isUnsigned)
6237 libCall = spv::UMin3AMD;
6238 else
6239 libCall = spv::SMin3AMD;
6240 }
6241 break;
6242 case glslang::EOpMax3:
6243 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6244 if (isFloat)
6245 libCall = spv::FMax3AMD;
6246 else {
6247 if (isUnsigned)
6248 libCall = spv::UMax3AMD;
6249 else
6250 libCall = spv::SMax3AMD;
6251 }
6252 break;
6253 case glslang::EOpMid3:
6254 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6255 if (isFloat)
6256 libCall = spv::FMid3AMD;
6257 else {
6258 if (isUnsigned)
6259 libCall = spv::UMid3AMD;
6260 else
6261 libCall = spv::SMid3AMD;
6262 }
6263 break;
6264
6265 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006266 if (typeProxy == glslang::EbtFloat16)
6267 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08006268 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
6269 libCall = spv::InterpolateAtVertexAMD;
6270 break;
6271#endif
6272
John Kessenich140f3df2015-06-26 16:58:36 -06006273 default:
6274 return 0;
6275 }
6276
6277 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07006278 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05006279 // Use an extended instruction from the standard library.
6280 // Construct the call arguments, without modifying the original operands vector.
6281 // We might need the remaining arguments, e.g. in the EOpFrexp case.
6282 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08006283 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07006284 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07006285 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06006286 case 0:
6287 // should all be handled by visitAggregate and createNoArgOperation
6288 assert(0);
6289 return 0;
6290 case 1:
6291 // should all be handled by createUnaryOperation
6292 assert(0);
6293 return 0;
6294 case 2:
6295 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
6296 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006297 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006298 // anything 3 or over doesn't have l-value operands, so all should be consumed
6299 assert(consumedOperands == operands.size());
6300 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06006301 break;
6302 }
6303 }
6304
John Kessenich55e7d112015-11-15 21:33:39 -07006305 // Decode the return types that were structures
6306 switch (op) {
6307 case glslang::EOpAddCarry:
6308 case glslang::EOpSubBorrow:
6309 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6310 id = builder.createCompositeExtract(id, typeId0, 0);
6311 break;
6312 case glslang::EOpUMulExtended:
6313 case glslang::EOpIMulExtended:
6314 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
6315 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6316 break;
6317 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006318 {
6319 assert(operands.size() == 2);
6320 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
6321 // "exp" is floating-point type (from HLSL intrinsic)
6322 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
6323 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
6324 builder.createStore(member1, operands[1]);
6325 } else
6326 // "exp" is integer type (from GLSL built-in function)
6327 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
6328 id = builder.createCompositeExtract(id, typeId0, 0);
6329 }
John Kessenich55e7d112015-11-15 21:33:39 -07006330 break;
6331 default:
6332 break;
6333 }
6334
John Kessenich32cfd492016-02-02 12:37:46 -07006335 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006336}
6337
Rex Xu9d93a232016-05-05 12:30:44 +08006338// Intrinsics with no arguments (or no return value, and no precision).
6339spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06006340{
6341 // TODO: get the barrier operands correct
6342
6343 switch (op) {
6344 case glslang::EOpEmitVertex:
6345 builder.createNoResultOp(spv::OpEmitVertex);
6346 return 0;
6347 case glslang::EOpEndPrimitive:
6348 builder.createNoResultOp(spv::OpEndPrimitive);
6349 return 0;
6350 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006351 if (glslangIntermediate->getStage() == EShLangTessControl) {
6352 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
6353 // TODO: prefer the following, when available:
6354 // builder.createControlBarrier(spv::ScopePatch, spv::ScopePatch,
6355 // spv::MemorySemanticsPatchMask |
6356 // spv::MemorySemanticsAcquireReleaseMask);
6357 } else {
6358 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6359 spv::MemorySemanticsWorkgroupMemoryMask |
6360 spv::MemorySemanticsAcquireReleaseMask);
6361 }
John Kessenich140f3df2015-06-26 16:58:36 -06006362 return 0;
6363 case glslang::EOpMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006364 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory |
6365 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006366 return 0;
6367 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich82979362017-12-11 04:02:24 -07006368 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask |
6369 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006370 return 0;
6371 case glslang::EOpMemoryBarrierBuffer:
John Kessenich82979362017-12-11 04:02:24 -07006372 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6373 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006374 return 0;
6375 case glslang::EOpMemoryBarrierImage:
John Kessenich82979362017-12-11 04:02:24 -07006376 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask |
6377 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006378 return 0;
6379 case glslang::EOpMemoryBarrierShared:
John Kessenich82979362017-12-11 04:02:24 -07006380 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask |
6381 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006382 return 0;
6383 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006384 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
6385 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006386 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06006387 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006388 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07006389 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07006390 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006391 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07006392 case glslang::EOpDeviceMemoryBarrier:
6393 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6394 spv::MemorySemanticsImageMemoryMask |
6395 spv::MemorySemanticsAcquireReleaseMask);
6396 return 0;
6397 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
6398 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6399 spv::MemorySemanticsImageMemoryMask |
6400 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006401 return 0;
6402 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07006403 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6404 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006405 return 0;
6406 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006407 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6408 spv::MemorySemanticsWorkgroupMemoryMask |
6409 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006410 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07006411 case glslang::EOpSubgroupBarrier:
6412 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6413 spv::MemorySemanticsAcquireReleaseMask);
6414 return spv::NoResult;
6415 case glslang::EOpSubgroupMemoryBarrier:
6416 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6417 spv::MemorySemanticsAcquireReleaseMask);
6418 return spv::NoResult;
6419 case glslang::EOpSubgroupMemoryBarrierBuffer:
6420 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
6421 spv::MemorySemanticsAcquireReleaseMask);
6422 return spv::NoResult;
6423 case glslang::EOpSubgroupMemoryBarrierImage:
6424 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
6425 spv::MemorySemanticsAcquireReleaseMask);
6426 return spv::NoResult;
6427 case glslang::EOpSubgroupMemoryBarrierShared:
6428 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6429 spv::MemorySemanticsAcquireReleaseMask);
6430 return spv::NoResult;
6431 case glslang::EOpSubgroupElect: {
6432 std::vector<spv::Id> operands;
6433 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
6434 }
Rex Xu9d93a232016-05-05 12:30:44 +08006435#ifdef AMD_EXTENSIONS
6436 case glslang::EOpTime:
6437 {
6438 std::vector<spv::Id> args; // Dummy arguments
6439 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
6440 return builder.setPrecision(id, precision);
6441 }
6442#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006443 default:
Lei Zhang17535f72016-05-04 15:55:59 -04006444 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06006445 return 0;
6446 }
6447}
6448
6449spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
6450{
John Kessenich2f273362015-07-18 22:34:27 -06006451 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06006452 spv::Id id;
6453 if (symbolValues.end() != iter) {
6454 id = iter->second;
6455 return id;
6456 }
6457
6458 // it was not found, create it
6459 id = createSpvVariable(symbol);
6460 symbolValues[symbol->getId()] = id;
6461
Rex Xuc884b4a2016-06-29 15:03:44 +08006462 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006463 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
6464 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
6465 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07006466 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07006467 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06006468 if (symbol->getQualifier().hasIndex())
6469 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
6470 if (symbol->getQualifier().hasComponent())
6471 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06006472 // atomic counters use this:
6473 if (symbol->getQualifier().hasOffset())
6474 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006475 }
6476
scygan2c864272016-05-18 18:09:17 +02006477 if (symbol->getQualifier().hasLocation())
6478 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07006479 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07006480 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07006481 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06006482 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07006483 }
John Kessenich140f3df2015-06-26 16:58:36 -06006484 if (symbol->getQualifier().hasSet())
6485 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07006486 else if (IsDescriptorResource(symbol->getType())) {
6487 // default to 0
6488 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
6489 }
John Kessenich140f3df2015-06-26 16:58:36 -06006490 if (symbol->getQualifier().hasBinding())
6491 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07006492 if (symbol->getQualifier().hasAttachment())
6493 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06006494 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07006495 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06006496 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06006497 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07006498 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06006499 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07006500 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
6501 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
6502 builder.addDecoration(id, spv::DecorationXfbStride, stride);
6503 }
6504 if (symbol->getQualifier().hasXfbOffset())
6505 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006506 }
6507
Rex Xu1da878f2016-02-21 20:59:01 +08006508 if (symbol->getType().isImage()) {
6509 std::vector<spv::Decoration> memory;
6510 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
6511 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07006512 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08006513 }
6514
John Kessenich140f3df2015-06-26 16:58:36 -06006515 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06006516 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06006517 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07006518 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06006519
John Kessenich5611c6d2018-04-05 11:25:02 -06006520 // nonuniform
6521 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
6522
John Kessenichecba76f2017-01-06 00:34:48 -07006523#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08006524 if (builtIn == spv::BuiltInSampleMask) {
6525 spv::Decoration decoration;
6526 // GL_NV_sample_mask_override_coverage extension
6527 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08006528 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08006529 else
6530 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07006531 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08006532 if (decoration != spv::DecorationMax) {
6533 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
6534 }
6535 }
chaoc771d89f2017-01-13 01:10:53 -08006536 else if (builtIn == spv::BuiltInLayer) {
6537 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06006538 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006539 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08006540 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
6541 builder.addExtension(spv::E_SPV_NV_viewport_array2);
6542 }
John Kessenichb41bff62017-08-11 13:07:17 -06006543 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006544 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
6545 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08006546 builder.addCapability(spv::CapabilityShaderStereoViewNV);
6547 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
6548 }
6549 }
6550
chaoc6e5acae2016-12-20 13:28:52 -08006551 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006552 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08006553 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08006554 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
6555 }
chaoc0ad6a4e2016-12-19 16:29:34 -08006556#endif
6557
John Kessenich5d610ee2018-03-07 18:05:55 -07006558 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
6559 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
6560 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
6561 symbol->getType().getQualifier().semanticName);
6562 }
6563
John Kessenich140f3df2015-06-26 16:58:36 -06006564 return id;
6565}
6566
John Kessenich55e7d112015-11-15 21:33:39 -07006567// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07006568// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07006569//
6570// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
6571//
6572// Recursively walk the nodes. The nodes form a tree whose leaves are
6573// regular constants, which themselves are trees that createSpvConstant()
6574// recursively walks. So, this function walks the "top" of the tree:
6575// - emit specialization constant-building instructions for specConstant
6576// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04006577spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07006578{
John Kessenich7cc0e282016-03-20 00:46:02 -06006579 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07006580
qining4f4bb812016-04-03 23:55:17 -04006581 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07006582 if (! node.getQualifier().specConstant) {
6583 // hand off to the non-spec-constant path
6584 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
6585 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04006586 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07006587 nextConst, false);
6588 }
6589
6590 // We now know we have a specialization constant to build
6591
John Kessenichd94c0032016-05-30 19:29:40 -06006592 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04006593 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
6594 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
6595 std::vector<spv::Id> dimConstId;
6596 for (int dim = 0; dim < 3; ++dim) {
6597 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
6598 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07006599 if (specConst) {
6600 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
6601 glslangIntermediate->getLocalSizeSpecId(dim));
6602 }
qining4f4bb812016-04-03 23:55:17 -04006603 }
6604 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
6605 }
6606
6607 // An AST node labelled as specialization constant should be a symbol node.
6608 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
6609 if (auto* sn = node.getAsSymbolNode()) {
6610 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04006611 // Traverse the constant constructor sub tree like generating normal run-time instructions.
6612 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
6613 // will set the builder into spec constant op instruction generating mode.
6614 sub_tree->traverse(this);
6615 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04006616 } else if (auto* const_union_array = &sn->getConstArray()){
6617 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01006618 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
6619 builder.addName(id, sn->getName().c_str());
6620 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07006621 }
6622 }
qining4f4bb812016-04-03 23:55:17 -04006623
6624 // Neither a front-end constant node, nor a specialization constant node with constant union array or
6625 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04006626 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04006627 exit(1);
6628 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07006629}
6630
John Kessenich140f3df2015-06-26 16:58:36 -06006631// Use 'consts' as the flattened glslang source of scalar constants to recursively
6632// build the aggregate SPIR-V constant.
6633//
6634// If there are not enough elements present in 'consts', 0 will be substituted;
6635// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
6636//
qining08408382016-03-21 09:51:37 -04006637spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06006638{
6639 // vector of constants for SPIR-V
6640 std::vector<spv::Id> spvConsts;
6641
6642 // Type is used for struct and array constants
6643 spv::Id typeId = convertGlslangToSpvType(glslangType);
6644
6645 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006646 glslang::TType elementType(glslangType, 0);
6647 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04006648 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006649 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006650 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06006651 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04006652 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006653 } else if (glslangType.getStruct()) {
6654 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
6655 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04006656 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06006657 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06006658 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
6659 bool zero = nextConst >= consts.size();
6660 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006661 case glslang::EbtInt8:
6662 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
6663 break;
6664 case glslang::EbtUint8:
6665 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
6666 break;
6667 case glslang::EbtInt16:
6668 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
6669 break;
6670 case glslang::EbtUint16:
6671 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
6672 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006673 case glslang::EbtInt:
6674 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
6675 break;
6676 case glslang::EbtUint:
6677 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
6678 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006679 case glslang::EbtInt64:
6680 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
6681 break;
6682 case glslang::EbtUint64:
6683 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
6684 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006685 case glslang::EbtFloat:
6686 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
6687 break;
6688 case glslang::EbtDouble:
6689 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
6690 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006691 case glslang::EbtFloat16:
6692 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
6693 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006694 case glslang::EbtBool:
6695 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
6696 break;
6697 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006698 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06006699 break;
6700 }
6701 ++nextConst;
6702 }
6703 } else {
6704 // we have a non-aggregate (scalar) constant
6705 bool zero = nextConst >= consts.size();
6706 spv::Id scalar = 0;
6707 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006708 case glslang::EbtInt8:
6709 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
6710 break;
6711 case glslang::EbtUint8:
6712 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
6713 break;
6714 case glslang::EbtInt16:
6715 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
6716 break;
6717 case glslang::EbtUint16:
6718 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
6719 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006720 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07006721 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006722 break;
6723 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07006724 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006725 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006726 case glslang::EbtInt64:
6727 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
6728 break;
6729 case glslang::EbtUint64:
6730 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
6731 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006732 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07006733 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006734 break;
6735 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07006736 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006737 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006738 case glslang::EbtFloat16:
6739 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
6740 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006741 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07006742 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006743 break;
6744 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006745 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06006746 break;
6747 }
6748 ++nextConst;
6749 return scalar;
6750 }
6751
6752 return builder.makeCompositeConstant(typeId, spvConsts);
6753}
6754
John Kessenich7c1aa102015-10-15 13:29:11 -06006755// Return true if the node is a constant or symbol whose reading has no
6756// non-trivial observable cost or effect.
6757bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
6758{
6759 // don't know what this is
6760 if (node == nullptr)
6761 return false;
6762
6763 // a constant is safe
6764 if (node->getAsConstantUnion() != nullptr)
6765 return true;
6766
6767 // not a symbol means non-trivial
6768 if (node->getAsSymbolNode() == nullptr)
6769 return false;
6770
6771 // a symbol, depends on what's being read
6772 switch (node->getType().getQualifier().storage) {
6773 case glslang::EvqTemporary:
6774 case glslang::EvqGlobal:
6775 case glslang::EvqIn:
6776 case glslang::EvqInOut:
6777 case glslang::EvqConst:
6778 case glslang::EvqConstReadOnly:
6779 case glslang::EvqUniform:
6780 return true;
6781 default:
6782 return false;
6783 }
qining25262b32016-05-06 17:25:16 -04006784}
John Kessenich7c1aa102015-10-15 13:29:11 -06006785
6786// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06006787// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06006788// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06006789// Return true if trivial.
6790bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
6791{
6792 if (node == nullptr)
6793 return false;
6794
John Kessenich84cc15f2017-05-24 16:44:47 -06006795 // count non scalars as trivial, as well as anything coming from HLSL
6796 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06006797 return true;
6798
John Kessenich7c1aa102015-10-15 13:29:11 -06006799 // symbols and constants are trivial
6800 if (isTrivialLeaf(node))
6801 return true;
6802
6803 // otherwise, it needs to be a simple operation or one or two leaf nodes
6804
6805 // not a simple operation
6806 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
6807 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
6808 if (binaryNode == nullptr && unaryNode == nullptr)
6809 return false;
6810
6811 // not on leaf nodes
6812 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
6813 return false;
6814
6815 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
6816 return false;
6817 }
6818
6819 switch (node->getAsOperator()->getOp()) {
6820 case glslang::EOpLogicalNot:
6821 case glslang::EOpConvIntToBool:
6822 case glslang::EOpConvUintToBool:
6823 case glslang::EOpConvFloatToBool:
6824 case glslang::EOpConvDoubleToBool:
6825 case glslang::EOpEqual:
6826 case glslang::EOpNotEqual:
6827 case glslang::EOpLessThan:
6828 case glslang::EOpGreaterThan:
6829 case glslang::EOpLessThanEqual:
6830 case glslang::EOpGreaterThanEqual:
6831 case glslang::EOpIndexDirect:
6832 case glslang::EOpIndexDirectStruct:
6833 case glslang::EOpLogicalXor:
6834 case glslang::EOpAny:
6835 case glslang::EOpAll:
6836 return true;
6837 default:
6838 return false;
6839 }
6840}
6841
6842// Emit short-circuiting code, where 'right' is never evaluated unless
6843// the left side is true (for &&) or false (for ||).
6844spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
6845{
6846 spv::Id boolTypeId = builder.makeBoolType();
6847
6848 // emit left operand
6849 builder.clearAccessChain();
6850 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006851 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006852
6853 // Operands to accumulate OpPhi operands
6854 std::vector<spv::Id> phiOperands;
6855 // accumulate left operand's phi information
6856 phiOperands.push_back(leftId);
6857 phiOperands.push_back(builder.getBuildPoint()->getId());
6858
6859 // Make the two kinds of operation symmetric with a "!"
6860 // || => emit "if (! left) result = right"
6861 // && => emit "if ( left) result = right"
6862 //
6863 // TODO: this runtime "not" for || could be avoided by adding functionality
6864 // to 'builder' to have an "else" without an "then"
6865 if (op == glslang::EOpLogicalOr)
6866 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
6867
6868 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08006869 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06006870
6871 // emit right operand as the "then" part of the "if"
6872 builder.clearAccessChain();
6873 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006874 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006875
6876 // accumulate left operand's phi information
6877 phiOperands.push_back(rightId);
6878 phiOperands.push_back(builder.getBuildPoint()->getId());
6879
6880 // finish the "if"
6881 ifBuilder.makeEndIf();
6882
6883 // phi together the two results
6884 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
6885}
6886
Frank Henigman541f7bb2018-01-16 00:18:26 -05006887#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08006888// Return type Id of the imported set of extended instructions corresponds to the name.
6889// Import this set if it has not been imported yet.
6890spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
6891{
6892 if (extBuiltinMap.find(name) != extBuiltinMap.end())
6893 return extBuiltinMap[name];
6894 else {
Rex Xu51596642016-09-21 18:56:12 +08006895 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08006896 spv::Id extBuiltins = builder.import(name);
6897 extBuiltinMap[name] = extBuiltins;
6898 return extBuiltins;
6899 }
6900}
Frank Henigman541f7bb2018-01-16 00:18:26 -05006901#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006902
John Kessenich140f3df2015-06-26 16:58:36 -06006903}; // end anonymous namespace
6904
6905namespace glslang {
6906
John Kessenich68d78fd2015-07-12 19:28:10 -06006907void GetSpirvVersion(std::string& version)
6908{
John Kessenich9e55f632015-07-15 10:03:39 -06006909 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06006910 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07006911 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06006912 version = buf;
6913}
6914
John Kessenicha372a3e2017-11-02 22:32:14 -06006915// For low-order part of the generator's magic number. Bump up
6916// when there is a change in the style (e.g., if SSA form changes,
6917// or a different instruction sequence to do something gets used).
6918int GetSpirvGeneratorVersion()
6919{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07006920 // return 1; // start
6921 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07006922 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07006923 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07006924 // return 5; // make OpArrayLength result type be an int with signedness of 0
6925 return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
6926 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenicha372a3e2017-11-02 22:32:14 -06006927}
6928
John Kessenich140f3df2015-06-26 16:58:36 -06006929// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006930void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06006931{
6932 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06006933 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006934 if (out.fail())
6935 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06006936 for (int i = 0; i < (int)spirv.size(); ++i) {
6937 unsigned int word = spirv[i];
6938 out.write((const char*)&word, 4);
6939 }
6940 out.close();
6941}
6942
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006943// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08006944void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006945{
6946 std::ofstream out;
6947 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006948 if (out.fail())
6949 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07006950 out << "\t// " <<
6951 glslang::GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
6952 std::endl;
Flavio15017db2017-02-15 14:29:33 -08006953 if (varName != nullptr) {
6954 out << "\t #pragma once" << std::endl;
6955 out << "const uint32_t " << varName << "[] = {" << std::endl;
6956 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006957 const int WORDS_PER_LINE = 8;
6958 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
6959 out << "\t";
6960 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
6961 const unsigned int word = spirv[i + j];
6962 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
6963 if (i + j + 1 < (int)spirv.size()) {
6964 out << ",";
6965 }
6966 }
6967 out << std::endl;
6968 }
Flavio15017db2017-02-15 14:29:33 -08006969 if (varName != nullptr) {
6970 out << "};";
6971 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006972 out.close();
6973}
6974
John Kessenich140f3df2015-06-26 16:58:36 -06006975//
6976// Set up the glslang traversal
6977//
John Kessenich121853f2017-05-31 17:11:16 -06006978void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06006979{
Lei Zhang17535f72016-05-04 15:55:59 -04006980 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06006981 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04006982}
6983
John Kessenich121853f2017-05-31 17:11:16 -06006984void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
6985 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04006986{
John Kessenich140f3df2015-06-26 16:58:36 -06006987 TIntermNode* root = intermediate.getTreeRoot();
6988
6989 if (root == 0)
6990 return;
6991
John Kessenich121853f2017-05-31 17:11:16 -06006992 glslang::SpvOptions defaultOptions;
6993 if (options == nullptr)
6994 options = &defaultOptions;
6995
John Kessenich140f3df2015-06-26 16:58:36 -06006996 glslang::GetThreadPoolAllocator().push();
6997
John Kessenich2b5ea9f2018-01-31 18:35:56 -07006998 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06006999 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07007000 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06007001 it.dumpSpv(spirv);
7002
GregFfb03a552018-03-29 11:49:14 -06007003#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06007004 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
7005 // eg. forward and remove memory writes of opaque types.
7006 if ((intermediate.getSource() == EShSourceHlsl ||
7007 options->optimizeSize) &&
7008 !options->disableOptimizer) {
7009 spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
7010
7011 spvtools::Optimizer optimizer(target_env);
7012 optimizer.SetMessageConsumer([](spv_message_level_t level,
7013 const char* source,
7014 const spv_position_t& position,
7015 const char* message) {
7016 std::cerr << StringifyMessage(level, source, position, message)
7017 << std::endl;
7018 });
7019
GregFeecb8742018-03-26 12:11:55 -06007020 optimizer.RegisterPass(CreateMergeReturnPass());
GregFcd1f1692017-09-21 18:40:22 -06007021 optimizer.RegisterPass(CreateInlineExhaustivePass());
GregFe0639282017-12-21 10:55:57 -07007022 optimizer.RegisterPass(CreateEliminateDeadFunctionsPass());
7023 optimizer.RegisterPass(CreateScalarReplacementPass());
GregFcd1f1692017-09-21 18:40:22 -06007024 optimizer.RegisterPass(CreateLocalAccessChainConvertPass());
7025 optimizer.RegisterPass(CreateLocalSingleBlockLoadStoreElimPass());
7026 optimizer.RegisterPass(CreateLocalSingleStoreElimPass());
GregFeecb8742018-03-26 12:11:55 -06007027 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFcd1f1692017-09-21 18:40:22 -06007028 optimizer.RegisterPass(CreateInsertExtractElimPass());
GregF8a4848f2018-02-07 16:04:42 -07007029 optimizer.RegisterPass(CreateDeadInsertElimPass());
GregFcd1f1692017-09-21 18:40:22 -06007030 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFeecb8742018-03-26 12:11:55 -06007031 optimizer.RegisterPass(CreateCCPPass());
7032 optimizer.RegisterPass(CreateSimplificationPass());
GregFcd1f1692017-09-21 18:40:22 -06007033 optimizer.RegisterPass(CreateDeadBranchElimPass());
GregFcc80d802017-10-23 16:48:42 -06007034 optimizer.RegisterPass(CreateCFGCleanupPass());
GregFcd1f1692017-09-21 18:40:22 -06007035 optimizer.RegisterPass(CreateBlockMergePass());
7036 optimizer.RegisterPass(CreateLocalMultiStoreElimPass());
GregFeecb8742018-03-26 12:11:55 -06007037 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFcd1f1692017-09-21 18:40:22 -06007038 optimizer.RegisterPass(CreateInsertExtractElimPass());
GregF8a4848f2018-02-07 16:04:42 -07007039 optimizer.RegisterPass(CreateDeadInsertElimPass());
7040 if (options->optimizeSize) {
7041 optimizer.RegisterPass(CreateRedundancyEliminationPass());
7042 // TODO(greg-lunarg): Add this when AMD driver issues are resolved
7043 // optimizer.RegisterPass(CreateCommonUniformElimPass());
7044 }
GregFcd1f1692017-09-21 18:40:22 -06007045 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFcd1f1692017-09-21 18:40:22 -06007046
7047 if (!optimizer.Run(spirv.data(), spirv.size(), &spirv))
7048 return;
GregFcd1f1692017-09-21 18:40:22 -06007049 }
7050#endif
7051
John Kessenich140f3df2015-06-26 16:58:36 -06007052 glslang::GetThreadPoolAllocator().pop();
7053}
7054
7055}; // end namespace glslang