blob: 1434cbacc77c8cfb0038719355e3e38c091ca558 [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 Kessenichd41993d2017-09-10 15:21:05 -0600173 bool writableParam(glslang::TStorageQualifier);
174 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);
1282 if (counterId != spv::NoResult)
1283 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
1284 }
1285 }
1286 }
1287 }
1288 }
1289 }
John Kessenich140f3df2015-06-26 16:58:36 -06001290}
1291
1292bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1293{
John Kesseniche485c7a2017-05-31 18:50:53 -06001294 builder.setLine(node->getLoc().line);
1295
qining40887662016-04-03 22:20:42 -04001296 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1297 if (node->getType().getQualifier().isSpecConstant())
1298 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1299
John Kessenich140f3df2015-06-26 16:58:36 -06001300 // First, handle special cases
1301 switch (node->getOp()) {
1302 case glslang::EOpAssign:
1303 case glslang::EOpAddAssign:
1304 case glslang::EOpSubAssign:
1305 case glslang::EOpMulAssign:
1306 case glslang::EOpVectorTimesMatrixAssign:
1307 case glslang::EOpVectorTimesScalarAssign:
1308 case glslang::EOpMatrixTimesScalarAssign:
1309 case glslang::EOpMatrixTimesMatrixAssign:
1310 case glslang::EOpDivAssign:
1311 case glslang::EOpModAssign:
1312 case glslang::EOpAndAssign:
1313 case glslang::EOpInclusiveOrAssign:
1314 case glslang::EOpExclusiveOrAssign:
1315 case glslang::EOpLeftShiftAssign:
1316 case glslang::EOpRightShiftAssign:
1317 // A bin-op assign "a += b" means the same thing as "a = a + b"
1318 // where a is evaluated before b. For a simple assignment, GLSL
1319 // says to evaluate the left before the right. So, always, left
1320 // node then right node.
1321 {
1322 // get the left l-value, save it away
1323 builder.clearAccessChain();
1324 node->getLeft()->traverse(this);
1325 spv::Builder::AccessChain lValue = builder.getAccessChain();
1326
1327 // evaluate the right
1328 builder.clearAccessChain();
1329 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001330 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001331
1332 if (node->getOp() != glslang::EOpAssign) {
1333 // the left is also an r-value
1334 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001335 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001336
1337 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001338 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001339 TranslateNoContractionDecoration(node->getType().getQualifier()),
1340 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001341 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001342 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1343 node->getType().getBasicType());
1344
1345 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001346 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001347 }
1348
1349 // store the result
1350 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001351 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001352
1353 // assignments are expressions having an rValue after they are evaluated...
1354 builder.clearAccessChain();
1355 builder.setAccessChainRValue(rValue);
1356 }
1357 return false;
1358 case glslang::EOpIndexDirect:
1359 case glslang::EOpIndexDirectStruct:
1360 {
1361 // Get the left part of the access chain.
1362 node->getLeft()->traverse(this);
1363
1364 // Add the next element in the chain
1365
David Netoa901ffe2016-06-08 14:11:40 +01001366 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001367 if (! node->getLeft()->getType().isArray() &&
1368 node->getLeft()->getType().isVector() &&
1369 node->getOp() == glslang::EOpIndexDirect) {
1370 // This is essentially a hard-coded vector swizzle of size 1,
1371 // so short circuit the access-chain stuff with a swizzle.
1372 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001373 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001374 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001375 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001376 int spvIndex = glslangIndex;
1377 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1378 node->getOp() == glslang::EOpIndexDirectStruct)
1379 {
1380 // This may be, e.g., an anonymous block-member selection, which generally need
1381 // index remapping due to hidden members in anonymous blocks.
1382 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1383 assert(remapper.size() > 0);
1384 spvIndex = remapper[glslangIndex];
1385 }
John Kessenichebb50532016-05-16 19:22:05 -06001386
David Netoa901ffe2016-06-08 14:11:40 +01001387 // normal case for indexing array or structure or block
1388 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1389
1390 // Add capabilities here for accessing PointSize and clip/cull distance.
1391 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001392 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001393 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001394 }
1395 }
1396 return false;
1397 case glslang::EOpIndexIndirect:
1398 {
1399 // Structure or array or vector indirection.
1400 // Will use native SPIR-V access-chain for struct and array indirection;
1401 // matrices are arrays of vectors, so will also work for a matrix.
1402 // Will use the access chain's 'component' for variable index into a vector.
1403
1404 // This adapter is building access chains left to right.
1405 // Set up the access chain to the left.
1406 node->getLeft()->traverse(this);
1407
1408 // save it so that computing the right side doesn't trash it
1409 spv::Builder::AccessChain partial = builder.getAccessChain();
1410
1411 // compute the next index in the chain
1412 builder.clearAccessChain();
1413 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001414 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001415
John Kessenich5611c6d2018-04-05 11:25:02 -06001416 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1417
John Kessenich140f3df2015-06-26 16:58:36 -06001418 // restore the saved access chain
1419 builder.setAccessChain(partial);
1420
1421 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001422 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001423 else
John Kessenichfa668da2015-09-13 14:46:30 -06001424 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001425 }
1426 return false;
1427 case glslang::EOpVectorSwizzle:
1428 {
1429 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001430 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001431 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001432 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001433 }
1434 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001435 case glslang::EOpMatrixSwizzle:
1436 logger->missingFunctionality("matrix swizzle");
1437 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001438 case glslang::EOpLogicalOr:
1439 case glslang::EOpLogicalAnd:
1440 {
1441
1442 // These may require short circuiting, but can sometimes be done as straight
1443 // binary operations. The right operand must be short circuited if it has
1444 // side effects, and should probably be if it is complex.
1445 if (isTrivial(node->getRight()->getAsTyped()))
1446 break; // handle below as a normal binary operation
1447 // otherwise, we need to do dynamic short circuiting on the right operand
1448 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1449 builder.clearAccessChain();
1450 builder.setAccessChainRValue(result);
1451 }
1452 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001453 default:
1454 break;
1455 }
1456
1457 // Assume generic binary op...
1458
John Kessenich32cfd492016-02-02 12:37:46 -07001459 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001460 builder.clearAccessChain();
1461 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001462 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001463
John Kessenich32cfd492016-02-02 12:37:46 -07001464 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001465 builder.clearAccessChain();
1466 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001467 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001468
John Kessenich32cfd492016-02-02 12:37:46 -07001469 // get result
John Kessenichead86222018-03-28 18:01:20 -06001470 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001471 TranslateNoContractionDecoration(node->getType().getQualifier()),
1472 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001473 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001474 convertGlslangToSpvType(node->getType()), left, right,
1475 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001476
John Kessenich50e57562015-12-21 21:21:11 -07001477 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001478 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001479 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001480 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001481 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001482 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001483 return false;
1484 }
John Kessenich140f3df2015-06-26 16:58:36 -06001485}
1486
1487bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1488{
John Kesseniche485c7a2017-05-31 18:50:53 -06001489 builder.setLine(node->getLoc().line);
1490
qining40887662016-04-03 22:20:42 -04001491 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1492 if (node->getType().getQualifier().isSpecConstant())
1493 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1494
John Kessenichfc51d282015-08-19 13:34:18 -06001495 spv::Id result = spv::NoResult;
1496
1497 // try texturing first
1498 result = createImageTextureFunctionCall(node);
1499 if (result != spv::NoResult) {
1500 builder.clearAccessChain();
1501 builder.setAccessChainRValue(result);
1502
1503 return false; // done with this node
1504 }
1505
1506 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001507
1508 if (node->getOp() == glslang::EOpArrayLength) {
1509 // Quite special; won't want to evaluate the operand.
1510
John Kessenich5611c6d2018-04-05 11:25:02 -06001511 // Currently, the front-end does not allow .length() on an array until it is sized,
1512 // except for the last block membeor of an SSBO.
1513 // TODO: If this changes, link-time sized arrays might show up here, and need their
1514 // size extracted.
1515
John Kessenichc9a80832015-09-12 12:17:44 -06001516 // Normal .length() would have been constant folded by the front-end.
1517 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001518 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001519
John Kessenichc9a80832015-09-12 12:17:44 -06001520 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1521 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001522 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1523 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001524
1525 builder.clearAccessChain();
1526 builder.setAccessChainRValue(length);
1527
1528 return false;
1529 }
1530
John Kessenichfc51d282015-08-19 13:34:18 -06001531 // Start by evaluating the operand
1532
John Kessenich8c8505c2016-07-26 12:50:38 -06001533 // Does it need a swizzle inversion? If so, evaluation is inverted;
1534 // operate first on the swizzle base, then apply the swizzle.
1535 spv::Id invertedType = spv::NoType;
1536 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1537 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1538 invertedType = getInvertedSwizzleType(*node->getOperand());
1539
John Kessenich140f3df2015-06-26 16:58:36 -06001540 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001541 if (invertedType != spv::NoType)
1542 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1543 else
1544 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001545
Rex Xufc618912015-09-09 16:42:49 +08001546 spv::Id operand = spv::NoResult;
1547
1548 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1549 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001550 node->getOp() == glslang::EOpAtomicCounter ||
1551 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001552 operand = builder.accessChainGetLValue(); // Special case l-value operands
1553 else
John Kessenich32cfd492016-02-02 12:37:46 -07001554 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001555
John Kessenichead86222018-03-28 18:01:20 -06001556 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001557 TranslateNoContractionDecoration(node->getType().getQualifier()),
1558 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001559
1560 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001561 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001562 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001563
1564 // if not, then possibly an operation
1565 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001566 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001567
1568 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001569 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001570 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001571 builder.addDecoration(result, decorations.nonUniform);
1572 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001573
John Kessenich140f3df2015-06-26 16:58:36 -06001574 builder.clearAccessChain();
1575 builder.setAccessChainRValue(result);
1576
1577 return false; // done with this node
1578 }
1579
1580 // it must be a special case, check...
1581 switch (node->getOp()) {
1582 case glslang::EOpPostIncrement:
1583 case glslang::EOpPostDecrement:
1584 case glslang::EOpPreIncrement:
1585 case glslang::EOpPreDecrement:
1586 {
1587 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001588 spv::Id one = 0;
1589 if (node->getBasicType() == glslang::EbtFloat)
1590 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001591 else if (node->getBasicType() == glslang::EbtDouble)
1592 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001593 else if (node->getBasicType() == glslang::EbtFloat16)
1594 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001595 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1596 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001597 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1598 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001599 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1600 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001601 else
1602 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001603 glslang::TOperator op;
1604 if (node->getOp() == glslang::EOpPreIncrement ||
1605 node->getOp() == glslang::EOpPostIncrement)
1606 op = glslang::EOpAdd;
1607 else
1608 op = glslang::EOpSub;
1609
John Kessenichead86222018-03-28 18:01:20 -06001610 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001611 convertGlslangToSpvType(node->getType()), operand, one,
1612 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001613 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001614
1615 // The result of operation is always stored, but conditionally the
1616 // consumed result. The consumed result is always an r-value.
1617 builder.accessChainStore(result);
1618 builder.clearAccessChain();
1619 if (node->getOp() == glslang::EOpPreIncrement ||
1620 node->getOp() == glslang::EOpPreDecrement)
1621 builder.setAccessChainRValue(result);
1622 else
1623 builder.setAccessChainRValue(operand);
1624 }
1625
1626 return false;
1627
1628 case glslang::EOpEmitStreamVertex:
1629 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1630 return false;
1631 case glslang::EOpEndStreamPrimitive:
1632 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1633 return false;
1634
1635 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001636 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001637 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001638 }
John Kessenich140f3df2015-06-26 16:58:36 -06001639}
1640
1641bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1642{
qining27e04a02016-04-14 16:40:20 -04001643 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1644 if (node->getType().getQualifier().isSpecConstant())
1645 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1646
John Kessenichfc51d282015-08-19 13:34:18 -06001647 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001648 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1649 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001650
1651 // try texturing
1652 result = createImageTextureFunctionCall(node);
1653 if (result != spv::NoResult) {
1654 builder.clearAccessChain();
1655 builder.setAccessChainRValue(result);
1656
1657 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001658#ifdef AMD_EXTENSIONS
1659 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1660#else
John Kessenich56bab042015-09-16 10:54:31 -06001661 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001662#endif
Rex Xufc618912015-09-09 16:42:49 +08001663 // "imageStore" is a special case, which has no result
1664 return false;
1665 }
John Kessenichfc51d282015-08-19 13:34:18 -06001666
John Kessenich140f3df2015-06-26 16:58:36 -06001667 glslang::TOperator binOp = glslang::EOpNull;
1668 bool reduceComparison = true;
1669 bool isMatrix = false;
1670 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001671 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001672
1673 assert(node->getOp());
1674
John Kessenichf6640762016-08-01 19:44:00 -06001675 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001676
1677 switch (node->getOp()) {
1678 case glslang::EOpSequence:
1679 {
1680 if (preVisit)
1681 ++sequenceDepth;
1682 else
1683 --sequenceDepth;
1684
1685 if (sequenceDepth == 1) {
1686 // If this is the parent node of all the functions, we want to see them
1687 // early, so all call points have actual SPIR-V functions to reference.
1688 // In all cases, still let the traverser visit the children for us.
1689 makeFunctions(node->getAsAggregate()->getSequence());
1690
John Kessenich6fccb3c2016-09-19 16:01:41 -06001691 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001692 // anything else gets there, so visit out of order, doing them all now.
1693 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1694
John Kessenich6a60c2f2016-12-08 21:01:59 -07001695 // 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 -06001696 // so do them manually.
1697 visitFunctions(node->getAsAggregate()->getSequence());
1698
1699 return false;
1700 }
1701
1702 return true;
1703 }
1704 case glslang::EOpLinkerObjects:
1705 {
1706 if (visit == glslang::EvPreVisit)
1707 linkageOnly = true;
1708 else
1709 linkageOnly = false;
1710
1711 return true;
1712 }
1713 case glslang::EOpComma:
1714 {
1715 // processing from left to right naturally leaves the right-most
1716 // lying around in the access chain
1717 glslang::TIntermSequence& glslangOperands = node->getSequence();
1718 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1719 glslangOperands[i]->traverse(this);
1720
1721 return false;
1722 }
1723 case glslang::EOpFunction:
1724 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001725 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001726 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001727 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001728 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001729 } else {
1730 handleFunctionEntry(node);
1731 }
1732 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001733 if (inEntryPoint)
1734 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001735 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001736 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001737 }
1738
1739 return true;
1740 case glslang::EOpParameters:
1741 // Parameters will have been consumed by EOpFunction processing, but not
1742 // the body, so we still visited the function node's children, making this
1743 // child redundant.
1744 return false;
1745 case glslang::EOpFunctionCall:
1746 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001747 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001748 if (node->isUserDefined())
1749 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001750 // 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 -07001751 if (result) {
1752 builder.clearAccessChain();
1753 builder.setAccessChainRValue(result);
1754 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001755 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001756
1757 return false;
1758 }
1759 case glslang::EOpConstructMat2x2:
1760 case glslang::EOpConstructMat2x3:
1761 case glslang::EOpConstructMat2x4:
1762 case glslang::EOpConstructMat3x2:
1763 case glslang::EOpConstructMat3x3:
1764 case glslang::EOpConstructMat3x4:
1765 case glslang::EOpConstructMat4x2:
1766 case glslang::EOpConstructMat4x3:
1767 case glslang::EOpConstructMat4x4:
1768 case glslang::EOpConstructDMat2x2:
1769 case glslang::EOpConstructDMat2x3:
1770 case glslang::EOpConstructDMat2x4:
1771 case glslang::EOpConstructDMat3x2:
1772 case glslang::EOpConstructDMat3x3:
1773 case glslang::EOpConstructDMat3x4:
1774 case glslang::EOpConstructDMat4x2:
1775 case glslang::EOpConstructDMat4x3:
1776 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001777 case glslang::EOpConstructIMat2x2:
1778 case glslang::EOpConstructIMat2x3:
1779 case glslang::EOpConstructIMat2x4:
1780 case glslang::EOpConstructIMat3x2:
1781 case glslang::EOpConstructIMat3x3:
1782 case glslang::EOpConstructIMat3x4:
1783 case glslang::EOpConstructIMat4x2:
1784 case glslang::EOpConstructIMat4x3:
1785 case glslang::EOpConstructIMat4x4:
1786 case glslang::EOpConstructUMat2x2:
1787 case glslang::EOpConstructUMat2x3:
1788 case glslang::EOpConstructUMat2x4:
1789 case glslang::EOpConstructUMat3x2:
1790 case glslang::EOpConstructUMat3x3:
1791 case glslang::EOpConstructUMat3x4:
1792 case glslang::EOpConstructUMat4x2:
1793 case glslang::EOpConstructUMat4x3:
1794 case glslang::EOpConstructUMat4x4:
1795 case glslang::EOpConstructBMat2x2:
1796 case glslang::EOpConstructBMat2x3:
1797 case glslang::EOpConstructBMat2x4:
1798 case glslang::EOpConstructBMat3x2:
1799 case glslang::EOpConstructBMat3x3:
1800 case glslang::EOpConstructBMat3x4:
1801 case glslang::EOpConstructBMat4x2:
1802 case glslang::EOpConstructBMat4x3:
1803 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001804 case glslang::EOpConstructF16Mat2x2:
1805 case glslang::EOpConstructF16Mat2x3:
1806 case glslang::EOpConstructF16Mat2x4:
1807 case glslang::EOpConstructF16Mat3x2:
1808 case glslang::EOpConstructF16Mat3x3:
1809 case glslang::EOpConstructF16Mat3x4:
1810 case glslang::EOpConstructF16Mat4x2:
1811 case glslang::EOpConstructF16Mat4x3:
1812 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06001813 isMatrix = true;
1814 // fall through
1815 case glslang::EOpConstructFloat:
1816 case glslang::EOpConstructVec2:
1817 case glslang::EOpConstructVec3:
1818 case glslang::EOpConstructVec4:
1819 case glslang::EOpConstructDouble:
1820 case glslang::EOpConstructDVec2:
1821 case glslang::EOpConstructDVec3:
1822 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001823 case glslang::EOpConstructFloat16:
1824 case glslang::EOpConstructF16Vec2:
1825 case glslang::EOpConstructF16Vec3:
1826 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001827 case glslang::EOpConstructBool:
1828 case glslang::EOpConstructBVec2:
1829 case glslang::EOpConstructBVec3:
1830 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07001831 case glslang::EOpConstructInt8:
1832 case glslang::EOpConstructI8Vec2:
1833 case glslang::EOpConstructI8Vec3:
1834 case glslang::EOpConstructI8Vec4:
1835 case glslang::EOpConstructUint8:
1836 case glslang::EOpConstructU8Vec2:
1837 case glslang::EOpConstructU8Vec3:
1838 case glslang::EOpConstructU8Vec4:
1839 case glslang::EOpConstructInt16:
1840 case glslang::EOpConstructI16Vec2:
1841 case glslang::EOpConstructI16Vec3:
1842 case glslang::EOpConstructI16Vec4:
1843 case glslang::EOpConstructUint16:
1844 case glslang::EOpConstructU16Vec2:
1845 case glslang::EOpConstructU16Vec3:
1846 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001847 case glslang::EOpConstructInt:
1848 case glslang::EOpConstructIVec2:
1849 case glslang::EOpConstructIVec3:
1850 case glslang::EOpConstructIVec4:
1851 case glslang::EOpConstructUint:
1852 case glslang::EOpConstructUVec2:
1853 case glslang::EOpConstructUVec3:
1854 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001855 case glslang::EOpConstructInt64:
1856 case glslang::EOpConstructI64Vec2:
1857 case glslang::EOpConstructI64Vec3:
1858 case glslang::EOpConstructI64Vec4:
1859 case glslang::EOpConstructUint64:
1860 case glslang::EOpConstructU64Vec2:
1861 case glslang::EOpConstructU64Vec3:
1862 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001863 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001864 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001865 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001866 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001867 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001868 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001869 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001870 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001871 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001872 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001873 std::vector<spv::Id> constituents;
1874 for (int c = 0; c < (int)arguments.size(); ++c)
1875 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001876 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001877 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001878 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001879 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001880 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001881
1882 builder.clearAccessChain();
1883 builder.setAccessChainRValue(constructed);
1884
1885 return false;
1886 }
1887
1888 // These six are component-wise compares with component-wise results.
1889 // Forward on to createBinaryOperation(), requesting a vector result.
1890 case glslang::EOpLessThan:
1891 case glslang::EOpGreaterThan:
1892 case glslang::EOpLessThanEqual:
1893 case glslang::EOpGreaterThanEqual:
1894 case glslang::EOpVectorEqual:
1895 case glslang::EOpVectorNotEqual:
1896 {
1897 // Map the operation to a binary
1898 binOp = node->getOp();
1899 reduceComparison = false;
1900 switch (node->getOp()) {
1901 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1902 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1903 default: binOp = node->getOp(); break;
1904 }
1905
1906 break;
1907 }
1908 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001909 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001910 binOp = glslang::EOpMul;
1911 break;
1912 case glslang::EOpOuterProduct:
1913 // two vectors multiplied to make a matrix
1914 binOp = glslang::EOpOuterProduct;
1915 break;
1916 case glslang::EOpDot:
1917 {
qining25262b32016-05-06 17:25:16 -04001918 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001919 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001920 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001921 binOp = glslang::EOpMul;
1922 break;
1923 }
1924 case glslang::EOpMod:
1925 // when an aggregate, this is the floating-point mod built-in function,
1926 // which can be emitted by the one in createBinaryOperation()
1927 binOp = glslang::EOpMod;
1928 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001929 case glslang::EOpEmitVertex:
1930 case glslang::EOpEndPrimitive:
1931 case glslang::EOpBarrier:
1932 case glslang::EOpMemoryBarrier:
1933 case glslang::EOpMemoryBarrierAtomicCounter:
1934 case glslang::EOpMemoryBarrierBuffer:
1935 case glslang::EOpMemoryBarrierImage:
1936 case glslang::EOpMemoryBarrierShared:
1937 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07001938 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001939 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07001940 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001941 case glslang::EOpWorkgroupMemoryBarrier:
1942 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07001943 case glslang::EOpSubgroupBarrier:
1944 case glslang::EOpSubgroupMemoryBarrier:
1945 case glslang::EOpSubgroupMemoryBarrierBuffer:
1946 case glslang::EOpSubgroupMemoryBarrierImage:
1947 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06001948 noReturnValue = true;
1949 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1950 break;
1951
John Kessenich426394d2015-07-23 10:22:48 -06001952 case glslang::EOpAtomicAdd:
1953 case glslang::EOpAtomicMin:
1954 case glslang::EOpAtomicMax:
1955 case glslang::EOpAtomicAnd:
1956 case glslang::EOpAtomicOr:
1957 case glslang::EOpAtomicXor:
1958 case glslang::EOpAtomicExchange:
1959 case glslang::EOpAtomicCompSwap:
1960 atomic = true;
1961 break;
1962
John Kessenich0d0c6d32017-07-23 16:08:26 -06001963 case glslang::EOpAtomicCounterAdd:
1964 case glslang::EOpAtomicCounterSubtract:
1965 case glslang::EOpAtomicCounterMin:
1966 case glslang::EOpAtomicCounterMax:
1967 case glslang::EOpAtomicCounterAnd:
1968 case glslang::EOpAtomicCounterOr:
1969 case glslang::EOpAtomicCounterXor:
1970 case glslang::EOpAtomicCounterExchange:
1971 case glslang::EOpAtomicCounterCompSwap:
1972 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1973 builder.addCapability(spv::CapabilityAtomicStorageOps);
1974 atomic = true;
1975 break;
1976
John Kessenich140f3df2015-06-26 16:58:36 -06001977 default:
1978 break;
1979 }
1980
1981 //
1982 // See if it maps to a regular operation.
1983 //
John Kessenich140f3df2015-06-26 16:58:36 -06001984 if (binOp != glslang::EOpNull) {
1985 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1986 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1987 assert(left && right);
1988
1989 builder.clearAccessChain();
1990 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001991 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001992
1993 builder.clearAccessChain();
1994 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001995 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001996
John Kesseniche485c7a2017-05-31 18:50:53 -06001997 builder.setLine(node->getLoc().line);
John Kessenichead86222018-03-28 18:01:20 -06001998 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06001999 TranslateNoContractionDecoration(node->getType().getQualifier()),
2000 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002001 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002002 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002003 left->getType().getBasicType(), reduceComparison);
2004
2005 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002006 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002007 builder.clearAccessChain();
2008 builder.setAccessChainRValue(result);
2009
2010 return false;
2011 }
2012
John Kessenich426394d2015-07-23 10:22:48 -06002013 //
2014 // Create the list of operands.
2015 //
John Kessenich140f3df2015-06-26 16:58:36 -06002016 glslang::TIntermSequence& glslangOperands = node->getSequence();
2017 std::vector<spv::Id> operands;
2018 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002019 // special case l-value operands; there are just a few
2020 bool lvalue = false;
2021 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002022 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002023 case glslang::EOpModf:
2024 if (arg == 1)
2025 lvalue = true;
2026 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002027 case glslang::EOpInterpolateAtSample:
2028 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002029#ifdef AMD_EXTENSIONS
2030 case glslang::EOpInterpolateAtVertex:
2031#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002032 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002033 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002034
2035 // Does it need a swizzle inversion? If so, evaluation is inverted;
2036 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002037 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002038 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2039 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2040 }
Rex Xu7a26c172015-12-08 17:12:09 +08002041 break;
Rex Xud4782c12015-09-06 16:30:11 +08002042 case glslang::EOpAtomicAdd:
2043 case glslang::EOpAtomicMin:
2044 case glslang::EOpAtomicMax:
2045 case glslang::EOpAtomicAnd:
2046 case glslang::EOpAtomicOr:
2047 case glslang::EOpAtomicXor:
2048 case glslang::EOpAtomicExchange:
2049 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002050 case glslang::EOpAtomicCounterAdd:
2051 case glslang::EOpAtomicCounterSubtract:
2052 case glslang::EOpAtomicCounterMin:
2053 case glslang::EOpAtomicCounterMax:
2054 case glslang::EOpAtomicCounterAnd:
2055 case glslang::EOpAtomicCounterOr:
2056 case glslang::EOpAtomicCounterXor:
2057 case glslang::EOpAtomicCounterExchange:
2058 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002059 if (arg == 0)
2060 lvalue = true;
2061 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002062 case glslang::EOpAddCarry:
2063 case glslang::EOpSubBorrow:
2064 if (arg == 2)
2065 lvalue = true;
2066 break;
2067 case glslang::EOpUMulExtended:
2068 case glslang::EOpIMulExtended:
2069 if (arg >= 2)
2070 lvalue = true;
2071 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002072 default:
2073 break;
2074 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002075 builder.clearAccessChain();
2076 if (invertedType != spv::NoType && arg == 0)
2077 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2078 else
2079 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002080 if (lvalue)
2081 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002082 else {
2083 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07002084 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002085 }
John Kessenich140f3df2015-06-26 16:58:36 -06002086 }
John Kessenich426394d2015-07-23 10:22:48 -06002087
John Kesseniche485c7a2017-05-31 18:50:53 -06002088 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06002089 if (atomic) {
2090 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002091 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002092 } else {
2093 // Pass through to generic operations.
2094 switch (glslangOperands.size()) {
2095 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002096 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002097 break;
2098 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002099 {
2100 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002101 TranslateNoContractionDecoration(node->getType().getQualifier()),
2102 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002103 result = createUnaryOperation(
2104 node->getOp(), decorations,
2105 resultType(), operands.front(),
2106 glslangOperands[0]->getAsTyped()->getBasicType());
2107 }
John Kessenich426394d2015-07-23 10:22:48 -06002108 break;
2109 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002110 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002111 break;
2112 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002113 if (invertedType)
2114 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002115 }
2116
2117 if (noReturnValue)
2118 return false;
2119
2120 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002121 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002122 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002123 } else {
2124 builder.clearAccessChain();
2125 builder.setAccessChainRValue(result);
2126 return false;
2127 }
2128}
2129
John Kessenich433e9ff2017-01-26 20:31:11 -07002130// This path handles both if-then-else and ?:
2131// The if-then-else has a node type of void, while
2132// ?: has either a void or a non-void node type
2133//
2134// Leaving the result, when not void:
2135// GLSL only has r-values as the result of a :?, but
2136// if we have an l-value, that can be more efficient if it will
2137// become the base of a complex r-value expression, because the
2138// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002139bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2140{
John Kessenich4bee5312018-02-20 21:29:05 -07002141 // See if it simple and safe, or required, to execute both sides.
2142 // Crucially, side effects must be either semantically required or avoided,
2143 // and there are performance trade-offs.
2144 // Return true if required or a good idea (and safe) to execute both sides,
2145 // false otherwise.
2146 const auto bothSidesPolicy = [&]() -> bool {
2147 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002148 if (node->getTrueBlock() == nullptr ||
2149 node->getFalseBlock() == nullptr)
2150 return false;
2151
John Kessenich4bee5312018-02-20 21:29:05 -07002152 // required? (unless we write additional code to look for side effects
2153 // and make performance trade-offs if none are present)
2154 if (!node->getShortCircuit())
2155 return true;
2156
2157 // if not required to execute both, decide based on performance/practicality...
2158
2159 // see if OpSelect can handle it
2160 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2161 node->getBasicType() == glslang::EbtVoid)
2162 return false;
2163
John Kessenich433e9ff2017-01-26 20:31:11 -07002164 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2165 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2166
2167 // return true if a single operand to ? : is okay for OpSelect
2168 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002169 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002170 };
2171
2172 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2173 operandOkay(node->getFalseBlock()->getAsTyped());
2174 };
2175
John Kessenich4bee5312018-02-20 21:29:05 -07002176 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2177 // emit the condition before doing anything with selection
2178 node->getCondition()->traverse(this);
2179 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2180
2181 // Find a way of executing both sides and selecting the right result.
2182 const auto executeBothSides = [&]() -> void {
2183 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002184 node->getTrueBlock()->traverse(this);
2185 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2186 node->getFalseBlock()->traverse(this);
2187 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2188
John Kesseniche485c7a2017-05-31 18:50:53 -06002189 builder.setLine(node->getLoc().line);
2190
John Kessenich4bee5312018-02-20 21:29:05 -07002191 // done if void
2192 if (node->getBasicType() == glslang::EbtVoid)
2193 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002194
John Kessenich4bee5312018-02-20 21:29:05 -07002195 // emit code to select between trueValue and falseValue
2196
2197 // see if OpSelect can handle it
2198 if (node->getType().isScalar() || node->getType().isVector()) {
2199 // Emit OpSelect for this selection.
2200
2201 // smear condition to vector, if necessary (AST is always scalar)
2202 if (builder.isVector(trueValue))
2203 condition = builder.smearScalar(spv::NoPrecision, condition,
2204 builder.makeVectorType(builder.makeBoolType(),
2205 builder.getNumComponents(trueValue)));
2206
2207 // OpSelect
2208 result = builder.createTriOp(spv::OpSelect,
2209 convertGlslangToSpvType(node->getType()), condition,
2210 trueValue, falseValue);
2211
2212 builder.clearAccessChain();
2213 builder.setAccessChainRValue(result);
2214 } else {
2215 // We need control flow to select the result.
2216 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2217 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2218
2219 // Selection control:
2220 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2221
2222 // make an "if" based on the value created by the condition
2223 spv::Builder::If ifBuilder(condition, control, builder);
2224
2225 // emit the "then" statement
2226 builder.createStore(trueValue, result);
2227 ifBuilder.makeBeginElse();
2228 // emit the "else" statement
2229 builder.createStore(falseValue, result);
2230
2231 // finish off the control flow
2232 ifBuilder.makeEndIf();
2233
2234 builder.clearAccessChain();
2235 builder.setAccessChainLValue(result);
2236 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002237 };
2238
John Kessenich4bee5312018-02-20 21:29:05 -07002239 // Execute the one side needed, as per the condition
2240 const auto executeOneSide = [&]() {
2241 // Always emit control flow.
2242 if (node->getBasicType() != glslang::EbtVoid)
2243 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002244
John Kessenich4bee5312018-02-20 21:29:05 -07002245 // Selection control:
2246 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2247
2248 // make an "if" based on the value created by the condition
2249 spv::Builder::If ifBuilder(condition, control, builder);
2250
2251 // emit the "then" statement
2252 if (node->getTrueBlock() != nullptr) {
2253 node->getTrueBlock()->traverse(this);
2254 if (result != spv::NoResult)
2255 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2256 }
2257
2258 if (node->getFalseBlock() != nullptr) {
2259 ifBuilder.makeBeginElse();
2260 // emit the "else" statement
2261 node->getFalseBlock()->traverse(this);
2262 if (result != spv::NoResult)
2263 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2264 }
2265
2266 // finish off the control flow
2267 ifBuilder.makeEndIf();
2268
2269 if (result != spv::NoResult) {
2270 builder.clearAccessChain();
2271 builder.setAccessChainLValue(result);
2272 }
2273 };
2274
2275 // Try for OpSelect (or a requirement to execute both sides)
2276 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002277 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2278 if (node->getType().getQualifier().isSpecConstant())
2279 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002280 executeBothSides();
2281 } else
2282 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002283
2284 return false;
2285}
2286
2287bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2288{
2289 // emit and get the condition before doing anything with switch
2290 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002291 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002292
Rex Xu57e65922017-07-04 23:23:40 +08002293 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002294 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002295
John Kessenich140f3df2015-06-26 16:58:36 -06002296 // browse the children to sort out code segments
2297 int defaultSegment = -1;
2298 std::vector<TIntermNode*> codeSegments;
2299 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2300 std::vector<int> caseValues;
2301 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2302 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2303 TIntermNode* child = *c;
2304 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002305 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002306 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002307 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002308 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2309 } else
2310 codeSegments.push_back(child);
2311 }
2312
qining25262b32016-05-06 17:25:16 -04002313 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002314 // statements between the last case and the end of the switch statement
2315 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2316 (int)codeSegments.size() == defaultSegment)
2317 codeSegments.push_back(nullptr);
2318
2319 // make the switch statement
2320 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002321 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002322
2323 // emit all the code in the segments
2324 breakForLoop.push(false);
2325 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2326 builder.nextSwitchSegment(segmentBlocks, s);
2327 if (codeSegments[s])
2328 codeSegments[s]->traverse(this);
2329 else
2330 builder.addSwitchBreak();
2331 }
2332 breakForLoop.pop();
2333
2334 builder.endSwitch(segmentBlocks);
2335
2336 return false;
2337}
2338
2339void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2340{
2341 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002342 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002343
2344 builder.clearAccessChain();
2345 builder.setAccessChainRValue(constant);
2346}
2347
2348bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2349{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002350 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002351 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002352
2353 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002354 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2355 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002356
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002357 // Spec requires back edges to target header blocks, and every header block
2358 // must dominate its merge block. Make a header block first to ensure these
2359 // conditions are met. By definition, it will contain OpLoopMerge, followed
2360 // by a block-ending branch. But we don't want to put any other body/test
2361 // instructions in it, since the body/test may have arbitrary instructions,
2362 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002363 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002364 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002365 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002366 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002367 spv::Block& test = builder.makeNewBlock();
2368 builder.createBranch(&test);
2369
2370 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002371 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002372 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002373 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2374
2375 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002376 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002377 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002378 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002379 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002380 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002381
2382 builder.setBuildPoint(&blocks.continue_target);
2383 if (node->getTerminal())
2384 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002385 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002386 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002387 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002388 builder.createBranch(&blocks.body);
2389
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002390 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002391 builder.setBuildPoint(&blocks.body);
2392 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002393 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002394 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002395 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002396
2397 builder.setBuildPoint(&blocks.continue_target);
2398 if (node->getTerminal())
2399 node->getTerminal()->traverse(this);
2400 if (node->getTest()) {
2401 node->getTest()->traverse(this);
2402 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002403 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002404 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002405 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002406 // TODO: unless there was a break/return/discard instruction
2407 // somewhere in the body, this is an infinite loop, so we should
2408 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002409 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002410 }
John Kessenich140f3df2015-06-26 16:58:36 -06002411 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002412 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002413 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002414 return false;
2415}
2416
2417bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2418{
2419 if (node->getExpression())
2420 node->getExpression()->traverse(this);
2421
John Kesseniche485c7a2017-05-31 18:50:53 -06002422 builder.setLine(node->getLoc().line);
2423
John Kessenich140f3df2015-06-26 16:58:36 -06002424 switch (node->getFlowOp()) {
2425 case glslang::EOpKill:
2426 builder.makeDiscard();
2427 break;
2428 case glslang::EOpBreak:
2429 if (breakForLoop.top())
2430 builder.createLoopExit();
2431 else
2432 builder.addSwitchBreak();
2433 break;
2434 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002435 builder.createLoopContinue();
2436 break;
2437 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002438 if (node->getExpression()) {
2439 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2440 spv::Id returnId = accessChainLoad(glslangReturnType);
2441 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2442 builder.clearAccessChain();
2443 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2444 builder.setAccessChainLValue(copyId);
2445 multiTypeStore(glslangReturnType, returnId);
2446 returnId = builder.createLoad(copyId);
2447 }
2448 builder.makeReturn(false, returnId);
2449 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002450 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002451
2452 builder.clearAccessChain();
2453 break;
2454
2455 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002456 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002457 break;
2458 }
2459
2460 return false;
2461}
2462
2463spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2464{
qining25262b32016-05-06 17:25:16 -04002465 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002466 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002467 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002468 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002469 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002470 }
2471
2472 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002473 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002474 spv::Id spvType = convertGlslangToSpvType(node->getType());
2475
Rex Xucabbb782017-03-24 13:41:14 +08002476 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2477 node->getType().containsBasicType(glslang::EbtInt16) ||
2478 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002479 if (contains16BitType) {
2480 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
John Kessenich66011cb2018-03-06 16:12:04 -07002481 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002482 builder.addCapability(spv::CapabilityStorageInputOutput16);
2483 } else if (storageClass == spv::StorageClassPushConstant) {
John Kessenich66011cb2018-03-06 16:12:04 -07002484 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002485 builder.addCapability(spv::CapabilityStoragePushConstant16);
2486 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich66011cb2018-03-06 16:12:04 -07002487 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002488 builder.addCapability(spv::CapabilityStorageUniform16);
2489 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2490 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2491 }
2492 }
Rex Xuf89ad982017-04-07 23:22:33 +08002493
John Kessenich140f3df2015-06-26 16:58:36 -06002494 const char* name = node->getName().c_str();
2495 if (glslang::IsAnonymous(name))
2496 name = "";
2497
2498 return builder.createVariable(storageClass, spvType, name);
2499}
2500
2501// Return type Id of the sampled type.
2502spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2503{
2504 switch (sampler.type) {
2505 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08002506#ifdef AMD_EXTENSIONS
2507 case glslang::EbtFloat16:
2508 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
2509 builder.addCapability(spv::CapabilityFloat16ImageAMD);
2510 return builder.makeFloatType(16);
2511#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002512 case glslang::EbtInt: return builder.makeIntType(32);
2513 case glslang::EbtUint: return builder.makeUintType(32);
2514 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002515 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002516 return builder.makeFloatType(32);
2517 }
2518}
2519
John Kessenich8c8505c2016-07-26 12:50:38 -06002520// If node is a swizzle operation, return the type that should be used if
2521// the swizzle base is first consumed by another operation, before the swizzle
2522// is applied.
2523spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2524{
John Kessenichecba76f2017-01-06 00:34:48 -07002525 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002526 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2527 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2528 else
2529 return spv::NoType;
2530}
2531
2532// When inverting a swizzle with a parent op, this function
2533// will apply the swizzle operation to a completed parent operation.
2534spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2535{
2536 std::vector<unsigned> swizzle;
2537 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2538 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2539}
2540
John Kessenich8c8505c2016-07-26 12:50:38 -06002541// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2542void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2543{
2544 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2545 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2546 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2547}
2548
John Kessenich3ac051e2015-12-20 11:29:16 -07002549// Convert from a glslang type to an SPV type, by calling into a
2550// recursive version of this function. This establishes the inherited
2551// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002552spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2553{
John Kessenichead86222018-03-28 18:01:20 -06002554 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false);
John Kessenich31ed4832015-09-09 17:51:38 -06002555}
2556
2557// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002558// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002559// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06002560spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
2561 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier, bool lastBufferBlockMember)
John Kessenich31ed4832015-09-09 17:51:38 -06002562{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002563 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002564
2565 switch (type.getBasicType()) {
2566 case glslang::EbtVoid:
2567 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002568 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002569 break;
2570 case glslang::EbtFloat:
2571 spvType = builder.makeFloatType(32);
2572 break;
2573 case glslang::EbtDouble:
2574 spvType = builder.makeFloatType(64);
2575 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002576 case glslang::EbtFloat16:
John Kessenich66011cb2018-03-06 16:12:04 -07002577 builder.addCapability(spv::CapabilityFloat16);
2578#if AMD_EXTENSIONS
2579 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2580 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
2581#endif
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002582 spvType = builder.makeFloatType(16);
2583 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002584 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002585 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2586 // a 32-bit int where non-0 means true.
2587 if (explicitLayout != glslang::ElpNone)
2588 spvType = builder.makeUintType(32);
2589 else
2590 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002591 break;
John Kessenich66011cb2018-03-06 16:12:04 -07002592 case glslang::EbtInt8:
2593 builder.addCapability(spv::CapabilityInt8);
2594 spvType = builder.makeIntType(8);
2595 break;
2596 case glslang::EbtUint8:
2597 builder.addCapability(spv::CapabilityInt8);
2598 spvType = builder.makeUintType(8);
2599 break;
2600 case glslang::EbtInt16:
2601 builder.addCapability(spv::CapabilityInt16);
2602#ifdef AMD_EXTENSIONS
2603 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2604 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2605#endif
2606 spvType = builder.makeIntType(16);
2607 break;
2608 case glslang::EbtUint16:
2609 builder.addCapability(spv::CapabilityInt16);
2610#ifdef AMD_EXTENSIONS
2611 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2612 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2613#endif
2614 spvType = builder.makeUintType(16);
2615 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002616 case glslang::EbtInt:
2617 spvType = builder.makeIntType(32);
2618 break;
2619 case glslang::EbtUint:
2620 spvType = builder.makeUintType(32);
2621 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002622 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002623 spvType = builder.makeIntType(64);
2624 break;
2625 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002626 spvType = builder.makeUintType(64);
2627 break;
John Kessenich426394d2015-07-23 10:22:48 -06002628 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002629 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002630 spvType = builder.makeUintType(32);
2631 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002632 case glslang::EbtSampler:
2633 {
2634 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002635 if (sampler.sampler) {
2636 // pure sampler
2637 spvType = builder.makeSamplerType();
2638 } else {
2639 // an image is present, make its type
2640 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2641 sampler.image ? 2 : 1, TranslateImageFormat(type));
2642 if (sampler.combined) {
2643 // already has both image and sampler, make the combined type
2644 spvType = builder.makeSampledImageType(spvType);
2645 }
John Kessenich55e7d112015-11-15 21:33:39 -07002646 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002647 }
John Kessenich140f3df2015-06-26 16:58:36 -06002648 break;
2649 case glslang::EbtStruct:
2650 case glslang::EbtBlock:
2651 {
2652 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002653 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002654
2655 // Try to share structs for different layouts, but not yet for other
2656 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002657 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002658 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002659 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002660 break;
2661
2662 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002663 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002664 memberRemapper[glslangMembers].resize(glslangMembers->size());
2665 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002666 }
2667 break;
2668 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002669 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002670 break;
2671 }
2672
2673 if (type.isMatrix())
2674 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2675 else {
2676 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2677 if (type.getVectorSize() > 1)
2678 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2679 }
2680
2681 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002682 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2683
John Kessenichc9a80832015-09-12 12:17:44 -06002684 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002685 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002686 // We need to decorate array strides for types needing explicit layout, except blocks.
2687 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002688 // Use a dummy glslang type for querying internal strides of
2689 // arrays of arrays, but using just a one-dimensional array.
2690 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06002691 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
2692 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07002693
2694 // Will compute the higher-order strides here, rather than making a whole
2695 // pile of types and doing repetitive recursion on their contents.
2696 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2697 }
John Kessenichf8842e52016-01-04 19:22:56 -07002698
2699 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002700 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002701 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002702 if (stride > 0)
2703 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002704 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002705 }
2706 } else {
2707 // single-dimensional array, and don't yet have stride
2708
John Kessenichf8842e52016-01-04 19:22:56 -07002709 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002710 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2711 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002712 }
John Kessenich31ed4832015-09-09 17:51:38 -06002713
John Kessenichead86222018-03-28 18:01:20 -06002714 // Do the outer dimension, which might not be known for a runtime-sized array.
2715 // (Unsized arrays that survive through linking will be runtime-sized arrays)
2716 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07002717 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06002718 else {
2719 if (!lastBufferBlockMember) {
2720 builder.addExtension("SPV_EXT_descriptor_indexing");
2721 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
2722 }
John Kessenichead86222018-03-28 18:01:20 -06002723 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06002724 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002725 if (stride > 0)
2726 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002727 }
2728
2729 return spvType;
2730}
2731
John Kessenich0e737842017-03-24 18:38:16 -06002732// TODO: this functionality should exist at a higher level, in creating the AST
2733//
2734// Identify interface members that don't have their required extension turned on.
2735//
2736bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2737{
2738 auto& extensions = glslangIntermediate->getRequestedExtensions();
2739
Rex Xubcf291a2017-03-29 23:01:36 +08002740 if (member.getFieldName() == "gl_ViewportMask" &&
2741 extensions.find("GL_NV_viewport_array2") == extensions.end())
2742 return true;
2743 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2744 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2745 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002746 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2747 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2748 return true;
2749 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2750 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2751 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002752 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2753 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2754 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002755
2756 return false;
2757};
2758
John Kessenich6090df02016-06-30 21:18:02 -06002759// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2760// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2761// Mutually recursive with convertGlslangToSpvType().
2762spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2763 const glslang::TTypeList* glslangMembers,
2764 glslang::TLayoutPacking explicitLayout,
2765 const glslang::TQualifier& qualifier)
2766{
2767 // Create a vector of struct types for SPIR-V to consume
2768 std::vector<spv::Id> spvMembers;
2769 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 -06002770 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2771 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2772 if (glslangMember.hiddenMember()) {
2773 ++memberDelta;
2774 if (type.getBasicType() == glslang::EbtBlock)
2775 memberRemapper[glslangMembers][i] = -1;
2776 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002777 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002778 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002779 if (filterMember(glslangMember))
2780 continue;
2781 }
John Kessenich6090df02016-06-30 21:18:02 -06002782 // modify just this child's view of the qualifier
2783 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2784 InheritQualifiers(memberQualifier, qualifier);
2785
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002786 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002787 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002788 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002789
2790 // recurse
John Kessenichead86222018-03-28 18:01:20 -06002791 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
2792 i == (int)glslangMembers->size() - 1;
2793 spvMembers.push_back(
2794 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember));
John Kessenich6090df02016-06-30 21:18:02 -06002795 }
2796 }
2797
2798 // Make the SPIR-V type
2799 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002800 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002801 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2802
2803 // Decorate it
2804 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2805
2806 return spvType;
2807}
2808
2809void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2810 const glslang::TTypeList* glslangMembers,
2811 glslang::TLayoutPacking explicitLayout,
2812 const glslang::TQualifier& qualifier,
2813 spv::Id spvType)
2814{
2815 // Name and decorate the non-hidden members
2816 int offset = -1;
2817 int locationOffset = 0; // for use within the members of this struct
2818 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2819 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2820 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002821 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002822 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002823 if (filterMember(glslangMember))
2824 continue;
2825 }
John Kessenich6090df02016-06-30 21:18:02 -06002826
2827 // modify just this child's view of the qualifier
2828 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2829 InheritQualifiers(memberQualifier, qualifier);
2830
2831 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07002832 if (member < 0)
2833 continue;
2834
2835 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2836 builder.addMemberDecoration(spvType, member,
2837 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2838 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2839 // Add interpolation and auxiliary storage decorations only to
2840 // top-level members of Input and Output storage classes
2841 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2842 type.getQualifier().storage == glslang::EvqVaryingOut) {
2843 if (type.getBasicType() == glslang::EbtBlock ||
2844 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
2845 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2846 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002847 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002848 }
2849 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002850
John Kessenich5d610ee2018-03-07 18:05:55 -07002851 if (type.getBasicType() == glslang::EbtBlock &&
2852 qualifier.storage == glslang::EvqBuffer) {
2853 // Add memory decorations only to top-level members of shader storage block
2854 std::vector<spv::Decoration> memory;
2855 TranslateMemoryDecoration(memberQualifier, memory);
2856 for (unsigned int i = 0; i < memory.size(); ++i)
2857 builder.addMemberDecoration(spvType, member, memory[i]);
2858 }
John Kessenich6090df02016-06-30 21:18:02 -06002859
John Kessenich5d610ee2018-03-07 18:05:55 -07002860 // Location assignment was already completed correctly by the front end,
2861 // just track whether a member needs to be decorated.
2862 // Ignore member locations if the container is an array, as that's
2863 // ill-specified and decisions have been made to not allow this.
2864 if (! type.isArray() && memberQualifier.hasLocation())
2865 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002866
John Kessenich5d610ee2018-03-07 18:05:55 -07002867 if (qualifier.hasLocation()) // track for upcoming inheritance
2868 locationOffset += glslangIntermediate->computeTypeLocationSize(
2869 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06002870
John Kessenich5d610ee2018-03-07 18:05:55 -07002871 // component, XFB, others
2872 if (glslangMember.getQualifier().hasComponent())
2873 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
2874 glslangMember.getQualifier().layoutComponent);
2875 if (glslangMember.getQualifier().hasXfbOffset())
2876 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
2877 glslangMember.getQualifier().layoutXfbOffset);
2878 else if (explicitLayout != glslang::ElpNone) {
2879 // figure out what to do with offset, which is accumulating
2880 int nextOffset;
2881 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2882 if (offset >= 0)
2883 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2884 offset = nextOffset;
2885 }
John Kessenich6090df02016-06-30 21:18:02 -06002886
John Kessenich5d610ee2018-03-07 18:05:55 -07002887 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2888 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
2889 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06002890
John Kessenich5d610ee2018-03-07 18:05:55 -07002891 // built-in variable decorations
2892 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
2893 if (builtIn != spv::BuiltInMax)
2894 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002895
John Kessenich5611c6d2018-04-05 11:25:02 -06002896 // nonuniform
2897 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
2898
John Kessenichead86222018-03-28 18:01:20 -06002899 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
2900 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
2901 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
2902 memberQualifier.semanticName);
2903 }
2904
chaoc771d89f2017-01-13 01:10:53 -08002905#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07002906 if (builtIn == spv::BuiltInLayer) {
2907 // SPV_NV_viewport_array2 extension
2908 if (glslangMember.getQualifier().layoutViewportRelative){
2909 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2910 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2911 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08002912 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002913 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2914 builder.addMemberDecoration(spvType, member,
2915 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
2916 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2917 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2918 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08002919 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002920 }
2921 if (glslangMember.getQualifier().layoutPassthrough) {
2922 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2923 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2924 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2925 }
chaoc771d89f2017-01-13 01:10:53 -08002926#endif
John Kessenich6090df02016-06-30 21:18:02 -06002927 }
2928
2929 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07002930 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2931 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002932 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2933 builder.addCapability(spv::CapabilityGeometryStreams);
2934 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2935 }
John Kessenich6090df02016-06-30 21:18:02 -06002936}
2937
John Kessenich6c292d32016-02-15 20:58:50 -07002938// Turn the expression forming the array size into an id.
2939// This is not quite trivial, because of specialization constants.
2940// Sometimes, a raw constant is turned into an Id, and sometimes
2941// a specialization constant expression is.
2942spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2943{
2944 // First, see if this is sized with a node, meaning a specialization constant:
2945 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2946 if (specNode != nullptr) {
2947 builder.clearAccessChain();
2948 specNode->traverse(this);
2949 return accessChainLoad(specNode->getAsTyped()->getType());
2950 }
qining25262b32016-05-06 17:25:16 -04002951
John Kessenich6c292d32016-02-15 20:58:50 -07002952 // Otherwise, need a compile-time (front end) size, get it:
2953 int size = arraySizes.getDimSize(dim);
2954 assert(size > 0);
2955 return builder.makeUintConstant(size);
2956}
2957
John Kessenich103bef92016-02-08 21:38:15 -07002958// Wrap the builder's accessChainLoad to:
2959// - localize handling of RelaxedPrecision
2960// - use the SPIR-V inferred type instead of another conversion of the glslang type
2961// (avoids unnecessary work and possible type punning for structures)
2962// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002963spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2964{
John Kessenich103bef92016-02-08 21:38:15 -07002965 spv::Id nominalTypeId = builder.accessChainGetInferredType();
John Kessenich5611c6d2018-04-05 11:25:02 -06002966 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
2967 TranslateNonUniformDecoration(type.getQualifier()), nominalTypeId);
John Kessenich103bef92016-02-08 21:38:15 -07002968
2969 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002970 if (type.getBasicType() == glslang::EbtBool) {
2971 if (builder.isScalarType(nominalTypeId)) {
2972 // Conversion for bool
2973 spv::Id boolType = builder.makeBoolType();
2974 if (nominalTypeId != boolType)
2975 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2976 } else if (builder.isVectorType(nominalTypeId)) {
2977 // Conversion for bvec
2978 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2979 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2980 if (nominalTypeId != bvecType)
2981 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2982 }
2983 }
John Kessenich103bef92016-02-08 21:38:15 -07002984
2985 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002986}
2987
Rex Xu27253232016-02-23 17:51:09 +08002988// Wrap the builder's accessChainStore to:
2989// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002990//
2991// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002992void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2993{
2994 // Need to convert to abstract types when necessary
2995 if (type.getBasicType() == glslang::EbtBool) {
2996 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2997
2998 if (builder.isScalarType(nominalTypeId)) {
2999 // Conversion for bool
3000 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003001 if (nominalTypeId != boolType) {
3002 // keep these outside arguments, for determinant order-of-evaluation
3003 spv::Id one = builder.makeUintConstant(1);
3004 spv::Id zero = builder.makeUintConstant(0);
3005 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3006 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003007 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003008 } else if (builder.isVectorType(nominalTypeId)) {
3009 // Conversion for bvec
3010 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3011 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003012 if (nominalTypeId != bvecType) {
3013 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003014 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3015 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3016 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003017 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003018 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3019 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003020 }
3021 }
3022
3023 builder.accessChainStore(rvalue);
3024}
3025
John Kessenich4bf71552016-09-02 11:20:21 -06003026// For storing when types match at the glslang level, but not might match at the
3027// SPIR-V level.
3028//
3029// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003030// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003031// as in a member-decorated way.
3032//
3033// NOTE: This function can handle any store request; if it's not special it
3034// simplifies to a simple OpStore.
3035//
3036// Implicitly uses the existing builder.accessChain as the storage target.
3037void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3038{
John Kessenichb3e24e42016-09-11 12:33:43 -06003039 // we only do the complex path here if it's an aggregate
3040 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003041 accessChainStore(type, rValue);
3042 return;
3043 }
3044
John Kessenichb3e24e42016-09-11 12:33:43 -06003045 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003046 spv::Id rType = builder.getTypeId(rValue);
3047 spv::Id lValue = builder.accessChainGetLValue();
3048 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3049 if (lType == rType) {
3050 accessChainStore(type, rValue);
3051 return;
3052 }
3053
John Kessenichb3e24e42016-09-11 12:33:43 -06003054 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003055 // where the two types were the same type in GLSL. This requires member
3056 // by member copy, recursively.
3057
John Kessenichb3e24e42016-09-11 12:33:43 -06003058 // If an array, copy element by element.
3059 if (type.isArray()) {
3060 glslang::TType glslangElementType(type, 0);
3061 spv::Id elementRType = builder.getContainedTypeId(rType);
3062 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3063 // get the source member
3064 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003065
John Kessenichb3e24e42016-09-11 12:33:43 -06003066 // set up the target storage
3067 builder.clearAccessChain();
3068 builder.setAccessChainLValue(lValue);
3069 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06003070
John Kessenichb3e24e42016-09-11 12:33:43 -06003071 // store the member
3072 multiTypeStore(glslangElementType, elementRValue);
3073 }
3074 } else {
3075 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003076
John Kessenichb3e24e42016-09-11 12:33:43 -06003077 // loop over structure members
3078 const glslang::TTypeList& members = *type.getStruct();
3079 for (int m = 0; m < (int)members.size(); ++m) {
3080 const glslang::TType& glslangMemberType = *members[m].type;
3081
3082 // get the source member
3083 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3084 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3085
3086 // set up the target storage
3087 builder.clearAccessChain();
3088 builder.setAccessChainLValue(lValue);
3089 builder.accessChainPush(builder.makeIntConstant(m));
3090
3091 // store the member
3092 multiTypeStore(glslangMemberType, memberRValue);
3093 }
John Kessenich4bf71552016-09-02 11:20:21 -06003094 }
3095}
3096
John Kessenichf85e8062015-12-19 13:57:10 -07003097// Decide whether or not this type should be
3098// decorated with offsets and strides, and if so
3099// whether std140 or std430 rules should be applied.
3100glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003101{
John Kessenichf85e8062015-12-19 13:57:10 -07003102 // has to be a block
3103 if (type.getBasicType() != glslang::EbtBlock)
3104 return glslang::ElpNone;
3105
3106 // has to be a uniform or buffer block
3107 if (type.getQualifier().storage != glslang::EvqUniform &&
3108 type.getQualifier().storage != glslang::EvqBuffer)
3109 return glslang::ElpNone;
3110
3111 // return the layout to use
3112 switch (type.getQualifier().layoutPacking) {
3113 case glslang::ElpStd140:
3114 case glslang::ElpStd430:
3115 return type.getQualifier().layoutPacking;
3116 default:
3117 return glslang::ElpNone;
3118 }
John Kessenich31ed4832015-09-09 17:51:38 -06003119}
3120
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003121// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003122int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003123{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003124 int size;
John Kessenich49987892015-12-29 17:11:44 -07003125 int stride;
3126 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003127
3128 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003129}
3130
John Kessenich49987892015-12-29 17:11:44 -07003131// 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 -07003132// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003133int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003134{
John Kessenich49987892015-12-29 17:11:44 -07003135 glslang::TType elementType;
3136 elementType.shallowCopy(matrixType);
3137 elementType.clearArraySizes();
3138
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003139 int size;
John Kessenich49987892015-12-29 17:11:44 -07003140 int stride;
3141 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
3142
3143 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003144}
3145
John Kessenich5e4b1242015-08-06 22:53:06 -06003146// Given a member type of a struct, realign the current offset for it, and compute
3147// the next (not yet aligned) offset for the next member, which will get aligned
3148// on the next call.
3149// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3150// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3151// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003152void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003153 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003154{
3155 // this will get a positive value when deemed necessary
3156 nextOffset = -1;
3157
John Kessenich5e4b1242015-08-06 22:53:06 -06003158 // override anything in currentOffset with user-set offset
3159 if (memberType.getQualifier().hasOffset())
3160 currentOffset = memberType.getQualifier().layoutOffset;
3161
3162 // It could be that current linker usage in glslang updated all the layoutOffset,
3163 // in which case the following code does not matter. But, that's not quite right
3164 // once cross-compilation unit GLSL validation is done, as the original user
3165 // settings are needed in layoutOffset, and then the following will come into play.
3166
John Kessenichf85e8062015-12-19 13:57:10 -07003167 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003168 if (! memberType.getQualifier().hasOffset())
3169 currentOffset = -1;
3170
3171 return;
3172 }
3173
John Kessenichf85e8062015-12-19 13:57:10 -07003174 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003175 if (currentOffset < 0)
3176 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003177
John Kessenich5e4b1242015-08-06 22:53:06 -06003178 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3179 // but possibly not yet correctly aligned.
3180
3181 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003182 int dummyStride;
3183 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003184
3185 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003186 // TODO: make this consistent in early phases of code:
3187 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3188 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3189 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06003190 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003191 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003192 int dummySize;
3193 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3194 if (componentAlignment <= 4)
3195 memberAlignment = componentAlignment;
3196 }
3197
3198 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003199 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003200
3201 // Bump up to vec4 if there is a bad straddle
3202 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
3203 glslang::RoundToPow2(currentOffset, 16);
3204
John Kessenich5e4b1242015-08-06 22:53:06 -06003205 nextOffset = currentOffset + memberSize;
3206}
3207
David Netoa901ffe2016-06-08 14:11:40 +01003208void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003209{
David Netoa901ffe2016-06-08 14:11:40 +01003210 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3211 switch (glslangBuiltIn)
3212 {
3213 case glslang::EbvClipDistance:
3214 case glslang::EbvCullDistance:
3215 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003216#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003217 case glslang::EbvViewportMaskNV:
3218 case glslang::EbvSecondaryPositionNV:
3219 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003220 case glslang::EbvPositionPerViewNV:
3221 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08003222#endif
David Netoa901ffe2016-06-08 14:11:40 +01003223 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3224 // Alternately, we could just call this for any glslang built-in, since the
3225 // capability already guards against duplicates.
3226 TranslateBuiltInDecoration(glslangBuiltIn, false);
3227 break;
3228 default:
3229 // Capabilities were already generated when the struct was declared.
3230 break;
3231 }
John Kessenichebb50532016-05-16 19:22:05 -06003232}
3233
John Kessenich6fccb3c2016-09-19 16:01:41 -06003234bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003235{
John Kessenicheee9d532016-09-19 18:09:30 -06003236 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003237}
3238
John Kessenichd41993d2017-09-10 15:21:05 -06003239// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003240// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3241// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd41993d2017-09-10 15:21:05 -06003242bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier)
3243{
John Kessenich6a14f782017-12-04 02:48:10 -07003244 assert(qualifier == glslang::EvqIn ||
3245 qualifier == glslang::EvqOut ||
3246 qualifier == glslang::EvqInOut ||
3247 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003248 return qualifier != glslang::EvqConstReadOnly;
3249}
3250
3251// Is parameter pass-by-original?
3252bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3253 bool implicitThisParam)
3254{
3255 if (implicitThisParam) // implicit this
3256 return true;
3257 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003258 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003259 return paramType.containsOpaque() || // sampler, etc.
3260 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3261}
3262
John Kessenich140f3df2015-06-26 16:58:36 -06003263// Make all the functions, skeletally, without actually visiting their bodies.
3264void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3265{
John Kessenichfad62972017-07-18 02:35:46 -06003266 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
3267 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3268 if (paramPrecision != spv::NoPrecision)
3269 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06003270 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06003271 };
3272
John Kessenich140f3df2015-06-26 16:58:36 -06003273 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3274 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003275 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003276 continue;
3277
3278 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003279 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003280 //
qining25262b32016-05-06 17:25:16 -04003281 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003282 // function. What it is an address of varies:
3283 //
John Kessenich4bf71552016-09-02 11:20:21 -06003284 // - "in" parameters not marked as "const" can be written to without modifying the calling
3285 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003286 //
3287 // - "const in" parameters can just be the r-value, as no writes need occur.
3288 //
John Kessenich4bf71552016-09-02 11:20:21 -06003289 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3290 // 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 -06003291
3292 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003293 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003294 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3295
John Kessenichfad62972017-07-18 02:35:46 -06003296 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3297 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003298
John Kessenichfad62972017-07-18 02:35:46 -06003299 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003300 for (int p = 0; p < (int)parameters.size(); ++p) {
3301 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3302 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003303 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003304 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003305 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003306 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3307 else
John Kessenich4bf71552016-09-02 11:20:21 -06003308 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003309 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003310 paramTypes.push_back(typeId);
3311 }
3312
3313 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003314 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3315 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003316 glslFunction->getName().c_str(), paramTypes,
3317 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003318 if (implicitThis)
3319 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003320
3321 // Track function to emit/call later
3322 functionMap[glslFunction->getName().c_str()] = function;
3323
3324 // Set the parameter id's
3325 for (int p = 0; p < (int)parameters.size(); ++p) {
3326 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3327 // give a name too
3328 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3329 }
3330 }
3331}
3332
3333// Process all the initializers, while skipping the functions and link objects
3334void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3335{
3336 builder.setBuildPoint(shaderEntry->getLastBlock());
3337 for (int i = 0; i < (int)initializers.size(); ++i) {
3338 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3339 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3340
3341 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003342 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003343 initializer->traverse(this);
3344 }
3345 }
3346}
3347
3348// Process all the functions, while skipping initializers.
3349void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3350{
3351 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3352 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003353 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003354 node->traverse(this);
3355 }
3356}
3357
3358void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3359{
qining25262b32016-05-06 17:25:16 -04003360 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003361 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003362 currentFunction = functionMap[node->getName().c_str()];
3363 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003364 builder.setBuildPoint(functionBlock);
3365}
3366
Rex Xu04db3f52015-09-16 11:44:02 +08003367void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003368{
Rex Xufc618912015-09-09 16:42:49 +08003369 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003370
3371 glslang::TSampler sampler = {};
3372 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003373#ifdef AMD_EXTENSIONS
3374 bool f16ShadowCompare = false;
3375#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003376 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003377 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3378 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003379#ifdef AMD_EXTENSIONS
3380 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3381#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003382 }
3383
John Kessenich140f3df2015-06-26 16:58:36 -06003384 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3385 builder.clearAccessChain();
3386 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003387
3388 // Special case l-value operands
3389 bool lvalue = false;
3390 switch (node.getOp()) {
3391 case glslang::EOpImageAtomicAdd:
3392 case glslang::EOpImageAtomicMin:
3393 case glslang::EOpImageAtomicMax:
3394 case glslang::EOpImageAtomicAnd:
3395 case glslang::EOpImageAtomicOr:
3396 case glslang::EOpImageAtomicXor:
3397 case glslang::EOpImageAtomicExchange:
3398 case glslang::EOpImageAtomicCompSwap:
3399 if (i == 0)
3400 lvalue = true;
3401 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003402 case glslang::EOpSparseImageLoad:
3403 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3404 lvalue = true;
3405 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003406#ifdef AMD_EXTENSIONS
3407 case glslang::EOpSparseTexture:
3408 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3409 lvalue = true;
3410 break;
3411 case glslang::EOpSparseTextureClamp:
3412 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3413 lvalue = true;
3414 break;
3415 case glslang::EOpSparseTextureLod:
3416 case glslang::EOpSparseTextureOffset:
3417 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
3418 lvalue = true;
3419 break;
3420#else
Rex Xu48edadf2015-12-31 16:11:41 +08003421 case glslang::EOpSparseTexture:
3422 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3423 lvalue = true;
3424 break;
3425 case glslang::EOpSparseTextureClamp:
3426 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3427 lvalue = true;
3428 break;
3429 case glslang::EOpSparseTextureLod:
3430 case glslang::EOpSparseTextureOffset:
3431 if (i == 3)
3432 lvalue = true;
3433 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003434#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003435 case glslang::EOpSparseTextureFetch:
3436 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3437 lvalue = true;
3438 break;
3439 case glslang::EOpSparseTextureFetchOffset:
3440 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3441 lvalue = true;
3442 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003443#ifdef AMD_EXTENSIONS
3444 case glslang::EOpSparseTextureLodOffset:
3445 case glslang::EOpSparseTextureGrad:
3446 case glslang::EOpSparseTextureOffsetClamp:
3447 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
3448 lvalue = true;
3449 break;
3450 case glslang::EOpSparseTextureGradOffset:
3451 case glslang::EOpSparseTextureGradClamp:
3452 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
3453 lvalue = true;
3454 break;
3455 case glslang::EOpSparseTextureGradOffsetClamp:
3456 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
3457 lvalue = true;
3458 break;
3459#else
Rex Xu48edadf2015-12-31 16:11:41 +08003460 case glslang::EOpSparseTextureLodOffset:
3461 case glslang::EOpSparseTextureGrad:
3462 case glslang::EOpSparseTextureOffsetClamp:
3463 if (i == 4)
3464 lvalue = true;
3465 break;
3466 case glslang::EOpSparseTextureGradOffset:
3467 case glslang::EOpSparseTextureGradClamp:
3468 if (i == 5)
3469 lvalue = true;
3470 break;
3471 case glslang::EOpSparseTextureGradOffsetClamp:
3472 if (i == 6)
3473 lvalue = true;
3474 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003475#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08003476 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003477 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3478 lvalue = true;
3479 break;
3480 case glslang::EOpSparseTextureGatherOffset:
3481 case glslang::EOpSparseTextureGatherOffsets:
3482 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3483 lvalue = true;
3484 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003485#ifdef AMD_EXTENSIONS
3486 case glslang::EOpSparseTextureGatherLod:
3487 if (i == 3)
3488 lvalue = true;
3489 break;
3490 case glslang::EOpSparseTextureGatherLodOffset:
3491 case glslang::EOpSparseTextureGatherLodOffsets:
3492 if (i == 4)
3493 lvalue = true;
3494 break;
Rex Xu129799a2017-07-05 17:23:28 +08003495 case glslang::EOpSparseImageLoadLod:
3496 if (i == 3)
3497 lvalue = true;
3498 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003499#endif
Rex Xufc618912015-09-09 16:42:49 +08003500 default:
3501 break;
3502 }
3503
Rex Xu6b86d492015-09-16 17:48:22 +08003504 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003505 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003506 else
John Kessenich32cfd492016-02-02 12:37:46 -07003507 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003508 }
3509}
3510
John Kessenichfc51d282015-08-19 13:34:18 -06003511void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003512{
John Kessenichfc51d282015-08-19 13:34:18 -06003513 builder.clearAccessChain();
3514 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003515 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003516}
John Kessenich140f3df2015-06-26 16:58:36 -06003517
John Kessenichfc51d282015-08-19 13:34:18 -06003518spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3519{
John Kesseniche485c7a2017-05-31 18:50:53 -06003520 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003521 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003522
3523 builder.setLine(node->getLoc().line);
3524
John Kessenichfc51d282015-08-19 13:34:18 -06003525 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003526 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3527 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08003528#ifdef AMD_EXTENSIONS
3529 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
3530 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
3531 : false;
3532#endif
3533
John Kessenichfc51d282015-08-19 13:34:18 -06003534 std::vector<spv::Id> arguments;
3535 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003536 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003537 else
3538 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003539 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003540
3541 spv::Builder::TextureParameters params = { };
3542 params.sampler = arguments[0];
3543
Rex Xu04db3f52015-09-16 11:44:02 +08003544 glslang::TCrackedTextureOp cracked;
3545 node->crackTexture(sampler, cracked);
3546
amhagan05506bb2017-06-13 16:53:02 -04003547 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003548
John Kessenichfc51d282015-08-19 13:34:18 -06003549 // Check for queries
3550 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003551 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3552 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003553 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003554
John Kessenichfc51d282015-08-19 13:34:18 -06003555 switch (node->getOp()) {
3556 case glslang::EOpImageQuerySize:
3557 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003558 if (arguments.size() > 1) {
3559 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003560 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003561 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003562 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003563 case glslang::EOpImageQuerySamples:
3564 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003565 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003566 case glslang::EOpTextureQueryLod:
3567 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003568 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003569 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003570 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003571 case glslang::EOpSparseTexelsResident:
3572 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003573 default:
3574 assert(0);
3575 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003576 }
John Kessenich140f3df2015-06-26 16:58:36 -06003577 }
3578
LoopDawg4425f242018-02-18 11:40:01 -07003579 int components = node->getType().getVectorSize();
3580
3581 if (node->getOp() == glslang::EOpTextureFetch) {
3582 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3583 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3584 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3585 // here around e.g. which ones return scalars or other types.
3586 components = 4;
3587 }
3588
3589 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3590
3591 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3592
Rex Xufc618912015-09-09 16:42:49 +08003593 // Check for image functions other than queries
3594 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003595 std::vector<spv::Id> operands;
3596 auto opIt = arguments.begin();
3597 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003598
3599 // Handle subpass operations
3600 // TODO: GLSL should change to have the "MS" only on the type rather than the
3601 // built-in function.
3602 if (cracked.subpass) {
3603 // add on the (0,0) coordinate
3604 spv::Id zero = builder.makeIntConstant(0);
3605 std::vector<spv::Id> comps;
3606 comps.push_back(zero);
3607 comps.push_back(zero);
3608 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3609 if (sampler.ms) {
3610 operands.push_back(spv::ImageOperandsSampleMask);
3611 operands.push_back(*(opIt++));
3612 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003613 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3614 builder.setPrecision(result, precision);
3615 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003616 }
3617
John Kessenich56bab042015-09-16 10:54:31 -06003618 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003619#ifdef AMD_EXTENSIONS
3620 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3621#else
John Kessenich56bab042015-09-16 10:54:31 -06003622 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003623#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003624 if (sampler.ms) {
3625 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003626 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003627#ifdef AMD_EXTENSIONS
3628 } else if (cracked.lod) {
3629 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3630 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3631
3632 operands.push_back(spv::ImageOperandsLodMask);
3633 operands.push_back(*opIt);
3634#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003635 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003636 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3637 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003638
LoopDawg4425f242018-02-18 11:40:01 -07003639 std::vector<spv::Id> result = { builder.createOp(spv::OpImageRead, resultType(), operands) };
3640 builder.setPrecision(result[0], precision);
3641
3642 // If needed, add a conversion constructor to the proper size.
3643 if (components != node->getType().getVectorSize())
3644 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3645
3646 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08003647#ifdef AMD_EXTENSIONS
3648 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3649#else
John Kessenich56bab042015-09-16 10:54:31 -06003650 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003651#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003652 if (sampler.ms) {
3653 operands.push_back(*(opIt + 1));
3654 operands.push_back(spv::ImageOperandsSampleMask);
3655 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003656#ifdef AMD_EXTENSIONS
3657 } else if (cracked.lod) {
3658 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3659 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3660
3661 operands.push_back(*(opIt + 1));
3662 operands.push_back(spv::ImageOperandsLodMask);
3663 operands.push_back(*opIt);
3664#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003665 } else
3666 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003667 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003668 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3669 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003670 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003671#ifdef AMD_EXTENSIONS
3672 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3673#else
Rex Xu5eafa472016-02-19 22:24:03 +08003674 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003675#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003676 builder.addCapability(spv::CapabilitySparseResidency);
3677 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3678 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3679
3680 if (sampler.ms) {
3681 operands.push_back(spv::ImageOperandsSampleMask);
3682 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003683#ifdef AMD_EXTENSIONS
3684 } else if (cracked.lod) {
3685 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3686 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3687
3688 operands.push_back(spv::ImageOperandsLodMask);
3689 operands.push_back(*opIt++);
3690#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003691 }
3692
3693 // Create the return type that was a special structure
3694 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003695 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003696 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3697 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3698
3699 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3700
3701 // Decode the return type
3702 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3703 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003704 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003705 // Process image atomic operations
3706
3707 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3708 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003709 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003710
John Kessenich8c8505c2016-07-26 12:50:38 -06003711 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003712 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003713
3714 std::vector<spv::Id> operands;
3715 operands.push_back(pointer);
3716 for (; opIt != arguments.end(); ++opIt)
3717 operands.push_back(*opIt);
3718
John Kessenich8c8505c2016-07-26 12:50:38 -06003719 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003720 }
3721 }
3722
amhagan05506bb2017-06-13 16:53:02 -04003723#ifdef AMD_EXTENSIONS
3724 // Check for fragment mask functions other than queries
3725 if (cracked.fragMask) {
3726 assert(sampler.ms);
3727
3728 auto opIt = arguments.begin();
3729 std::vector<spv::Id> operands;
3730
3731 // Extract the image if necessary
3732 if (builder.isSampledImage(params.sampler))
3733 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3734
3735 operands.push_back(params.sampler);
3736 ++opIt;
3737
3738 if (sampler.isSubpass()) {
3739 // add on the (0,0) coordinate
3740 spv::Id zero = builder.makeIntConstant(0);
3741 std::vector<spv::Id> comps;
3742 comps.push_back(zero);
3743 comps.push_back(zero);
3744 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3745 }
3746
3747 for (; opIt != arguments.end(); ++opIt)
3748 operands.push_back(*opIt);
3749
3750 spv::Op fragMaskOp = spv::OpNop;
3751 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3752 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3753 else if (node->getOp() == glslang::EOpFragmentFetch)
3754 fragMaskOp = spv::OpFragmentFetchAMD;
3755
3756 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3757 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3758 return builder.createOp(fragMaskOp, resultType(), operands);
3759 }
3760#endif
3761
Rex Xufc618912015-09-09 16:42:49 +08003762 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003763 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003764 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3765
John Kessenichfc51d282015-08-19 13:34:18 -06003766 // check for bias argument
3767 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003768#ifdef AMD_EXTENSIONS
3769 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3770#else
Rex Xu71519fe2015-11-11 15:35:47 +08003771 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003772#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003773 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003774#ifdef AMD_EXTENSIONS
3775 if (cracked.gather)
3776 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08003777
3778 if (f16ShadowCompare)
3779 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003780#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003781 if (cracked.offset)
3782 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003783#ifdef AMD_EXTENSIONS
3784 else if (cracked.offsets)
3785 ++nonBiasArgCount;
3786#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003787 if (cracked.grad)
3788 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003789 if (cracked.lodClamp)
3790 ++nonBiasArgCount;
3791 if (sparse)
3792 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003793
3794 if ((int)arguments.size() > nonBiasArgCount)
3795 bias = true;
3796 }
3797
John Kessenicha5c33d62016-06-02 23:45:21 -06003798 // See if the sampler param should really be just the SPV image part
3799 if (cracked.fetch) {
3800 // a fetch needs to have the image extracted first
3801 if (builder.isSampledImage(params.sampler))
3802 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3803 }
3804
Rex Xu225e0fc2016-11-17 17:47:59 +08003805#ifdef AMD_EXTENSIONS
3806 if (cracked.gather) {
3807 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3808 if (bias || cracked.lod ||
3809 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3810 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003811 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003812 }
3813 }
3814#endif
3815
John Kessenichfc51d282015-08-19 13:34:18 -06003816 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003817
John Kessenichfc51d282015-08-19 13:34:18 -06003818 params.coords = arguments[1];
3819 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003820 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003821
3822 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08003823#ifdef AMD_EXTENSIONS
3824 if (cubeCompare || f16ShadowCompare) {
3825#else
Rex Xu48edadf2015-12-31 16:11:41 +08003826 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08003827#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003828 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003829 ++extraArgs;
3830 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003831 params.Dref = arguments[2];
3832 ++extraArgs;
3833 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003834 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003835 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003836 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003837 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003838 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003839 dRefComp = builder.getNumComponents(params.coords) - 1;
3840 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003841 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3842 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003843
3844 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003845 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003846 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003847 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003848 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3849 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3850 noImplicitLod = true;
3851 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003852
3853 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003854 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003855 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003856 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003857 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003858
3859 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003860 if (cracked.grad) {
3861 params.gradX = arguments[2 + extraArgs];
3862 params.gradY = arguments[3 + extraArgs];
3863 extraArgs += 2;
3864 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003865
3866 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003867 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003868 params.offset = arguments[2 + extraArgs];
3869 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003870 } else if (cracked.offsets) {
3871 params.offsets = arguments[2 + extraArgs];
3872 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003873 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003874
3875 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003876 if (cracked.lodClamp) {
3877 params.lodClamp = arguments[2 + extraArgs];
3878 ++extraArgs;
3879 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003880
3881 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003882 if (sparse) {
3883 params.texelOut = arguments[2 + extraArgs];
3884 ++extraArgs;
3885 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003886
John Kessenich76d4dfc2016-06-16 12:43:23 -06003887 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003888 if (cracked.gather && ! sampler.shadow) {
3889 // default component is 0, if missing, otherwise an argument
3890 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003891 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003892 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003893 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003894 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003895 }
3896
3897 // bias
3898 if (bias) {
3899 params.bias = arguments[2 + extraArgs];
3900 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003901 }
John Kessenichfc51d282015-08-19 13:34:18 -06003902
John Kessenich65336482016-06-16 14:06:26 -06003903 // projective component (might not to move)
3904 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3905 // are divided by the last component of P."
3906 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3907 // unused components will appear after all used components."
3908 if (cracked.proj) {
3909 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3910 int projTargetComp;
3911 switch (sampler.dim) {
3912 case glslang::Esd1D: projTargetComp = 1; break;
3913 case glslang::Esd2D: projTargetComp = 2; break;
3914 case glslang::EsdRect: projTargetComp = 2; break;
3915 default: projTargetComp = projSourceComp; break;
3916 }
3917 // copy the projective coordinate if we have to
3918 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003919 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003920 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3921 projSourceComp);
3922 params.coords = builder.createCompositeInsert(projComp, params.coords,
3923 builder.getTypeId(params.coords), projTargetComp);
3924 }
3925 }
3926
LoopDawg4425f242018-02-18 11:40:01 -07003927 std::vector<spv::Id> result = {
3928 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
3929 };
3930
3931 if (components != node->getType().getVectorSize())
3932 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3933
3934 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06003935}
3936
3937spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3938{
3939 // Grab the function's pointer from the previously created function
3940 spv::Function* function = functionMap[node->getName().c_str()];
3941 if (! function)
3942 return 0;
3943
3944 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3945 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3946
3947 // See comments in makeFunctions() for details about the semantics for parameter passing.
3948 //
3949 // These imply we need a four step process:
3950 // 1. Evaluate the arguments
3951 // 2. Allocate and make copies of in, out, and inout arguments
3952 // 3. Make the call
3953 // 4. Copy back the results
3954
3955 // 1. Evaluate the arguments
3956 std::vector<spv::Builder::AccessChain> lValues;
3957 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003958 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003959 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003960 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003961 // build l-value
3962 builder.clearAccessChain();
3963 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003964 argTypes.push_back(&paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003965 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenich6a14f782017-12-04 02:48:10 -07003966 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0) ||
3967 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003968 // save l-value
3969 lValues.push_back(builder.getAccessChain());
3970 } else {
3971 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003972 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003973 }
3974 }
3975
3976 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3977 // copy the original into that space.
3978 //
3979 // Also, build up the list of actual arguments to pass in for the call
3980 int lValueCount = 0;
3981 int rValueCount = 0;
3982 std::vector<spv::Id> spvArgs;
3983 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003984 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003985 spv::Id arg;
John Kessenichd41993d2017-09-10 15:21:05 -06003986 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003987 builder.setAccessChain(lValues[lValueCount]);
3988 arg = builder.accessChainGetLValue();
3989 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06003990 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003991 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003992 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3993 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3994 // need to copy the input into output space
3995 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003996 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003997 builder.clearAccessChain();
3998 builder.setAccessChainLValue(arg);
3999 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004000 }
4001 ++lValueCount;
4002 } else {
4003 arg = rValues[rValueCount];
4004 ++rValueCount;
4005 }
4006 spvArgs.push_back(arg);
4007 }
4008
4009 // 3. Make the call.
4010 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004011 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004012
4013 // 4. Copy back out an "out" arguments.
4014 lValueCount = 0;
4015 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06004016 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenichd41993d2017-09-10 15:21:05 -06004017 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0))
4018 ++lValueCount;
4019 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004020 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4021 spv::Id copy = builder.createLoad(spvArgs[a]);
4022 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06004023 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004024 }
4025 ++lValueCount;
4026 }
4027 }
4028
4029 return result;
4030}
4031
4032// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004033spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004034 spv::Id typeId, spv::Id left, spv::Id right,
4035 glslang::TBasicType typeProxy, bool reduceComparison)
4036{
John Kessenich66011cb2018-03-06 16:12:04 -07004037 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4038 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004039 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004040
4041 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004042 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004043 bool comparison = false;
4044
4045 switch (op) {
4046 case glslang::EOpAdd:
4047 case glslang::EOpAddAssign:
4048 if (isFloat)
4049 binOp = spv::OpFAdd;
4050 else
4051 binOp = spv::OpIAdd;
4052 break;
4053 case glslang::EOpSub:
4054 case glslang::EOpSubAssign:
4055 if (isFloat)
4056 binOp = spv::OpFSub;
4057 else
4058 binOp = spv::OpISub;
4059 break;
4060 case glslang::EOpMul:
4061 case glslang::EOpMulAssign:
4062 if (isFloat)
4063 binOp = spv::OpFMul;
4064 else
4065 binOp = spv::OpIMul;
4066 break;
4067 case glslang::EOpVectorTimesScalar:
4068 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004069 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004070 if (builder.isVector(right))
4071 std::swap(left, right);
4072 assert(builder.isScalar(right));
4073 needMatchingVectors = false;
4074 binOp = spv::OpVectorTimesScalar;
4075 } else
4076 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004077 break;
4078 case glslang::EOpVectorTimesMatrix:
4079 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004080 binOp = spv::OpVectorTimesMatrix;
4081 break;
4082 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004083 binOp = spv::OpMatrixTimesVector;
4084 break;
4085 case glslang::EOpMatrixTimesScalar:
4086 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004087 binOp = spv::OpMatrixTimesScalar;
4088 break;
4089 case glslang::EOpMatrixTimesMatrix:
4090 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004091 binOp = spv::OpMatrixTimesMatrix;
4092 break;
4093 case glslang::EOpOuterProduct:
4094 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004095 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004096 break;
4097
4098 case glslang::EOpDiv:
4099 case glslang::EOpDivAssign:
4100 if (isFloat)
4101 binOp = spv::OpFDiv;
4102 else if (isUnsigned)
4103 binOp = spv::OpUDiv;
4104 else
4105 binOp = spv::OpSDiv;
4106 break;
4107 case glslang::EOpMod:
4108 case glslang::EOpModAssign:
4109 if (isFloat)
4110 binOp = spv::OpFMod;
4111 else if (isUnsigned)
4112 binOp = spv::OpUMod;
4113 else
4114 binOp = spv::OpSMod;
4115 break;
4116 case glslang::EOpRightShift:
4117 case glslang::EOpRightShiftAssign:
4118 if (isUnsigned)
4119 binOp = spv::OpShiftRightLogical;
4120 else
4121 binOp = spv::OpShiftRightArithmetic;
4122 break;
4123 case glslang::EOpLeftShift:
4124 case glslang::EOpLeftShiftAssign:
4125 binOp = spv::OpShiftLeftLogical;
4126 break;
4127 case glslang::EOpAnd:
4128 case glslang::EOpAndAssign:
4129 binOp = spv::OpBitwiseAnd;
4130 break;
4131 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004132 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004133 binOp = spv::OpLogicalAnd;
4134 break;
4135 case glslang::EOpInclusiveOr:
4136 case glslang::EOpInclusiveOrAssign:
4137 binOp = spv::OpBitwiseOr;
4138 break;
4139 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004140 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004141 binOp = spv::OpLogicalOr;
4142 break;
4143 case glslang::EOpExclusiveOr:
4144 case glslang::EOpExclusiveOrAssign:
4145 binOp = spv::OpBitwiseXor;
4146 break;
4147 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004148 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004149 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004150 break;
4151
4152 case glslang::EOpLessThan:
4153 case glslang::EOpGreaterThan:
4154 case glslang::EOpLessThanEqual:
4155 case glslang::EOpGreaterThanEqual:
4156 case glslang::EOpEqual:
4157 case glslang::EOpNotEqual:
4158 case glslang::EOpVectorEqual:
4159 case glslang::EOpVectorNotEqual:
4160 comparison = true;
4161 break;
4162 default:
4163 break;
4164 }
4165
John Kessenich7c1aa102015-10-15 13:29:11 -06004166 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004167 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004168 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07004169 if (builder.isMatrix(left) || builder.isMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004170 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004171
4172 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004173 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004174 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004175
qining25262b32016-05-06 17:25:16 -04004176 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004177 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004178 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004179 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004180 }
4181
4182 if (! comparison)
4183 return 0;
4184
John Kessenich7c1aa102015-10-15 13:29:11 -06004185 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004186
John Kessenich4583b612016-08-07 19:14:22 -06004187 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004188 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4189 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004190 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004191 return result;
4192 }
John Kessenich140f3df2015-06-26 16:58:36 -06004193
4194 switch (op) {
4195 case glslang::EOpLessThan:
4196 if (isFloat)
4197 binOp = spv::OpFOrdLessThan;
4198 else if (isUnsigned)
4199 binOp = spv::OpULessThan;
4200 else
4201 binOp = spv::OpSLessThan;
4202 break;
4203 case glslang::EOpGreaterThan:
4204 if (isFloat)
4205 binOp = spv::OpFOrdGreaterThan;
4206 else if (isUnsigned)
4207 binOp = spv::OpUGreaterThan;
4208 else
4209 binOp = spv::OpSGreaterThan;
4210 break;
4211 case glslang::EOpLessThanEqual:
4212 if (isFloat)
4213 binOp = spv::OpFOrdLessThanEqual;
4214 else if (isUnsigned)
4215 binOp = spv::OpULessThanEqual;
4216 else
4217 binOp = spv::OpSLessThanEqual;
4218 break;
4219 case glslang::EOpGreaterThanEqual:
4220 if (isFloat)
4221 binOp = spv::OpFOrdGreaterThanEqual;
4222 else if (isUnsigned)
4223 binOp = spv::OpUGreaterThanEqual;
4224 else
4225 binOp = spv::OpSGreaterThanEqual;
4226 break;
4227 case glslang::EOpEqual:
4228 case glslang::EOpVectorEqual:
4229 if (isFloat)
4230 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004231 else if (isBool)
4232 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004233 else
4234 binOp = spv::OpIEqual;
4235 break;
4236 case glslang::EOpNotEqual:
4237 case glslang::EOpVectorNotEqual:
4238 if (isFloat)
4239 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004240 else if (isBool)
4241 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004242 else
4243 binOp = spv::OpINotEqual;
4244 break;
4245 default:
4246 break;
4247 }
4248
qining25262b32016-05-06 17:25:16 -04004249 if (binOp != spv::OpNop) {
4250 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004251 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004252 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004253 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004254 }
John Kessenich140f3df2015-06-26 16:58:36 -06004255
4256 return 0;
4257}
4258
John Kessenich04bb8a02015-12-12 12:28:14 -07004259//
4260// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
4261// These can be any of:
4262//
4263// matrix * scalar
4264// scalar * matrix
4265// matrix * matrix linear algebraic
4266// matrix * vector
4267// vector * matrix
4268// matrix * matrix componentwise
4269// matrix op matrix op in {+, -, /}
4270// matrix op scalar op in {+, -, /}
4271// scalar op matrix op in {+, -, /}
4272//
John Kessenichead86222018-03-28 18:01:20 -06004273spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4274 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07004275{
4276 bool firstClass = true;
4277
4278 // First, handle first-class matrix operations (* and matrix/scalar)
4279 switch (op) {
4280 case spv::OpFDiv:
4281 if (builder.isMatrix(left) && builder.isScalar(right)) {
4282 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01004283 spv::Id resultType = builder.getTypeId(right);
4284 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07004285 op = spv::OpMatrixTimesScalar;
4286 } else
4287 firstClass = false;
4288 break;
4289 case spv::OpMatrixTimesScalar:
4290 if (builder.isMatrix(right))
4291 std::swap(left, right);
4292 assert(builder.isScalar(right));
4293 break;
4294 case spv::OpVectorTimesMatrix:
4295 assert(builder.isVector(left));
4296 assert(builder.isMatrix(right));
4297 break;
4298 case spv::OpMatrixTimesVector:
4299 assert(builder.isMatrix(left));
4300 assert(builder.isVector(right));
4301 break;
4302 case spv::OpMatrixTimesMatrix:
4303 assert(builder.isMatrix(left));
4304 assert(builder.isMatrix(right));
4305 break;
4306 default:
4307 firstClass = false;
4308 break;
4309 }
4310
qining25262b32016-05-06 17:25:16 -04004311 if (firstClass) {
4312 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004313 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004314 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004315 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004316 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004317
LoopDawg592860c2016-06-09 08:57:35 -06004318 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004319 // The result type of all of them is the same type as the (a) matrix operand.
4320 // The algorithm is to:
4321 // - break the matrix(es) into vectors
4322 // - smear any scalar to a vector
4323 // - do vector operations
4324 // - make a matrix out the vector results
4325 switch (op) {
4326 case spv::OpFAdd:
4327 case spv::OpFSub:
4328 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004329 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004330 case spv::OpFMul:
4331 {
4332 // one time set up...
4333 bool leftMat = builder.isMatrix(left);
4334 bool rightMat = builder.isMatrix(right);
4335 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4336 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4337 spv::Id scalarType = builder.getScalarTypeId(typeId);
4338 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4339 std::vector<spv::Id> results;
4340 spv::Id smearVec = spv::NoResult;
4341 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06004342 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004343 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06004344 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004345
4346 // do each vector op
4347 for (unsigned int c = 0; c < numCols; ++c) {
4348 std::vector<unsigned int> indexes;
4349 indexes.push_back(c);
4350 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4351 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004352 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06004353 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004354 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004355 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004356 }
4357
4358 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004359 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004360 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004361 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07004362 }
4363 default:
4364 assert(0);
4365 return spv::NoResult;
4366 }
4367}
4368
John Kessenichead86222018-03-28 18:01:20 -06004369spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
4370 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004371{
4372 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004373 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004374 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07004375 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4376 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004377
4378 switch (op) {
4379 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004380 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004381 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004382 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06004383 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004384 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004385 unaryOp = spv::OpSNegate;
4386 break;
4387
4388 case glslang::EOpLogicalNot:
4389 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004390 unaryOp = spv::OpLogicalNot;
4391 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004392 case glslang::EOpBitwiseNot:
4393 unaryOp = spv::OpNot;
4394 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004395
John Kessenich140f3df2015-06-26 16:58:36 -06004396 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004397 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004398 break;
4399 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004400 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004401 break;
4402 case glslang::EOpTranspose:
4403 unaryOp = spv::OpTranspose;
4404 break;
4405
4406 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004407 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004408 break;
4409 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004410 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004411 break;
4412 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004413 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004414 break;
4415 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004416 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004417 break;
4418 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004419 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004420 break;
4421 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004422 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004423 break;
4424 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004425 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004426 break;
4427 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004428 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004429 break;
4430
4431 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004432 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004433 break;
4434 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004435 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004436 break;
4437 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004438 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004439 break;
4440 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004441 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004442 break;
4443 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004444 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004445 break;
4446 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004447 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004448 break;
4449
4450 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004451 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004452 break;
4453 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004454 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004455 break;
4456
4457 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004458 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004459 break;
4460 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004461 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004462 break;
4463 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004464 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004465 break;
4466 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004467 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004468 break;
4469 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004470 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004471 break;
4472 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004473 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004474 break;
4475
4476 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004477 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004478 break;
4479 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004480 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004481 break;
4482 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004483 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004484 break;
4485 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004486 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004487 break;
4488 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004489 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004490 break;
4491 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004492 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004493 break;
4494
4495 case glslang::EOpIsNan:
4496 unaryOp = spv::OpIsNan;
4497 break;
4498 case glslang::EOpIsInf:
4499 unaryOp = spv::OpIsInf;
4500 break;
LoopDawg592860c2016-06-09 08:57:35 -06004501 case glslang::EOpIsFinite:
4502 unaryOp = spv::OpIsFinite;
4503 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004504
Rex Xucbc426e2015-12-15 16:03:10 +08004505 case glslang::EOpFloatBitsToInt:
4506 case glslang::EOpFloatBitsToUint:
4507 case glslang::EOpIntBitsToFloat:
4508 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004509 case glslang::EOpDoubleBitsToInt64:
4510 case glslang::EOpDoubleBitsToUint64:
4511 case glslang::EOpInt64BitsToDouble:
4512 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004513 case glslang::EOpFloat16BitsToInt16:
4514 case glslang::EOpFloat16BitsToUint16:
4515 case glslang::EOpInt16BitsToFloat16:
4516 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08004517 unaryOp = spv::OpBitcast;
4518 break;
4519
John Kessenich140f3df2015-06-26 16:58:36 -06004520 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004521 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004522 break;
4523 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004524 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004525 break;
4526 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004527 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004528 break;
4529 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004530 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004531 break;
4532 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004533 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004534 break;
4535 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004536 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004537 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004538 case glslang::EOpPackSnorm4x8:
4539 libCall = spv::GLSLstd450PackSnorm4x8;
4540 break;
4541 case glslang::EOpUnpackSnorm4x8:
4542 libCall = spv::GLSLstd450UnpackSnorm4x8;
4543 break;
4544 case glslang::EOpPackUnorm4x8:
4545 libCall = spv::GLSLstd450PackUnorm4x8;
4546 break;
4547 case glslang::EOpUnpackUnorm4x8:
4548 libCall = spv::GLSLstd450UnpackUnorm4x8;
4549 break;
4550 case glslang::EOpPackDouble2x32:
4551 libCall = spv::GLSLstd450PackDouble2x32;
4552 break;
4553 case glslang::EOpUnpackDouble2x32:
4554 libCall = spv::GLSLstd450UnpackDouble2x32;
4555 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004556
Rex Xu8ff43de2016-04-22 16:51:45 +08004557 case glslang::EOpPackInt2x32:
4558 case glslang::EOpUnpackInt2x32:
4559 case glslang::EOpPackUint2x32:
4560 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07004561 case glslang::EOpPack16:
4562 case glslang::EOpPack32:
4563 case glslang::EOpPack64:
4564 case glslang::EOpUnpack32:
4565 case glslang::EOpUnpack16:
4566 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08004567 case glslang::EOpPackInt2x16:
4568 case glslang::EOpUnpackInt2x16:
4569 case glslang::EOpPackUint2x16:
4570 case glslang::EOpUnpackUint2x16:
4571 case glslang::EOpPackInt4x16:
4572 case glslang::EOpUnpackInt4x16:
4573 case glslang::EOpPackUint4x16:
4574 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004575 case glslang::EOpPackFloat2x16:
4576 case glslang::EOpUnpackFloat2x16:
4577 unaryOp = spv::OpBitcast;
4578 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004579
John Kessenich140f3df2015-06-26 16:58:36 -06004580 case glslang::EOpDPdx:
4581 unaryOp = spv::OpDPdx;
4582 break;
4583 case glslang::EOpDPdy:
4584 unaryOp = spv::OpDPdy;
4585 break;
4586 case glslang::EOpFwidth:
4587 unaryOp = spv::OpFwidth;
4588 break;
4589 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004590 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004591 unaryOp = spv::OpDPdxFine;
4592 break;
4593 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004594 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004595 unaryOp = spv::OpDPdyFine;
4596 break;
4597 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004598 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004599 unaryOp = spv::OpFwidthFine;
4600 break;
4601 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004602 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004603 unaryOp = spv::OpDPdxCoarse;
4604 break;
4605 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004606 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004607 unaryOp = spv::OpDPdyCoarse;
4608 break;
4609 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004610 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004611 unaryOp = spv::OpFwidthCoarse;
4612 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004613 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004614 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004615 libCall = spv::GLSLstd450InterpolateAtCentroid;
4616 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004617 case glslang::EOpAny:
4618 unaryOp = spv::OpAny;
4619 break;
4620 case glslang::EOpAll:
4621 unaryOp = spv::OpAll;
4622 break;
4623
4624 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004625 if (isFloat)
4626 libCall = spv::GLSLstd450FAbs;
4627 else
4628 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004629 break;
4630 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004631 if (isFloat)
4632 libCall = spv::GLSLstd450FSign;
4633 else
4634 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004635 break;
4636
John Kessenichfc51d282015-08-19 13:34:18 -06004637 case glslang::EOpAtomicCounterIncrement:
4638 case glslang::EOpAtomicCounterDecrement:
4639 case glslang::EOpAtomicCounter:
4640 {
4641 // Handle all of the atomics in one place, in createAtomicOperation()
4642 std::vector<spv::Id> operands;
4643 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06004644 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004645 }
4646
John Kessenichfc51d282015-08-19 13:34:18 -06004647 case glslang::EOpBitFieldReverse:
4648 unaryOp = spv::OpBitReverse;
4649 break;
4650 case glslang::EOpBitCount:
4651 unaryOp = spv::OpBitCount;
4652 break;
4653 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004654 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004655 break;
4656 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004657 if (isUnsigned)
4658 libCall = spv::GLSLstd450FindUMsb;
4659 else
4660 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004661 break;
4662
Rex Xu574ab042016-04-14 16:53:07 +08004663 case glslang::EOpBallot:
4664 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004665 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004666 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004667 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004668#ifdef AMD_EXTENSIONS
4669 case glslang::EOpMinInvocations:
4670 case glslang::EOpMaxInvocations:
4671 case glslang::EOpAddInvocations:
4672 case glslang::EOpMinInvocationsNonUniform:
4673 case glslang::EOpMaxInvocationsNonUniform:
4674 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004675 case glslang::EOpMinInvocationsInclusiveScan:
4676 case glslang::EOpMaxInvocationsInclusiveScan:
4677 case glslang::EOpAddInvocationsInclusiveScan:
4678 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4679 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4680 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4681 case glslang::EOpMinInvocationsExclusiveScan:
4682 case glslang::EOpMaxInvocationsExclusiveScan:
4683 case glslang::EOpAddInvocationsExclusiveScan:
4684 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4685 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4686 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004687#endif
Rex Xu51596642016-09-21 18:56:12 +08004688 {
4689 std::vector<spv::Id> operands;
4690 operands.push_back(operand);
4691 return createInvocationsOperation(op, typeId, operands, typeProxy);
4692 }
John Kessenich66011cb2018-03-06 16:12:04 -07004693 case glslang::EOpSubgroupAll:
4694 case glslang::EOpSubgroupAny:
4695 case glslang::EOpSubgroupAllEqual:
4696 case glslang::EOpSubgroupBroadcastFirst:
4697 case glslang::EOpSubgroupBallot:
4698 case glslang::EOpSubgroupInverseBallot:
4699 case glslang::EOpSubgroupBallotBitCount:
4700 case glslang::EOpSubgroupBallotInclusiveBitCount:
4701 case glslang::EOpSubgroupBallotExclusiveBitCount:
4702 case glslang::EOpSubgroupBallotFindLSB:
4703 case glslang::EOpSubgroupBallotFindMSB:
4704 case glslang::EOpSubgroupAdd:
4705 case glslang::EOpSubgroupMul:
4706 case glslang::EOpSubgroupMin:
4707 case glslang::EOpSubgroupMax:
4708 case glslang::EOpSubgroupAnd:
4709 case glslang::EOpSubgroupOr:
4710 case glslang::EOpSubgroupXor:
4711 case glslang::EOpSubgroupInclusiveAdd:
4712 case glslang::EOpSubgroupInclusiveMul:
4713 case glslang::EOpSubgroupInclusiveMin:
4714 case glslang::EOpSubgroupInclusiveMax:
4715 case glslang::EOpSubgroupInclusiveAnd:
4716 case glslang::EOpSubgroupInclusiveOr:
4717 case glslang::EOpSubgroupInclusiveXor:
4718 case glslang::EOpSubgroupExclusiveAdd:
4719 case glslang::EOpSubgroupExclusiveMul:
4720 case glslang::EOpSubgroupExclusiveMin:
4721 case glslang::EOpSubgroupExclusiveMax:
4722 case glslang::EOpSubgroupExclusiveAnd:
4723 case glslang::EOpSubgroupExclusiveOr:
4724 case glslang::EOpSubgroupExclusiveXor:
4725 case glslang::EOpSubgroupQuadSwapHorizontal:
4726 case glslang::EOpSubgroupQuadSwapVertical:
4727 case glslang::EOpSubgroupQuadSwapDiagonal: {
4728 std::vector<spv::Id> operands;
4729 operands.push_back(operand);
4730 return createSubgroupOperation(op, typeId, operands, typeProxy);
4731 }
Rex Xu9d93a232016-05-05 12:30:44 +08004732#ifdef AMD_EXTENSIONS
4733 case glslang::EOpMbcnt:
4734 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4735 libCall = spv::MbcntAMD;
4736 break;
4737
4738 case glslang::EOpCubeFaceIndex:
4739 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4740 libCall = spv::CubeFaceIndexAMD;
4741 break;
4742
4743 case glslang::EOpCubeFaceCoord:
4744 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4745 libCall = spv::CubeFaceCoordAMD;
4746 break;
4747#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05004748#ifdef NV_EXTENSIONS
4749 case glslang::EOpSubgroupPartition:
4750 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
4751 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
4752 unaryOp = spv::OpGroupNonUniformPartitionNV;
4753 break;
4754#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004755 default:
4756 return 0;
4757 }
4758
4759 spv::Id id;
4760 if (libCall >= 0) {
4761 std::vector<spv::Id> args;
4762 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004763 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004764 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004765 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004766 }
John Kessenich140f3df2015-06-26 16:58:36 -06004767
John Kessenichead86222018-03-28 18:01:20 -06004768 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004769 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004770 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004771}
4772
John Kessenich7a53f762016-01-20 11:19:27 -07004773// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06004774spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4775 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07004776{
4777 // Handle unary operations vector by vector.
4778 // The result type is the same type as the original type.
4779 // The algorithm is to:
4780 // - break the matrix into vectors
4781 // - apply the operation to each vector
4782 // - make a matrix out the vector results
4783
4784 // get the types sorted out
4785 int numCols = builder.getNumColumns(operand);
4786 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004787 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4788 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004789 std::vector<spv::Id> results;
4790
4791 // do each vector op
4792 for (int c = 0; c < numCols; ++c) {
4793 std::vector<unsigned int> indexes;
4794 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004795 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4796 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06004797 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004798 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004799 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004800 }
4801
4802 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004803 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004804 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004805 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07004806}
4807
John Kessenich66011cb2018-03-06 16:12:04 -07004808spv::Id TGlslangToSpvTraverser::createConversionOperation(glslang::TOperator op, spv::Id operand, int vectorSize)
4809{
4810 spv::Op convOp = spv::OpNop;
4811 spv::Id type = 0;
4812
4813 spv::Id result = 0;
4814
4815 switch(op) {
4816 case glslang::EOpConvInt8ToUint16:
4817 convOp = spv::OpSConvert;
4818 type = builder.makeIntType(16);
4819 break;
4820 case glslang::EOpConvInt8ToUint:
4821 convOp = spv::OpSConvert;
4822 type = builder.makeIntType(32);
4823 break;
4824 case glslang::EOpConvInt8ToUint64:
4825 convOp = spv::OpSConvert;
4826 type = builder.makeIntType(64);
4827 break;
4828 case glslang::EOpConvInt16ToUint8:
4829 convOp = spv::OpSConvert;
4830 type = builder.makeIntType(8);
4831 break;
4832 case glslang::EOpConvInt16ToUint:
4833 convOp = spv::OpSConvert;
4834 type = builder.makeIntType(32);
4835 break;
4836 case glslang::EOpConvInt16ToUint64:
4837 convOp = spv::OpSConvert;
4838 type = builder.makeIntType(64);
4839 break;
4840 case glslang::EOpConvIntToUint8:
4841 convOp = spv::OpSConvert;
4842 type = builder.makeIntType(8);
4843 break;
4844 case glslang::EOpConvIntToUint16:
4845 convOp = spv::OpSConvert;
4846 type = builder.makeIntType(16);
4847 break;
4848 case glslang::EOpConvIntToUint64:
4849 convOp = spv::OpSConvert;
4850 type = builder.makeIntType(64);
4851 break;
4852 case glslang::EOpConvInt64ToUint8:
4853 convOp = spv::OpSConvert;
4854 type = builder.makeIntType(8);
4855 break;
4856 case glslang::EOpConvInt64ToUint16:
4857 convOp = spv::OpSConvert;
4858 type = builder.makeIntType(16);
4859 break;
4860 case glslang::EOpConvInt64ToUint:
4861 convOp = spv::OpSConvert;
4862 type = builder.makeIntType(32);
4863 break;
4864 case glslang::EOpConvUint8ToInt16:
4865 convOp = spv::OpUConvert;
4866 type = builder.makeIntType(16);
4867 break;
4868 case glslang::EOpConvUint8ToInt:
4869 convOp = spv::OpUConvert;
4870 type = builder.makeIntType(32);
4871 break;
4872 case glslang::EOpConvUint8ToInt64:
4873 convOp = spv::OpUConvert;
4874 type = builder.makeIntType(64);
4875 break;
4876 case glslang::EOpConvUint16ToInt8:
4877 convOp = spv::OpUConvert;
4878 type = builder.makeIntType(8);
4879 break;
4880 case glslang::EOpConvUint16ToInt:
4881 convOp = spv::OpUConvert;
4882 type = builder.makeIntType(32);
4883 break;
4884 case glslang::EOpConvUint16ToInt64:
4885 convOp = spv::OpUConvert;
4886 type = builder.makeIntType(64);
4887 break;
4888 case glslang::EOpConvUintToInt8:
4889 convOp = spv::OpUConvert;
4890 type = builder.makeIntType(8);
4891 break;
4892 case glslang::EOpConvUintToInt16:
4893 convOp = spv::OpUConvert;
4894 type = builder.makeIntType(16);
4895 break;
4896 case glslang::EOpConvUintToInt64:
4897 convOp = spv::OpUConvert;
4898 type = builder.makeIntType(64);
4899 break;
4900 case glslang::EOpConvUint64ToInt8:
4901 convOp = spv::OpUConvert;
4902 type = builder.makeIntType(8);
4903 break;
4904 case glslang::EOpConvUint64ToInt16:
4905 convOp = spv::OpUConvert;
4906 type = builder.makeIntType(16);
4907 break;
4908 case glslang::EOpConvUint64ToInt:
4909 convOp = spv::OpUConvert;
4910 type = builder.makeIntType(32);
4911 break;
4912
4913 default:
4914 assert(false && "Default missing");
4915 break;
4916 }
4917
4918 if (vectorSize > 0)
4919 type = builder.makeVectorType(type, vectorSize);
4920
4921 result = builder.createUnaryOp(convOp, type, operand);
4922 return result;
4923}
4924
John Kessenichead86222018-03-28 18:01:20 -06004925spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
4926 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004927{
4928 spv::Op convOp = spv::OpNop;
4929 spv::Id zero = 0;
4930 spv::Id one = 0;
4931
4932 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4933
4934 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07004935 case glslang::EOpConvInt8ToBool:
4936 case glslang::EOpConvUint8ToBool:
4937 zero = builder.makeUint8Constant(0);
4938 zero = makeSmearedConstant(zero, vectorSize);
4939 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08004940 case glslang::EOpConvInt16ToBool:
4941 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07004942 zero = builder.makeUint16Constant(0);
4943 zero = makeSmearedConstant(zero, vectorSize);
4944 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4945 case glslang::EOpConvIntToBool:
4946 case glslang::EOpConvUintToBool:
4947 zero = builder.makeUintConstant(0);
4948 zero = makeSmearedConstant(zero, vectorSize);
4949 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4950 case glslang::EOpConvInt64ToBool:
4951 case glslang::EOpConvUint64ToBool:
4952 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004953 zero = makeSmearedConstant(zero, vectorSize);
4954 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4955
4956 case glslang::EOpConvFloatToBool:
4957 zero = builder.makeFloatConstant(0.0F);
4958 zero = makeSmearedConstant(zero, vectorSize);
4959 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4960
4961 case glslang::EOpConvDoubleToBool:
4962 zero = builder.makeDoubleConstant(0.0);
4963 zero = makeSmearedConstant(zero, vectorSize);
4964 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4965
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004966 case glslang::EOpConvFloat16ToBool:
4967 zero = builder.makeFloat16Constant(0.0F);
4968 zero = makeSmearedConstant(zero, vectorSize);
4969 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004970
John Kessenich140f3df2015-06-26 16:58:36 -06004971 case glslang::EOpConvBoolToFloat:
4972 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004973 zero = builder.makeFloatConstant(0.0F);
4974 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004975 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004976
John Kessenich140f3df2015-06-26 16:58:36 -06004977 case glslang::EOpConvBoolToDouble:
4978 convOp = spv::OpSelect;
4979 zero = builder.makeDoubleConstant(0.0);
4980 one = builder.makeDoubleConstant(1.0);
4981 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004982
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004983 case glslang::EOpConvBoolToFloat16:
4984 convOp = spv::OpSelect;
4985 zero = builder.makeFloat16Constant(0.0F);
4986 one = builder.makeFloat16Constant(1.0F);
4987 break;
John Kessenich66011cb2018-03-06 16:12:04 -07004988
4989 case glslang::EOpConvBoolToInt8:
4990 zero = builder.makeInt8Constant(0);
4991 one = builder.makeInt8Constant(1);
4992 convOp = spv::OpSelect;
4993 break;
4994
4995 case glslang::EOpConvBoolToUint8:
4996 zero = builder.makeUint8Constant(0);
4997 one = builder.makeUint8Constant(1);
4998 convOp = spv::OpSelect;
4999 break;
5000
5001 case glslang::EOpConvBoolToInt16:
5002 zero = builder.makeInt16Constant(0);
5003 one = builder.makeInt16Constant(1);
5004 convOp = spv::OpSelect;
5005 break;
5006
5007 case glslang::EOpConvBoolToUint16:
5008 zero = builder.makeUint16Constant(0);
5009 one = builder.makeUint16Constant(1);
5010 convOp = spv::OpSelect;
5011 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005012
John Kessenich140f3df2015-06-26 16:58:36 -06005013 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005014 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005015 if (op == glslang::EOpConvBoolToInt64)
5016 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005017 else
5018 zero = builder.makeIntConstant(0);
5019
5020 if (op == glslang::EOpConvBoolToInt64)
5021 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005022 else
5023 one = builder.makeIntConstant(1);
5024
John Kessenich140f3df2015-06-26 16:58:36 -06005025 convOp = spv::OpSelect;
5026 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005027
John Kessenich140f3df2015-06-26 16:58:36 -06005028 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005029 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005030 if (op == glslang::EOpConvBoolToUint64)
5031 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005032 else
5033 zero = builder.makeUintConstant(0);
5034
5035 if (op == glslang::EOpConvBoolToUint64)
5036 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005037 else
5038 one = builder.makeUintConstant(1);
5039
John Kessenich140f3df2015-06-26 16:58:36 -06005040 convOp = spv::OpSelect;
5041 break;
5042
John Kessenich66011cb2018-03-06 16:12:04 -07005043 case glslang::EOpConvInt8ToFloat16:
5044 case glslang::EOpConvInt8ToFloat:
5045 case glslang::EOpConvInt8ToDouble:
5046 case glslang::EOpConvInt16ToFloat16:
5047 case glslang::EOpConvInt16ToFloat:
5048 case glslang::EOpConvInt16ToDouble:
5049 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005050 case glslang::EOpConvIntToFloat:
5051 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005052 case glslang::EOpConvInt64ToFloat:
5053 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005054 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005055 convOp = spv::OpConvertSToF;
5056 break;
5057
John Kessenich66011cb2018-03-06 16:12:04 -07005058 case glslang::EOpConvUint8ToFloat16:
5059 case glslang::EOpConvUint8ToFloat:
5060 case glslang::EOpConvUint8ToDouble:
5061 case glslang::EOpConvUint16ToFloat16:
5062 case glslang::EOpConvUint16ToFloat:
5063 case glslang::EOpConvUint16ToDouble:
5064 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005065 case glslang::EOpConvUintToFloat:
5066 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005067 case glslang::EOpConvUint64ToFloat:
5068 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005069 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005070 convOp = spv::OpConvertUToF;
5071 break;
5072
5073 case glslang::EOpConvDoubleToFloat:
5074 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005075 case glslang::EOpConvDoubleToFloat16:
5076 case glslang::EOpConvFloat16ToDouble:
5077 case glslang::EOpConvFloatToFloat16:
5078 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005079 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005080 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005081 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005082 break;
5083
John Kessenich66011cb2018-03-06 16:12:04 -07005084 case glslang::EOpConvFloat16ToInt8:
5085 case glslang::EOpConvFloatToInt8:
5086 case glslang::EOpConvDoubleToInt8:
5087 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005088 case glslang::EOpConvFloatToInt16:
5089 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005090 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005091 case glslang::EOpConvFloatToInt:
5092 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005093 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005094 case glslang::EOpConvFloatToInt64:
5095 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005096 convOp = spv::OpConvertFToS;
5097 break;
5098
John Kessenich66011cb2018-03-06 16:12:04 -07005099 case glslang::EOpConvUint8ToInt8:
5100 case glslang::EOpConvInt8ToUint8:
5101 case glslang::EOpConvUint16ToInt16:
5102 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005103 case glslang::EOpConvUintToInt:
5104 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005105 case glslang::EOpConvUint64ToInt64:
5106 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005107 if (builder.isInSpecConstCodeGenMode()) {
5108 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005109 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5110 zero = builder.makeUint8Constant(0);
5111 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005112 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005113 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5114 zero = builder.makeUint64Constant(0);
5115 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005116 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005117 }
qining189b2032016-04-12 23:16:20 -04005118 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005119 // Use OpIAdd, instead of OpBitcast to do the conversion when
5120 // generating for OpSpecConstantOp instruction.
5121 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5122 }
5123 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005124 convOp = spv::OpBitcast;
5125 break;
5126
John Kessenich66011cb2018-03-06 16:12:04 -07005127 case glslang::EOpConvFloat16ToUint8:
5128 case glslang::EOpConvFloatToUint8:
5129 case glslang::EOpConvDoubleToUint8:
5130 case glslang::EOpConvFloat16ToUint16:
5131 case glslang::EOpConvFloatToUint16:
5132 case glslang::EOpConvDoubleToUint16:
5133 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005134 case glslang::EOpConvFloatToUint:
5135 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005136 case glslang::EOpConvFloatToUint64:
5137 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005138 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005139 convOp = spv::OpConvertFToU;
5140 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005141
John Kessenich66011cb2018-03-06 16:12:04 -07005142 case glslang::EOpConvInt8ToInt16:
5143 case glslang::EOpConvInt8ToInt:
5144 case glslang::EOpConvInt8ToInt64:
5145 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005146 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005147 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005148 case glslang::EOpConvIntToInt8:
5149 case glslang::EOpConvIntToInt16:
5150 case glslang::EOpConvIntToInt64:
5151 case glslang::EOpConvInt64ToInt8:
5152 case glslang::EOpConvInt64ToInt16:
5153 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005154 convOp = spv::OpSConvert;
5155 break;
5156
John Kessenich66011cb2018-03-06 16:12:04 -07005157 case glslang::EOpConvUint8ToUint16:
5158 case glslang::EOpConvUint8ToUint:
5159 case glslang::EOpConvUint8ToUint64:
5160 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005161 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005162 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005163 case glslang::EOpConvUintToUint8:
5164 case glslang::EOpConvUintToUint16:
5165 case glslang::EOpConvUintToUint64:
5166 case glslang::EOpConvUint64ToUint8:
5167 case glslang::EOpConvUint64ToUint16:
5168 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005169 convOp = spv::OpUConvert;
5170 break;
5171
John Kessenich66011cb2018-03-06 16:12:04 -07005172 case glslang::EOpConvInt8ToUint16:
5173 case glslang::EOpConvInt8ToUint:
5174 case glslang::EOpConvInt8ToUint64:
5175 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005176 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005177 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005178 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005179 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005180 case glslang::EOpConvIntToUint64:
5181 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005182 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005183 case glslang::EOpConvInt64ToUint:
5184 case glslang::EOpConvUint8ToInt16:
5185 case glslang::EOpConvUint8ToInt:
5186 case glslang::EOpConvUint8ToInt64:
5187 case glslang::EOpConvUint16ToInt8:
5188 case glslang::EOpConvUint16ToInt:
5189 case glslang::EOpConvUint16ToInt64:
5190 case glslang::EOpConvUintToInt8:
5191 case glslang::EOpConvUintToInt16:
5192 case glslang::EOpConvUintToInt64:
5193 case glslang::EOpConvUint64ToInt8:
5194 case glslang::EOpConvUint64ToInt16:
5195 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005196 // OpSConvert/OpUConvert + OpBitCast
John Kessenich66011cb2018-03-06 16:12:04 -07005197 operand = createConversionOperation(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005198
5199 if (builder.isInSpecConstCodeGenMode()) {
5200 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005201 switch(op) {
5202 case glslang::EOpConvInt16ToUint8:
5203 case glslang::EOpConvIntToUint8:
5204 case glslang::EOpConvInt64ToUint8:
5205 case glslang::EOpConvUint16ToInt8:
5206 case glslang::EOpConvUintToInt8:
5207 case glslang::EOpConvUint64ToInt8:
5208 zero = builder.makeUint8Constant(0);
5209 break;
5210 case glslang::EOpConvInt8ToUint16:
5211 case glslang::EOpConvIntToUint16:
5212 case glslang::EOpConvInt64ToUint16:
5213 case glslang::EOpConvUint8ToInt16:
5214 case glslang::EOpConvUintToInt16:
5215 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005216 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005217 break;
5218 case glslang::EOpConvInt8ToUint:
5219 case glslang::EOpConvInt16ToUint:
5220 case glslang::EOpConvInt64ToUint:
5221 case glslang::EOpConvUint8ToInt:
5222 case glslang::EOpConvUint16ToInt:
5223 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005224 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005225 break;
5226 case glslang::EOpConvInt8ToUint64:
5227 case glslang::EOpConvInt16ToUint64:
5228 case glslang::EOpConvIntToUint64:
5229 case glslang::EOpConvUint8ToInt64:
5230 case glslang::EOpConvUint16ToInt64:
5231 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005232 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005233 break;
5234 default:
5235 assert(false && "Default missing");
5236 break;
5237 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005238 zero = makeSmearedConstant(zero, vectorSize);
5239 // Use OpIAdd, instead of OpBitcast to do the conversion when
5240 // generating for OpSpecConstantOp instruction.
5241 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5242 }
5243 // For normal run-time conversion instruction, use OpBitcast.
5244 convOp = spv::OpBitcast;
5245 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005246 default:
5247 break;
5248 }
5249
5250 spv::Id result = 0;
5251 if (convOp == spv::OpNop)
5252 return result;
5253
5254 if (convOp == spv::OpSelect) {
5255 zero = makeSmearedConstant(zero, vectorSize);
5256 one = makeSmearedConstant(one, vectorSize);
5257 result = builder.createTriOp(convOp, destType, operand, one, zero);
5258 } else
5259 result = builder.createUnaryOp(convOp, destType, operand);
5260
John Kessenichead86222018-03-28 18:01:20 -06005261 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005262 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005263 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06005264}
5265
5266spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
5267{
5268 if (vectorSize == 0)
5269 return constant;
5270
5271 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
5272 std::vector<spv::Id> components;
5273 for (int c = 0; c < vectorSize; ++c)
5274 components.push_back(constant);
5275 return builder.makeCompositeConstant(vectorTypeId, components);
5276}
5277
John Kessenich426394d2015-07-23 10:22:48 -06005278// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07005279spv::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 -06005280{
5281 spv::Op opCode = spv::OpNop;
5282
5283 switch (op) {
5284 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08005285 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005286 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06005287 opCode = spv::OpAtomicIAdd;
5288 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06005289 case glslang::EOpAtomicCounterSubtract:
5290 opCode = spv::OpAtomicISub;
5291 break;
John Kessenich426394d2015-07-23 10:22:48 -06005292 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08005293 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005294 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08005295 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06005296 break;
5297 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08005298 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005299 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08005300 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06005301 break;
5302 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08005303 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005304 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06005305 opCode = spv::OpAtomicAnd;
5306 break;
5307 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08005308 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005309 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06005310 opCode = spv::OpAtomicOr;
5311 break;
5312 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08005313 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005314 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06005315 opCode = spv::OpAtomicXor;
5316 break;
5317 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08005318 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005319 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06005320 opCode = spv::OpAtomicExchange;
5321 break;
5322 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08005323 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005324 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06005325 opCode = spv::OpAtomicCompareExchange;
5326 break;
5327 case glslang::EOpAtomicCounterIncrement:
5328 opCode = spv::OpAtomicIIncrement;
5329 break;
5330 case glslang::EOpAtomicCounterDecrement:
5331 opCode = spv::OpAtomicIDecrement;
5332 break;
5333 case glslang::EOpAtomicCounter:
5334 opCode = spv::OpAtomicLoad;
5335 break;
5336 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005337 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06005338 break;
5339 }
5340
Rex Xue8fe8b02017-09-26 15:42:56 +08005341 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
5342 builder.addCapability(spv::CapabilityInt64Atomics);
5343
John Kessenich426394d2015-07-23 10:22:48 -06005344 // Sort out the operands
5345 // - mapping from glslang -> SPV
5346 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06005347 // - compare-exchange swaps the value and comparator
5348 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06005349 // - EOpAtomicCounterDecrement needs a post decrement
John Kessenich426394d2015-07-23 10:22:48 -06005350 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
5351 auto opIt = operands.begin(); // walk the glslang operands
5352 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08005353 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
5354 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
5355 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08005356 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
5357 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08005358 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06005359 spvAtomicOperands.push_back(*(opIt + 1));
5360 spvAtomicOperands.push_back(*opIt);
5361 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08005362 }
John Kessenich426394d2015-07-23 10:22:48 -06005363
John Kessenich3e60a6f2015-09-14 22:45:16 -06005364 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06005365 for (; opIt != operands.end(); ++opIt)
5366 spvAtomicOperands.push_back(*opIt);
5367
John Kessenich48d6e792017-10-06 21:21:48 -06005368 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
5369
5370 // GLSL and HLSL atomic-counter decrement return post-decrement value,
5371 // while SPIR-V returns pre-decrement value. Translate between these semantics.
5372 if (op == glslang::EOpAtomicCounterDecrement)
5373 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
5374
5375 return resultId;
John Kessenich426394d2015-07-23 10:22:48 -06005376}
5377
John Kessenich91cef522016-05-05 16:45:40 -06005378// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08005379spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06005380{
John Kessenich66011cb2018-03-06 16:12:04 -07005381 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5382 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08005383
Rex Xu51596642016-09-21 18:56:12 +08005384 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08005385 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08005386 spv::GroupOperation groupOperation = spv::GroupOperationMax;
5387
chaocf200da82016-12-20 12:44:35 -08005388 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
5389 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08005390 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
5391 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005392 } else if (op == glslang::EOpAnyInvocation ||
5393 op == glslang::EOpAllInvocations ||
5394 op == glslang::EOpAllInvocationsEqual) {
5395 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
5396 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08005397 } else {
5398 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04005399#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08005400 if (op == glslang::EOpMinInvocationsNonUniform ||
5401 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08005402 op == glslang::EOpAddInvocationsNonUniform ||
5403 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5404 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5405 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
5406 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
5407 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
5408 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08005409 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04005410#endif
Rex Xu51596642016-09-21 18:56:12 +08005411
5412 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08005413#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08005414 switch (op) {
5415 case glslang::EOpMinInvocations:
5416 case glslang::EOpMaxInvocations:
5417 case glslang::EOpAddInvocations:
5418 case glslang::EOpMinInvocationsNonUniform:
5419 case glslang::EOpMaxInvocationsNonUniform:
5420 case glslang::EOpAddInvocationsNonUniform:
5421 groupOperation = spv::GroupOperationReduce;
5422 spvGroupOperands.push_back(groupOperation);
5423 break;
5424 case glslang::EOpMinInvocationsInclusiveScan:
5425 case glslang::EOpMaxInvocationsInclusiveScan:
5426 case glslang::EOpAddInvocationsInclusiveScan:
5427 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5428 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5429 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5430 groupOperation = spv::GroupOperationInclusiveScan;
5431 spvGroupOperands.push_back(groupOperation);
5432 break;
5433 case glslang::EOpMinInvocationsExclusiveScan:
5434 case glslang::EOpMaxInvocationsExclusiveScan:
5435 case glslang::EOpAddInvocationsExclusiveScan:
5436 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5437 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5438 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5439 groupOperation = spv::GroupOperationExclusiveScan;
5440 spvGroupOperands.push_back(groupOperation);
5441 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07005442 default:
5443 break;
Rex Xu430ef402016-10-14 17:22:23 +08005444 }
Rex Xu9d93a232016-05-05 12:30:44 +08005445#endif
Rex Xu51596642016-09-21 18:56:12 +08005446 }
5447
5448 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
5449 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06005450
5451 switch (op) {
5452 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005453 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08005454 break;
John Kessenich91cef522016-05-05 16:45:40 -06005455 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005456 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08005457 break;
John Kessenich91cef522016-05-05 16:45:40 -06005458 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005459 opCode = spv::OpSubgroupAllEqualKHR;
5460 break;
Rex Xu51596642016-09-21 18:56:12 +08005461 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08005462 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08005463 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005464 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005465 break;
5466 case glslang::EOpReadFirstInvocation:
5467 opCode = spv::OpSubgroupFirstInvocationKHR;
5468 break;
5469 case glslang::EOpBallot:
5470 {
5471 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
5472 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
5473 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
5474 //
5475 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
5476 //
5477 spv::Id uintType = builder.makeUintType(32);
5478 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
5479 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
5480
5481 std::vector<spv::Id> components;
5482 components.push_back(builder.createCompositeExtract(result, uintType, 0));
5483 components.push_back(builder.createCompositeExtract(result, uintType, 1));
5484
5485 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
5486 return builder.createUnaryOp(spv::OpBitcast, typeId,
5487 builder.createCompositeConstruct(uvec2Type, components));
5488 }
5489
Rex Xu9d93a232016-05-05 12:30:44 +08005490#ifdef AMD_EXTENSIONS
5491 case glslang::EOpMinInvocations:
5492 case glslang::EOpMaxInvocations:
5493 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08005494 case glslang::EOpMinInvocationsInclusiveScan:
5495 case glslang::EOpMaxInvocationsInclusiveScan:
5496 case glslang::EOpAddInvocationsInclusiveScan:
5497 case glslang::EOpMinInvocationsExclusiveScan:
5498 case glslang::EOpMaxInvocationsExclusiveScan:
5499 case glslang::EOpAddInvocationsExclusiveScan:
5500 if (op == glslang::EOpMinInvocations ||
5501 op == glslang::EOpMinInvocationsInclusiveScan ||
5502 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005503 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005504 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005505 else {
5506 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005507 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005508 else
Rex Xu51596642016-09-21 18:56:12 +08005509 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005510 }
Rex Xu430ef402016-10-14 17:22:23 +08005511 } else if (op == glslang::EOpMaxInvocations ||
5512 op == glslang::EOpMaxInvocationsInclusiveScan ||
5513 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005514 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005515 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005516 else {
5517 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005518 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005519 else
Rex Xu51596642016-09-21 18:56:12 +08005520 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005521 }
5522 } else {
5523 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005524 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005525 else
Rex Xu51596642016-09-21 18:56:12 +08005526 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005527 }
5528
Rex Xu2bbbe062016-08-23 15:41:05 +08005529 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005530 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005531
5532 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005533 case glslang::EOpMinInvocationsNonUniform:
5534 case glslang::EOpMaxInvocationsNonUniform:
5535 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005536 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5537 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5538 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5539 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5540 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5541 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5542 if (op == glslang::EOpMinInvocationsNonUniform ||
5543 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5544 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005545 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005546 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005547 else {
5548 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005549 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005550 else
Rex Xu51596642016-09-21 18:56:12 +08005551 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005552 }
5553 }
Rex Xu430ef402016-10-14 17:22:23 +08005554 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5555 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5556 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005557 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005558 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005559 else {
5560 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005561 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005562 else
Rex Xu51596642016-09-21 18:56:12 +08005563 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005564 }
5565 }
5566 else {
5567 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005568 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005569 else
Rex Xu51596642016-09-21 18:56:12 +08005570 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005571 }
5572
Rex Xu2bbbe062016-08-23 15:41:05 +08005573 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005574 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005575
5576 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005577#endif
John Kessenich91cef522016-05-05 16:45:40 -06005578 default:
5579 logger->missingFunctionality("invocation operation");
5580 return spv::NoResult;
5581 }
Rex Xu51596642016-09-21 18:56:12 +08005582
5583 assert(opCode != spv::OpNop);
5584 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005585}
5586
Rex Xu2bbbe062016-08-23 15:41:05 +08005587// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005588spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005589{
Rex Xub7072052016-09-26 15:53:40 +08005590#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005591 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5592 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005593 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005594 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005595 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5596 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5597 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005598#else
5599 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5600 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005601 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5602 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005603#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005604
5605 // Handle group invocation operations scalar by scalar.
5606 // The result type is the same type as the original type.
5607 // The algorithm is to:
5608 // - break the vector into scalars
5609 // - apply the operation to each scalar
5610 // - make a vector out the scalar results
5611
5612 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005613 int numComponents = builder.getNumComponents(operands[0]);
5614 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005615 std::vector<spv::Id> results;
5616
5617 // do each scalar op
5618 for (int comp = 0; comp < numComponents; ++comp) {
5619 std::vector<unsigned int> indexes;
5620 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005621 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005622 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005623 if (op == spv::OpSubgroupReadInvocationKHR) {
5624 spvGroupOperands.push_back(scalar);
5625 spvGroupOperands.push_back(operands[1]);
5626 } else if (op == spv::OpGroupBroadcast) {
5627 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005628 spvGroupOperands.push_back(scalar);
5629 spvGroupOperands.push_back(operands[1]);
5630 } else {
chaocf200da82016-12-20 12:44:35 -08005631 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005632 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005633 spvGroupOperands.push_back(scalar);
5634 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005635
Rex Xub7072052016-09-26 15:53:40 +08005636 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005637 }
5638
5639 // put the pieces together
5640 return builder.createCompositeConstruct(typeId, results);
5641}
Rex Xu2bbbe062016-08-23 15:41:05 +08005642
John Kessenich66011cb2018-03-06 16:12:04 -07005643// Create subgroup invocation operations.
5644spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
5645{
5646 // Add the required capabilities.
5647 switch (op) {
5648 case glslang::EOpSubgroupElect:
5649 builder.addCapability(spv::CapabilityGroupNonUniform);
5650 break;
5651 case glslang::EOpSubgroupAll:
5652 case glslang::EOpSubgroupAny:
5653 case glslang::EOpSubgroupAllEqual:
5654 builder.addCapability(spv::CapabilityGroupNonUniform);
5655 builder.addCapability(spv::CapabilityGroupNonUniformVote);
5656 break;
5657 case glslang::EOpSubgroupBroadcast:
5658 case glslang::EOpSubgroupBroadcastFirst:
5659 case glslang::EOpSubgroupBallot:
5660 case glslang::EOpSubgroupInverseBallot:
5661 case glslang::EOpSubgroupBallotBitExtract:
5662 case glslang::EOpSubgroupBallotBitCount:
5663 case glslang::EOpSubgroupBallotInclusiveBitCount:
5664 case glslang::EOpSubgroupBallotExclusiveBitCount:
5665 case glslang::EOpSubgroupBallotFindLSB:
5666 case glslang::EOpSubgroupBallotFindMSB:
5667 builder.addCapability(spv::CapabilityGroupNonUniform);
5668 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
5669 break;
5670 case glslang::EOpSubgroupShuffle:
5671 case glslang::EOpSubgroupShuffleXor:
5672 builder.addCapability(spv::CapabilityGroupNonUniform);
5673 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
5674 break;
5675 case glslang::EOpSubgroupShuffleUp:
5676 case glslang::EOpSubgroupShuffleDown:
5677 builder.addCapability(spv::CapabilityGroupNonUniform);
5678 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
5679 break;
5680 case glslang::EOpSubgroupAdd:
5681 case glslang::EOpSubgroupMul:
5682 case glslang::EOpSubgroupMin:
5683 case glslang::EOpSubgroupMax:
5684 case glslang::EOpSubgroupAnd:
5685 case glslang::EOpSubgroupOr:
5686 case glslang::EOpSubgroupXor:
5687 case glslang::EOpSubgroupInclusiveAdd:
5688 case glslang::EOpSubgroupInclusiveMul:
5689 case glslang::EOpSubgroupInclusiveMin:
5690 case glslang::EOpSubgroupInclusiveMax:
5691 case glslang::EOpSubgroupInclusiveAnd:
5692 case glslang::EOpSubgroupInclusiveOr:
5693 case glslang::EOpSubgroupInclusiveXor:
5694 case glslang::EOpSubgroupExclusiveAdd:
5695 case glslang::EOpSubgroupExclusiveMul:
5696 case glslang::EOpSubgroupExclusiveMin:
5697 case glslang::EOpSubgroupExclusiveMax:
5698 case glslang::EOpSubgroupExclusiveAnd:
5699 case glslang::EOpSubgroupExclusiveOr:
5700 case glslang::EOpSubgroupExclusiveXor:
5701 builder.addCapability(spv::CapabilityGroupNonUniform);
5702 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
5703 break;
5704 case glslang::EOpSubgroupClusteredAdd:
5705 case glslang::EOpSubgroupClusteredMul:
5706 case glslang::EOpSubgroupClusteredMin:
5707 case glslang::EOpSubgroupClusteredMax:
5708 case glslang::EOpSubgroupClusteredAnd:
5709 case glslang::EOpSubgroupClusteredOr:
5710 case glslang::EOpSubgroupClusteredXor:
5711 builder.addCapability(spv::CapabilityGroupNonUniform);
5712 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
5713 break;
5714 case glslang::EOpSubgroupQuadBroadcast:
5715 case glslang::EOpSubgroupQuadSwapHorizontal:
5716 case glslang::EOpSubgroupQuadSwapVertical:
5717 case glslang::EOpSubgroupQuadSwapDiagonal:
5718 builder.addCapability(spv::CapabilityGroupNonUniform);
5719 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
5720 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005721#ifdef NV_EXTENSIONS
5722 case glslang::EOpSubgroupPartitionedAdd:
5723 case glslang::EOpSubgroupPartitionedMul:
5724 case glslang::EOpSubgroupPartitionedMin:
5725 case glslang::EOpSubgroupPartitionedMax:
5726 case glslang::EOpSubgroupPartitionedAnd:
5727 case glslang::EOpSubgroupPartitionedOr:
5728 case glslang::EOpSubgroupPartitionedXor:
5729 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5730 case glslang::EOpSubgroupPartitionedInclusiveMul:
5731 case glslang::EOpSubgroupPartitionedInclusiveMin:
5732 case glslang::EOpSubgroupPartitionedInclusiveMax:
5733 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5734 case glslang::EOpSubgroupPartitionedInclusiveOr:
5735 case glslang::EOpSubgroupPartitionedInclusiveXor:
5736 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5737 case glslang::EOpSubgroupPartitionedExclusiveMul:
5738 case glslang::EOpSubgroupPartitionedExclusiveMin:
5739 case glslang::EOpSubgroupPartitionedExclusiveMax:
5740 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5741 case glslang::EOpSubgroupPartitionedExclusiveOr:
5742 case glslang::EOpSubgroupPartitionedExclusiveXor:
5743 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
5744 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
5745 break;
5746#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005747 default: assert(0 && "Unhandled subgroup operation!");
5748 }
5749
5750 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
5751 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
5752 const bool isBool = typeProxy == glslang::EbtBool;
5753
5754 spv::Op opCode = spv::OpNop;
5755
5756 // Figure out which opcode to use.
5757 switch (op) {
5758 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
5759 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
5760 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
5761 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
5762 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
5763 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
5764 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
5765 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
5766 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
5767 case glslang::EOpSubgroupBallotBitCount:
5768 case glslang::EOpSubgroupBallotInclusiveBitCount:
5769 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
5770 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
5771 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
5772 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
5773 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
5774 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
5775 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
5776 case glslang::EOpSubgroupAdd:
5777 case glslang::EOpSubgroupInclusiveAdd:
5778 case glslang::EOpSubgroupExclusiveAdd:
5779 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005780#ifdef NV_EXTENSIONS
5781 case glslang::EOpSubgroupPartitionedAdd:
5782 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5783 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5784#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005785 if (isFloat) {
5786 opCode = spv::OpGroupNonUniformFAdd;
5787 } else {
5788 opCode = spv::OpGroupNonUniformIAdd;
5789 }
5790 break;
5791 case glslang::EOpSubgroupMul:
5792 case glslang::EOpSubgroupInclusiveMul:
5793 case glslang::EOpSubgroupExclusiveMul:
5794 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005795#ifdef NV_EXTENSIONS
5796 case glslang::EOpSubgroupPartitionedMul:
5797 case glslang::EOpSubgroupPartitionedInclusiveMul:
5798 case glslang::EOpSubgroupPartitionedExclusiveMul:
5799#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005800 if (isFloat) {
5801 opCode = spv::OpGroupNonUniformFMul;
5802 } else {
5803 opCode = spv::OpGroupNonUniformIMul;
5804 }
5805 break;
5806 case glslang::EOpSubgroupMin:
5807 case glslang::EOpSubgroupInclusiveMin:
5808 case glslang::EOpSubgroupExclusiveMin:
5809 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005810#ifdef NV_EXTENSIONS
5811 case glslang::EOpSubgroupPartitionedMin:
5812 case glslang::EOpSubgroupPartitionedInclusiveMin:
5813 case glslang::EOpSubgroupPartitionedExclusiveMin:
5814#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005815 if (isFloat) {
5816 opCode = spv::OpGroupNonUniformFMin;
5817 } else if (isUnsigned) {
5818 opCode = spv::OpGroupNonUniformUMin;
5819 } else {
5820 opCode = spv::OpGroupNonUniformSMin;
5821 }
5822 break;
5823 case glslang::EOpSubgroupMax:
5824 case glslang::EOpSubgroupInclusiveMax:
5825 case glslang::EOpSubgroupExclusiveMax:
5826 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005827#ifdef NV_EXTENSIONS
5828 case glslang::EOpSubgroupPartitionedMax:
5829 case glslang::EOpSubgroupPartitionedInclusiveMax:
5830 case glslang::EOpSubgroupPartitionedExclusiveMax:
5831#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005832 if (isFloat) {
5833 opCode = spv::OpGroupNonUniformFMax;
5834 } else if (isUnsigned) {
5835 opCode = spv::OpGroupNonUniformUMax;
5836 } else {
5837 opCode = spv::OpGroupNonUniformSMax;
5838 }
5839 break;
5840 case glslang::EOpSubgroupAnd:
5841 case glslang::EOpSubgroupInclusiveAnd:
5842 case glslang::EOpSubgroupExclusiveAnd:
5843 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005844#ifdef NV_EXTENSIONS
5845 case glslang::EOpSubgroupPartitionedAnd:
5846 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5847 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5848#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005849 if (isBool) {
5850 opCode = spv::OpGroupNonUniformLogicalAnd;
5851 } else {
5852 opCode = spv::OpGroupNonUniformBitwiseAnd;
5853 }
5854 break;
5855 case glslang::EOpSubgroupOr:
5856 case glslang::EOpSubgroupInclusiveOr:
5857 case glslang::EOpSubgroupExclusiveOr:
5858 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005859#ifdef NV_EXTENSIONS
5860 case glslang::EOpSubgroupPartitionedOr:
5861 case glslang::EOpSubgroupPartitionedInclusiveOr:
5862 case glslang::EOpSubgroupPartitionedExclusiveOr:
5863#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005864 if (isBool) {
5865 opCode = spv::OpGroupNonUniformLogicalOr;
5866 } else {
5867 opCode = spv::OpGroupNonUniformBitwiseOr;
5868 }
5869 break;
5870 case glslang::EOpSubgroupXor:
5871 case glslang::EOpSubgroupInclusiveXor:
5872 case glslang::EOpSubgroupExclusiveXor:
5873 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005874#ifdef NV_EXTENSIONS
5875 case glslang::EOpSubgroupPartitionedXor:
5876 case glslang::EOpSubgroupPartitionedInclusiveXor:
5877 case glslang::EOpSubgroupPartitionedExclusiveXor:
5878#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005879 if (isBool) {
5880 opCode = spv::OpGroupNonUniformLogicalXor;
5881 } else {
5882 opCode = spv::OpGroupNonUniformBitwiseXor;
5883 }
5884 break;
5885 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
5886 case glslang::EOpSubgroupQuadSwapHorizontal:
5887 case glslang::EOpSubgroupQuadSwapVertical:
5888 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
5889 default: assert(0 && "Unhandled subgroup operation!");
5890 }
5891
5892 std::vector<spv::Id> spvGroupOperands;
5893
5894 // Every operation begins with the Execution Scope operand.
5895 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
5896
5897 // Next, for all operations that use a Group Operation, push that as an operand.
5898 switch (op) {
5899 default: break;
5900 case glslang::EOpSubgroupBallotBitCount:
5901 case glslang::EOpSubgroupAdd:
5902 case glslang::EOpSubgroupMul:
5903 case glslang::EOpSubgroupMin:
5904 case glslang::EOpSubgroupMax:
5905 case glslang::EOpSubgroupAnd:
5906 case glslang::EOpSubgroupOr:
5907 case glslang::EOpSubgroupXor:
5908 spvGroupOperands.push_back(spv::GroupOperationReduce);
5909 break;
5910 case glslang::EOpSubgroupBallotInclusiveBitCount:
5911 case glslang::EOpSubgroupInclusiveAdd:
5912 case glslang::EOpSubgroupInclusiveMul:
5913 case glslang::EOpSubgroupInclusiveMin:
5914 case glslang::EOpSubgroupInclusiveMax:
5915 case glslang::EOpSubgroupInclusiveAnd:
5916 case glslang::EOpSubgroupInclusiveOr:
5917 case glslang::EOpSubgroupInclusiveXor:
5918 spvGroupOperands.push_back(spv::GroupOperationInclusiveScan);
5919 break;
5920 case glslang::EOpSubgroupBallotExclusiveBitCount:
5921 case glslang::EOpSubgroupExclusiveAdd:
5922 case glslang::EOpSubgroupExclusiveMul:
5923 case glslang::EOpSubgroupExclusiveMin:
5924 case glslang::EOpSubgroupExclusiveMax:
5925 case glslang::EOpSubgroupExclusiveAnd:
5926 case glslang::EOpSubgroupExclusiveOr:
5927 case glslang::EOpSubgroupExclusiveXor:
5928 spvGroupOperands.push_back(spv::GroupOperationExclusiveScan);
5929 break;
5930 case glslang::EOpSubgroupClusteredAdd:
5931 case glslang::EOpSubgroupClusteredMul:
5932 case glslang::EOpSubgroupClusteredMin:
5933 case glslang::EOpSubgroupClusteredMax:
5934 case glslang::EOpSubgroupClusteredAnd:
5935 case glslang::EOpSubgroupClusteredOr:
5936 case glslang::EOpSubgroupClusteredXor:
5937 spvGroupOperands.push_back(spv::GroupOperationClusteredReduce);
5938 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005939#ifdef NV_EXTENSIONS
5940 case glslang::EOpSubgroupPartitionedAdd:
5941 case glslang::EOpSubgroupPartitionedMul:
5942 case glslang::EOpSubgroupPartitionedMin:
5943 case glslang::EOpSubgroupPartitionedMax:
5944 case glslang::EOpSubgroupPartitionedAnd:
5945 case glslang::EOpSubgroupPartitionedOr:
5946 case glslang::EOpSubgroupPartitionedXor:
5947 spvGroupOperands.push_back(spv::GroupOperationPartitionedReduceNV);
5948 break;
5949 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5950 case glslang::EOpSubgroupPartitionedInclusiveMul:
5951 case glslang::EOpSubgroupPartitionedInclusiveMin:
5952 case glslang::EOpSubgroupPartitionedInclusiveMax:
5953 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5954 case glslang::EOpSubgroupPartitionedInclusiveOr:
5955 case glslang::EOpSubgroupPartitionedInclusiveXor:
5956 spvGroupOperands.push_back(spv::GroupOperationPartitionedInclusiveScanNV);
5957 break;
5958 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5959 case glslang::EOpSubgroupPartitionedExclusiveMul:
5960 case glslang::EOpSubgroupPartitionedExclusiveMin:
5961 case glslang::EOpSubgroupPartitionedExclusiveMax:
5962 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5963 case glslang::EOpSubgroupPartitionedExclusiveOr:
5964 case glslang::EOpSubgroupPartitionedExclusiveXor:
5965 spvGroupOperands.push_back(spv::GroupOperationPartitionedExclusiveScanNV);
5966 break;
5967#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005968 }
5969
5970 // Push back the operands next.
5971 for (auto opIt : operands) {
5972 spvGroupOperands.push_back(opIt);
5973 }
5974
5975 // Some opcodes have additional operands.
5976 switch (op) {
5977 default: break;
5978 case glslang::EOpSubgroupQuadSwapHorizontal: spvGroupOperands.push_back(builder.makeUintConstant(0)); break;
5979 case glslang::EOpSubgroupQuadSwapVertical: spvGroupOperands.push_back(builder.makeUintConstant(1)); break;
5980 case glslang::EOpSubgroupQuadSwapDiagonal: spvGroupOperands.push_back(builder.makeUintConstant(2)); break;
5981 }
5982
5983 return builder.createOp(opCode, typeId, spvGroupOperands);
5984}
5985
John Kessenich5e4b1242015-08-06 22:53:06 -06005986spv::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 -06005987{
John Kessenich66011cb2018-03-06 16:12:04 -07005988 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5989 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06005990
John Kessenich140f3df2015-06-26 16:58:36 -06005991 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005992 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005993 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005994 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005995 spv::Id typeId0 = 0;
5996 if (consumedOperands > 0)
5997 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005998 spv::Id typeId1 = 0;
5999 if (consumedOperands > 1)
6000 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006001 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006002
6003 switch (op) {
6004 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006005 if (isFloat)
6006 libCall = spv::GLSLstd450FMin;
6007 else if (isUnsigned)
6008 libCall = spv::GLSLstd450UMin;
6009 else
6010 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006011 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006012 break;
6013 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006014 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006015 break;
6016 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006017 if (isFloat)
6018 libCall = spv::GLSLstd450FMax;
6019 else if (isUnsigned)
6020 libCall = spv::GLSLstd450UMax;
6021 else
6022 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006023 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006024 break;
6025 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006026 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006027 break;
6028 case glslang::EOpDot:
6029 opCode = spv::OpDot;
6030 break;
6031 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006032 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006033 break;
6034
6035 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006036 if (isFloat)
6037 libCall = spv::GLSLstd450FClamp;
6038 else if (isUnsigned)
6039 libCall = spv::GLSLstd450UClamp;
6040 else
6041 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006042 builder.promoteScalar(precision, operands.front(), operands[1]);
6043 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006044 break;
6045 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006046 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6047 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006048 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006049 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006050 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006051 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006052 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006053 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006054 break;
6055 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006056 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006057 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006058 break;
6059 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006060 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006061 builder.promoteScalar(precision, operands[0], operands[2]);
6062 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006063 break;
6064
6065 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006066 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006067 break;
6068 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006069 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006070 break;
6071 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006072 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006073 break;
6074 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006075 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006076 break;
6077 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006078 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006079 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006080 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07006081 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08006082 libCall = spv::GLSLstd450InterpolateAtSample;
6083 break;
6084 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07006085 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08006086 libCall = spv::GLSLstd450InterpolateAtOffset;
6087 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006088 case glslang::EOpAddCarry:
6089 opCode = spv::OpIAddCarry;
6090 typeId = builder.makeStructResultType(typeId0, typeId0);
6091 consumedOperands = 2;
6092 break;
6093 case glslang::EOpSubBorrow:
6094 opCode = spv::OpISubBorrow;
6095 typeId = builder.makeStructResultType(typeId0, typeId0);
6096 consumedOperands = 2;
6097 break;
6098 case glslang::EOpUMulExtended:
6099 opCode = spv::OpUMulExtended;
6100 typeId = builder.makeStructResultType(typeId0, typeId0);
6101 consumedOperands = 2;
6102 break;
6103 case glslang::EOpIMulExtended:
6104 opCode = spv::OpSMulExtended;
6105 typeId = builder.makeStructResultType(typeId0, typeId0);
6106 consumedOperands = 2;
6107 break;
6108 case glslang::EOpBitfieldExtract:
6109 if (isUnsigned)
6110 opCode = spv::OpBitFieldUExtract;
6111 else
6112 opCode = spv::OpBitFieldSExtract;
6113 break;
6114 case glslang::EOpBitfieldInsert:
6115 opCode = spv::OpBitFieldInsert;
6116 break;
6117
6118 case glslang::EOpFma:
6119 libCall = spv::GLSLstd450Fma;
6120 break;
6121 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006122 {
6123 libCall = spv::GLSLstd450FrexpStruct;
6124 assert(builder.isPointerType(typeId1));
6125 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006126 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006127 if (builder.getNumComponents(operands[0]) == 1)
6128 frexpIntType = builder.makeIntegerType(width, true);
6129 else
6130 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6131 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6132 consumedOperands = 1;
6133 }
John Kessenich55e7d112015-11-15 21:33:39 -07006134 break;
6135 case glslang::EOpLdexp:
6136 libCall = spv::GLSLstd450Ldexp;
6137 break;
6138
Rex Xu574ab042016-04-14 16:53:07 +08006139 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08006140 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08006141
John Kessenich66011cb2018-03-06 16:12:04 -07006142 case glslang::EOpSubgroupBroadcast:
6143 case glslang::EOpSubgroupBallotBitExtract:
6144 case glslang::EOpSubgroupShuffle:
6145 case glslang::EOpSubgroupShuffleXor:
6146 case glslang::EOpSubgroupShuffleUp:
6147 case glslang::EOpSubgroupShuffleDown:
6148 case glslang::EOpSubgroupClusteredAdd:
6149 case glslang::EOpSubgroupClusteredMul:
6150 case glslang::EOpSubgroupClusteredMin:
6151 case glslang::EOpSubgroupClusteredMax:
6152 case glslang::EOpSubgroupClusteredAnd:
6153 case glslang::EOpSubgroupClusteredOr:
6154 case glslang::EOpSubgroupClusteredXor:
6155 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006156#ifdef NV_EXTENSIONS
6157 case glslang::EOpSubgroupPartitionedAdd:
6158 case glslang::EOpSubgroupPartitionedMul:
6159 case glslang::EOpSubgroupPartitionedMin:
6160 case glslang::EOpSubgroupPartitionedMax:
6161 case glslang::EOpSubgroupPartitionedAnd:
6162 case glslang::EOpSubgroupPartitionedOr:
6163 case glslang::EOpSubgroupPartitionedXor:
6164 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6165 case glslang::EOpSubgroupPartitionedInclusiveMul:
6166 case glslang::EOpSubgroupPartitionedInclusiveMin:
6167 case glslang::EOpSubgroupPartitionedInclusiveMax:
6168 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6169 case glslang::EOpSubgroupPartitionedInclusiveOr:
6170 case glslang::EOpSubgroupPartitionedInclusiveXor:
6171 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6172 case glslang::EOpSubgroupPartitionedExclusiveMul:
6173 case glslang::EOpSubgroupPartitionedExclusiveMin:
6174 case glslang::EOpSubgroupPartitionedExclusiveMax:
6175 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6176 case glslang::EOpSubgroupPartitionedExclusiveOr:
6177 case glslang::EOpSubgroupPartitionedExclusiveXor:
6178#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006179 return createSubgroupOperation(op, typeId, operands, typeProxy);
6180
Rex Xu9d93a232016-05-05 12:30:44 +08006181#ifdef AMD_EXTENSIONS
6182 case glslang::EOpSwizzleInvocations:
6183 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6184 libCall = spv::SwizzleInvocationsAMD;
6185 break;
6186 case glslang::EOpSwizzleInvocationsMasked:
6187 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6188 libCall = spv::SwizzleInvocationsMaskedAMD;
6189 break;
6190 case glslang::EOpWriteInvocation:
6191 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6192 libCall = spv::WriteInvocationAMD;
6193 break;
6194
6195 case glslang::EOpMin3:
6196 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6197 if (isFloat)
6198 libCall = spv::FMin3AMD;
6199 else {
6200 if (isUnsigned)
6201 libCall = spv::UMin3AMD;
6202 else
6203 libCall = spv::SMin3AMD;
6204 }
6205 break;
6206 case glslang::EOpMax3:
6207 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6208 if (isFloat)
6209 libCall = spv::FMax3AMD;
6210 else {
6211 if (isUnsigned)
6212 libCall = spv::UMax3AMD;
6213 else
6214 libCall = spv::SMax3AMD;
6215 }
6216 break;
6217 case glslang::EOpMid3:
6218 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6219 if (isFloat)
6220 libCall = spv::FMid3AMD;
6221 else {
6222 if (isUnsigned)
6223 libCall = spv::UMid3AMD;
6224 else
6225 libCall = spv::SMid3AMD;
6226 }
6227 break;
6228
6229 case glslang::EOpInterpolateAtVertex:
6230 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
6231 libCall = spv::InterpolateAtVertexAMD;
6232 break;
6233#endif
6234
John Kessenich140f3df2015-06-26 16:58:36 -06006235 default:
6236 return 0;
6237 }
6238
6239 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07006240 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05006241 // Use an extended instruction from the standard library.
6242 // Construct the call arguments, without modifying the original operands vector.
6243 // We might need the remaining arguments, e.g. in the EOpFrexp case.
6244 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08006245 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07006246 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07006247 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06006248 case 0:
6249 // should all be handled by visitAggregate and createNoArgOperation
6250 assert(0);
6251 return 0;
6252 case 1:
6253 // should all be handled by createUnaryOperation
6254 assert(0);
6255 return 0;
6256 case 2:
6257 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
6258 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006259 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006260 // anything 3 or over doesn't have l-value operands, so all should be consumed
6261 assert(consumedOperands == operands.size());
6262 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06006263 break;
6264 }
6265 }
6266
John Kessenich55e7d112015-11-15 21:33:39 -07006267 // Decode the return types that were structures
6268 switch (op) {
6269 case glslang::EOpAddCarry:
6270 case glslang::EOpSubBorrow:
6271 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6272 id = builder.createCompositeExtract(id, typeId0, 0);
6273 break;
6274 case glslang::EOpUMulExtended:
6275 case glslang::EOpIMulExtended:
6276 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
6277 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6278 break;
6279 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006280 {
6281 assert(operands.size() == 2);
6282 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
6283 // "exp" is floating-point type (from HLSL intrinsic)
6284 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
6285 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
6286 builder.createStore(member1, operands[1]);
6287 } else
6288 // "exp" is integer type (from GLSL built-in function)
6289 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
6290 id = builder.createCompositeExtract(id, typeId0, 0);
6291 }
John Kessenich55e7d112015-11-15 21:33:39 -07006292 break;
6293 default:
6294 break;
6295 }
6296
John Kessenich32cfd492016-02-02 12:37:46 -07006297 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006298}
6299
Rex Xu9d93a232016-05-05 12:30:44 +08006300// Intrinsics with no arguments (or no return value, and no precision).
6301spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06006302{
6303 // TODO: get the barrier operands correct
6304
6305 switch (op) {
6306 case glslang::EOpEmitVertex:
6307 builder.createNoResultOp(spv::OpEmitVertex);
6308 return 0;
6309 case glslang::EOpEndPrimitive:
6310 builder.createNoResultOp(spv::OpEndPrimitive);
6311 return 0;
6312 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006313 if (glslangIntermediate->getStage() == EShLangTessControl) {
6314 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
6315 // TODO: prefer the following, when available:
6316 // builder.createControlBarrier(spv::ScopePatch, spv::ScopePatch,
6317 // spv::MemorySemanticsPatchMask |
6318 // spv::MemorySemanticsAcquireReleaseMask);
6319 } else {
6320 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6321 spv::MemorySemanticsWorkgroupMemoryMask |
6322 spv::MemorySemanticsAcquireReleaseMask);
6323 }
John Kessenich140f3df2015-06-26 16:58:36 -06006324 return 0;
6325 case glslang::EOpMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006326 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory |
6327 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006328 return 0;
6329 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich82979362017-12-11 04:02:24 -07006330 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask |
6331 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006332 return 0;
6333 case glslang::EOpMemoryBarrierBuffer:
John Kessenich82979362017-12-11 04:02:24 -07006334 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6335 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006336 return 0;
6337 case glslang::EOpMemoryBarrierImage:
John Kessenich82979362017-12-11 04:02:24 -07006338 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask |
6339 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006340 return 0;
6341 case glslang::EOpMemoryBarrierShared:
John Kessenich82979362017-12-11 04:02:24 -07006342 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask |
6343 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006344 return 0;
6345 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006346 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
6347 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006348 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06006349 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006350 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07006351 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07006352 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006353 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07006354 case glslang::EOpDeviceMemoryBarrier:
6355 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6356 spv::MemorySemanticsImageMemoryMask |
6357 spv::MemorySemanticsAcquireReleaseMask);
6358 return 0;
6359 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
6360 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6361 spv::MemorySemanticsImageMemoryMask |
6362 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006363 return 0;
6364 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07006365 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6366 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006367 return 0;
6368 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006369 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6370 spv::MemorySemanticsWorkgroupMemoryMask |
6371 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006372 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07006373 case glslang::EOpSubgroupBarrier:
6374 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6375 spv::MemorySemanticsAcquireReleaseMask);
6376 return spv::NoResult;
6377 case glslang::EOpSubgroupMemoryBarrier:
6378 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6379 spv::MemorySemanticsAcquireReleaseMask);
6380 return spv::NoResult;
6381 case glslang::EOpSubgroupMemoryBarrierBuffer:
6382 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
6383 spv::MemorySemanticsAcquireReleaseMask);
6384 return spv::NoResult;
6385 case glslang::EOpSubgroupMemoryBarrierImage:
6386 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
6387 spv::MemorySemanticsAcquireReleaseMask);
6388 return spv::NoResult;
6389 case glslang::EOpSubgroupMemoryBarrierShared:
6390 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6391 spv::MemorySemanticsAcquireReleaseMask);
6392 return spv::NoResult;
6393 case glslang::EOpSubgroupElect: {
6394 std::vector<spv::Id> operands;
6395 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
6396 }
Rex Xu9d93a232016-05-05 12:30:44 +08006397#ifdef AMD_EXTENSIONS
6398 case glslang::EOpTime:
6399 {
6400 std::vector<spv::Id> args; // Dummy arguments
6401 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
6402 return builder.setPrecision(id, precision);
6403 }
6404#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006405 default:
Lei Zhang17535f72016-05-04 15:55:59 -04006406 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06006407 return 0;
6408 }
6409}
6410
6411spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
6412{
John Kessenich2f273362015-07-18 22:34:27 -06006413 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06006414 spv::Id id;
6415 if (symbolValues.end() != iter) {
6416 id = iter->second;
6417 return id;
6418 }
6419
6420 // it was not found, create it
6421 id = createSpvVariable(symbol);
6422 symbolValues[symbol->getId()] = id;
6423
Rex Xuc884b4a2016-06-29 15:03:44 +08006424 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006425 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
6426 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
6427 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07006428 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07006429 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06006430 if (symbol->getQualifier().hasIndex())
6431 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
6432 if (symbol->getQualifier().hasComponent())
6433 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06006434 // atomic counters use this:
6435 if (symbol->getQualifier().hasOffset())
6436 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006437 }
6438
scygan2c864272016-05-18 18:09:17 +02006439 if (symbol->getQualifier().hasLocation())
6440 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07006441 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07006442 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07006443 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06006444 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07006445 }
John Kessenich140f3df2015-06-26 16:58:36 -06006446 if (symbol->getQualifier().hasSet())
6447 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07006448 else if (IsDescriptorResource(symbol->getType())) {
6449 // default to 0
6450 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
6451 }
John Kessenich140f3df2015-06-26 16:58:36 -06006452 if (symbol->getQualifier().hasBinding())
6453 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07006454 if (symbol->getQualifier().hasAttachment())
6455 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06006456 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07006457 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06006458 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06006459 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07006460 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06006461 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07006462 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
6463 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
6464 builder.addDecoration(id, spv::DecorationXfbStride, stride);
6465 }
6466 if (symbol->getQualifier().hasXfbOffset())
6467 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006468 }
6469
Rex Xu1da878f2016-02-21 20:59:01 +08006470 if (symbol->getType().isImage()) {
6471 std::vector<spv::Decoration> memory;
6472 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
6473 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07006474 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08006475 }
6476
John Kessenich140f3df2015-06-26 16:58:36 -06006477 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06006478 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06006479 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07006480 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06006481
John Kessenich5611c6d2018-04-05 11:25:02 -06006482 // nonuniform
6483 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
6484
John Kessenichecba76f2017-01-06 00:34:48 -07006485#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08006486 if (builtIn == spv::BuiltInSampleMask) {
6487 spv::Decoration decoration;
6488 // GL_NV_sample_mask_override_coverage extension
6489 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08006490 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08006491 else
6492 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07006493 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08006494 if (decoration != spv::DecorationMax) {
6495 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
6496 }
6497 }
chaoc771d89f2017-01-13 01:10:53 -08006498 else if (builtIn == spv::BuiltInLayer) {
6499 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06006500 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006501 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08006502 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
6503 builder.addExtension(spv::E_SPV_NV_viewport_array2);
6504 }
John Kessenichb41bff62017-08-11 13:07:17 -06006505 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006506 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
6507 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08006508 builder.addCapability(spv::CapabilityShaderStereoViewNV);
6509 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
6510 }
6511 }
6512
chaoc6e5acae2016-12-20 13:28:52 -08006513 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006514 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08006515 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08006516 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
6517 }
chaoc0ad6a4e2016-12-19 16:29:34 -08006518#endif
6519
John Kessenich5d610ee2018-03-07 18:05:55 -07006520 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
6521 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
6522 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
6523 symbol->getType().getQualifier().semanticName);
6524 }
6525
John Kessenich140f3df2015-06-26 16:58:36 -06006526 return id;
6527}
6528
John Kessenich55e7d112015-11-15 21:33:39 -07006529// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07006530// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07006531//
6532// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
6533//
6534// Recursively walk the nodes. The nodes form a tree whose leaves are
6535// regular constants, which themselves are trees that createSpvConstant()
6536// recursively walks. So, this function walks the "top" of the tree:
6537// - emit specialization constant-building instructions for specConstant
6538// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04006539spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07006540{
John Kessenich7cc0e282016-03-20 00:46:02 -06006541 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07006542
qining4f4bb812016-04-03 23:55:17 -04006543 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07006544 if (! node.getQualifier().specConstant) {
6545 // hand off to the non-spec-constant path
6546 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
6547 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04006548 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07006549 nextConst, false);
6550 }
6551
6552 // We now know we have a specialization constant to build
6553
John Kessenichd94c0032016-05-30 19:29:40 -06006554 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04006555 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
6556 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
6557 std::vector<spv::Id> dimConstId;
6558 for (int dim = 0; dim < 3; ++dim) {
6559 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
6560 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07006561 if (specConst) {
6562 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
6563 glslangIntermediate->getLocalSizeSpecId(dim));
6564 }
qining4f4bb812016-04-03 23:55:17 -04006565 }
6566 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
6567 }
6568
6569 // An AST node labelled as specialization constant should be a symbol node.
6570 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
6571 if (auto* sn = node.getAsSymbolNode()) {
6572 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04006573 // Traverse the constant constructor sub tree like generating normal run-time instructions.
6574 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
6575 // will set the builder into spec constant op instruction generating mode.
6576 sub_tree->traverse(this);
6577 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04006578 } else if (auto* const_union_array = &sn->getConstArray()){
6579 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01006580 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
6581 builder.addName(id, sn->getName().c_str());
6582 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07006583 }
6584 }
qining4f4bb812016-04-03 23:55:17 -04006585
6586 // Neither a front-end constant node, nor a specialization constant node with constant union array or
6587 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04006588 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04006589 exit(1);
6590 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07006591}
6592
John Kessenich140f3df2015-06-26 16:58:36 -06006593// Use 'consts' as the flattened glslang source of scalar constants to recursively
6594// build the aggregate SPIR-V constant.
6595//
6596// If there are not enough elements present in 'consts', 0 will be substituted;
6597// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
6598//
qining08408382016-03-21 09:51:37 -04006599spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06006600{
6601 // vector of constants for SPIR-V
6602 std::vector<spv::Id> spvConsts;
6603
6604 // Type is used for struct and array constants
6605 spv::Id typeId = convertGlslangToSpvType(glslangType);
6606
6607 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006608 glslang::TType elementType(glslangType, 0);
6609 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04006610 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006611 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006612 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06006613 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04006614 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006615 } else if (glslangType.getStruct()) {
6616 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
6617 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04006618 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06006619 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06006620 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
6621 bool zero = nextConst >= consts.size();
6622 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006623 case glslang::EbtInt8:
6624 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
6625 break;
6626 case glslang::EbtUint8:
6627 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
6628 break;
6629 case glslang::EbtInt16:
6630 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
6631 break;
6632 case glslang::EbtUint16:
6633 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
6634 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006635 case glslang::EbtInt:
6636 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
6637 break;
6638 case glslang::EbtUint:
6639 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
6640 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006641 case glslang::EbtInt64:
6642 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
6643 break;
6644 case glslang::EbtUint64:
6645 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
6646 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006647 case glslang::EbtFloat:
6648 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
6649 break;
6650 case glslang::EbtDouble:
6651 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
6652 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006653 case glslang::EbtFloat16:
6654 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
6655 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006656 case glslang::EbtBool:
6657 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
6658 break;
6659 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006660 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06006661 break;
6662 }
6663 ++nextConst;
6664 }
6665 } else {
6666 // we have a non-aggregate (scalar) constant
6667 bool zero = nextConst >= consts.size();
6668 spv::Id scalar = 0;
6669 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006670 case glslang::EbtInt8:
6671 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
6672 break;
6673 case glslang::EbtUint8:
6674 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
6675 break;
6676 case glslang::EbtInt16:
6677 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
6678 break;
6679 case glslang::EbtUint16:
6680 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
6681 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006682 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07006683 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006684 break;
6685 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07006686 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006687 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006688 case glslang::EbtInt64:
6689 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
6690 break;
6691 case glslang::EbtUint64:
6692 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
6693 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006694 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07006695 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006696 break;
6697 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07006698 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006699 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006700 case glslang::EbtFloat16:
6701 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
6702 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006703 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07006704 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006705 break;
6706 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006707 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06006708 break;
6709 }
6710 ++nextConst;
6711 return scalar;
6712 }
6713
6714 return builder.makeCompositeConstant(typeId, spvConsts);
6715}
6716
John Kessenich7c1aa102015-10-15 13:29:11 -06006717// Return true if the node is a constant or symbol whose reading has no
6718// non-trivial observable cost or effect.
6719bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
6720{
6721 // don't know what this is
6722 if (node == nullptr)
6723 return false;
6724
6725 // a constant is safe
6726 if (node->getAsConstantUnion() != nullptr)
6727 return true;
6728
6729 // not a symbol means non-trivial
6730 if (node->getAsSymbolNode() == nullptr)
6731 return false;
6732
6733 // a symbol, depends on what's being read
6734 switch (node->getType().getQualifier().storage) {
6735 case glslang::EvqTemporary:
6736 case glslang::EvqGlobal:
6737 case glslang::EvqIn:
6738 case glslang::EvqInOut:
6739 case glslang::EvqConst:
6740 case glslang::EvqConstReadOnly:
6741 case glslang::EvqUniform:
6742 return true;
6743 default:
6744 return false;
6745 }
qining25262b32016-05-06 17:25:16 -04006746}
John Kessenich7c1aa102015-10-15 13:29:11 -06006747
6748// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06006749// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06006750// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06006751// Return true if trivial.
6752bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
6753{
6754 if (node == nullptr)
6755 return false;
6756
John Kessenich84cc15f2017-05-24 16:44:47 -06006757 // count non scalars as trivial, as well as anything coming from HLSL
6758 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06006759 return true;
6760
John Kessenich7c1aa102015-10-15 13:29:11 -06006761 // symbols and constants are trivial
6762 if (isTrivialLeaf(node))
6763 return true;
6764
6765 // otherwise, it needs to be a simple operation or one or two leaf nodes
6766
6767 // not a simple operation
6768 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
6769 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
6770 if (binaryNode == nullptr && unaryNode == nullptr)
6771 return false;
6772
6773 // not on leaf nodes
6774 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
6775 return false;
6776
6777 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
6778 return false;
6779 }
6780
6781 switch (node->getAsOperator()->getOp()) {
6782 case glslang::EOpLogicalNot:
6783 case glslang::EOpConvIntToBool:
6784 case glslang::EOpConvUintToBool:
6785 case glslang::EOpConvFloatToBool:
6786 case glslang::EOpConvDoubleToBool:
6787 case glslang::EOpEqual:
6788 case glslang::EOpNotEqual:
6789 case glslang::EOpLessThan:
6790 case glslang::EOpGreaterThan:
6791 case glslang::EOpLessThanEqual:
6792 case glslang::EOpGreaterThanEqual:
6793 case glslang::EOpIndexDirect:
6794 case glslang::EOpIndexDirectStruct:
6795 case glslang::EOpLogicalXor:
6796 case glslang::EOpAny:
6797 case glslang::EOpAll:
6798 return true;
6799 default:
6800 return false;
6801 }
6802}
6803
6804// Emit short-circuiting code, where 'right' is never evaluated unless
6805// the left side is true (for &&) or false (for ||).
6806spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
6807{
6808 spv::Id boolTypeId = builder.makeBoolType();
6809
6810 // emit left operand
6811 builder.clearAccessChain();
6812 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006813 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006814
6815 // Operands to accumulate OpPhi operands
6816 std::vector<spv::Id> phiOperands;
6817 // accumulate left operand's phi information
6818 phiOperands.push_back(leftId);
6819 phiOperands.push_back(builder.getBuildPoint()->getId());
6820
6821 // Make the two kinds of operation symmetric with a "!"
6822 // || => emit "if (! left) result = right"
6823 // && => emit "if ( left) result = right"
6824 //
6825 // TODO: this runtime "not" for || could be avoided by adding functionality
6826 // to 'builder' to have an "else" without an "then"
6827 if (op == glslang::EOpLogicalOr)
6828 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
6829
6830 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08006831 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06006832
6833 // emit right operand as the "then" part of the "if"
6834 builder.clearAccessChain();
6835 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006836 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006837
6838 // accumulate left operand's phi information
6839 phiOperands.push_back(rightId);
6840 phiOperands.push_back(builder.getBuildPoint()->getId());
6841
6842 // finish the "if"
6843 ifBuilder.makeEndIf();
6844
6845 // phi together the two results
6846 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
6847}
6848
Frank Henigman541f7bb2018-01-16 00:18:26 -05006849#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08006850// Return type Id of the imported set of extended instructions corresponds to the name.
6851// Import this set if it has not been imported yet.
6852spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
6853{
6854 if (extBuiltinMap.find(name) != extBuiltinMap.end())
6855 return extBuiltinMap[name];
6856 else {
Rex Xu51596642016-09-21 18:56:12 +08006857 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08006858 spv::Id extBuiltins = builder.import(name);
6859 extBuiltinMap[name] = extBuiltins;
6860 return extBuiltins;
6861 }
6862}
Frank Henigman541f7bb2018-01-16 00:18:26 -05006863#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006864
John Kessenich140f3df2015-06-26 16:58:36 -06006865}; // end anonymous namespace
6866
6867namespace glslang {
6868
John Kessenich68d78fd2015-07-12 19:28:10 -06006869void GetSpirvVersion(std::string& version)
6870{
John Kessenich9e55f632015-07-15 10:03:39 -06006871 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06006872 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07006873 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06006874 version = buf;
6875}
6876
John Kessenicha372a3e2017-11-02 22:32:14 -06006877// For low-order part of the generator's magic number. Bump up
6878// when there is a change in the style (e.g., if SSA form changes,
6879// or a different instruction sequence to do something gets used).
6880int GetSpirvGeneratorVersion()
6881{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07006882 // return 1; // start
6883 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07006884 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07006885 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07006886 // return 5; // make OpArrayLength result type be an int with signedness of 0
6887 return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
6888 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenicha372a3e2017-11-02 22:32:14 -06006889}
6890
John Kessenich140f3df2015-06-26 16:58:36 -06006891// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006892void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06006893{
6894 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06006895 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006896 if (out.fail())
6897 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06006898 for (int i = 0; i < (int)spirv.size(); ++i) {
6899 unsigned int word = spirv[i];
6900 out.write((const char*)&word, 4);
6901 }
6902 out.close();
6903}
6904
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006905// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08006906void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006907{
6908 std::ofstream out;
6909 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006910 if (out.fail())
6911 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07006912 out << "\t// " <<
6913 glslang::GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
6914 std::endl;
Flavio15017db2017-02-15 14:29:33 -08006915 if (varName != nullptr) {
6916 out << "\t #pragma once" << std::endl;
6917 out << "const uint32_t " << varName << "[] = {" << std::endl;
6918 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006919 const int WORDS_PER_LINE = 8;
6920 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
6921 out << "\t";
6922 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
6923 const unsigned int word = spirv[i + j];
6924 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
6925 if (i + j + 1 < (int)spirv.size()) {
6926 out << ",";
6927 }
6928 }
6929 out << std::endl;
6930 }
Flavio15017db2017-02-15 14:29:33 -08006931 if (varName != nullptr) {
6932 out << "};";
6933 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006934 out.close();
6935}
6936
John Kessenich140f3df2015-06-26 16:58:36 -06006937//
6938// Set up the glslang traversal
6939//
John Kessenich121853f2017-05-31 17:11:16 -06006940void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06006941{
Lei Zhang17535f72016-05-04 15:55:59 -04006942 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06006943 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04006944}
6945
John Kessenich121853f2017-05-31 17:11:16 -06006946void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
6947 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04006948{
John Kessenich140f3df2015-06-26 16:58:36 -06006949 TIntermNode* root = intermediate.getTreeRoot();
6950
6951 if (root == 0)
6952 return;
6953
John Kessenich121853f2017-05-31 17:11:16 -06006954 glslang::SpvOptions defaultOptions;
6955 if (options == nullptr)
6956 options = &defaultOptions;
6957
John Kessenich140f3df2015-06-26 16:58:36 -06006958 glslang::GetThreadPoolAllocator().push();
6959
John Kessenich2b5ea9f2018-01-31 18:35:56 -07006960 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06006961 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07006962 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06006963 it.dumpSpv(spirv);
6964
GregFfb03a552018-03-29 11:49:14 -06006965#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06006966 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
6967 // eg. forward and remove memory writes of opaque types.
6968 if ((intermediate.getSource() == EShSourceHlsl ||
6969 options->optimizeSize) &&
6970 !options->disableOptimizer) {
6971 spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
6972
6973 spvtools::Optimizer optimizer(target_env);
6974 optimizer.SetMessageConsumer([](spv_message_level_t level,
6975 const char* source,
6976 const spv_position_t& position,
6977 const char* message) {
6978 std::cerr << StringifyMessage(level, source, position, message)
6979 << std::endl;
6980 });
6981
GregFeecb8742018-03-26 12:11:55 -06006982 optimizer.RegisterPass(CreateMergeReturnPass());
GregFcd1f1692017-09-21 18:40:22 -06006983 optimizer.RegisterPass(CreateInlineExhaustivePass());
GregFe0639282017-12-21 10:55:57 -07006984 optimizer.RegisterPass(CreateEliminateDeadFunctionsPass());
6985 optimizer.RegisterPass(CreateScalarReplacementPass());
GregFcd1f1692017-09-21 18:40:22 -06006986 optimizer.RegisterPass(CreateLocalAccessChainConvertPass());
6987 optimizer.RegisterPass(CreateLocalSingleBlockLoadStoreElimPass());
6988 optimizer.RegisterPass(CreateLocalSingleStoreElimPass());
GregFeecb8742018-03-26 12:11:55 -06006989 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFcd1f1692017-09-21 18:40:22 -06006990 optimizer.RegisterPass(CreateInsertExtractElimPass());
GregF8a4848f2018-02-07 16:04:42 -07006991 optimizer.RegisterPass(CreateDeadInsertElimPass());
GregFcd1f1692017-09-21 18:40:22 -06006992 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFeecb8742018-03-26 12:11:55 -06006993 optimizer.RegisterPass(CreateCCPPass());
6994 optimizer.RegisterPass(CreateSimplificationPass());
GregFcd1f1692017-09-21 18:40:22 -06006995 optimizer.RegisterPass(CreateDeadBranchElimPass());
GregFcc80d802017-10-23 16:48:42 -06006996 optimizer.RegisterPass(CreateCFGCleanupPass());
GregFcd1f1692017-09-21 18:40:22 -06006997 optimizer.RegisterPass(CreateBlockMergePass());
6998 optimizer.RegisterPass(CreateLocalMultiStoreElimPass());
GregFeecb8742018-03-26 12:11:55 -06006999 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFcd1f1692017-09-21 18:40:22 -06007000 optimizer.RegisterPass(CreateInsertExtractElimPass());
GregF8a4848f2018-02-07 16:04:42 -07007001 optimizer.RegisterPass(CreateDeadInsertElimPass());
7002 if (options->optimizeSize) {
7003 optimizer.RegisterPass(CreateRedundancyEliminationPass());
7004 // TODO(greg-lunarg): Add this when AMD driver issues are resolved
7005 // optimizer.RegisterPass(CreateCommonUniformElimPass());
7006 }
GregFcd1f1692017-09-21 18:40:22 -06007007 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFcd1f1692017-09-21 18:40:22 -06007008
7009 if (!optimizer.Run(spirv.data(), spirv.size(), &spirv))
7010 return;
GregFcd1f1692017-09-21 18:40:22 -06007011 }
7012#endif
7013
John Kessenich140f3df2015-06-26 16:58:36 -06007014 glslang::GetThreadPoolAllocator().pop();
7015}
7016
7017}; // end namespace glslang