blob: 95b507b13e5a09e8a4e6a351b72cb3ef84640ef6 [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);
John Kessenichf52b6382018-04-05 19:35:38 -06001282 if (counterId != spv::NoResult) {
1283 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001284 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001285 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001286 }
1287 }
1288 }
1289 }
1290 }
1291 }
John Kessenich140f3df2015-06-26 16:58:36 -06001292}
1293
1294bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1295{
John Kesseniche485c7a2017-05-31 18:50:53 -06001296 builder.setLine(node->getLoc().line);
1297
qining40887662016-04-03 22:20:42 -04001298 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1299 if (node->getType().getQualifier().isSpecConstant())
1300 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1301
John Kessenich140f3df2015-06-26 16:58:36 -06001302 // First, handle special cases
1303 switch (node->getOp()) {
1304 case glslang::EOpAssign:
1305 case glslang::EOpAddAssign:
1306 case glslang::EOpSubAssign:
1307 case glslang::EOpMulAssign:
1308 case glslang::EOpVectorTimesMatrixAssign:
1309 case glslang::EOpVectorTimesScalarAssign:
1310 case glslang::EOpMatrixTimesScalarAssign:
1311 case glslang::EOpMatrixTimesMatrixAssign:
1312 case glslang::EOpDivAssign:
1313 case glslang::EOpModAssign:
1314 case glslang::EOpAndAssign:
1315 case glslang::EOpInclusiveOrAssign:
1316 case glslang::EOpExclusiveOrAssign:
1317 case glslang::EOpLeftShiftAssign:
1318 case glslang::EOpRightShiftAssign:
1319 // A bin-op assign "a += b" means the same thing as "a = a + b"
1320 // where a is evaluated before b. For a simple assignment, GLSL
1321 // says to evaluate the left before the right. So, always, left
1322 // node then right node.
1323 {
1324 // get the left l-value, save it away
1325 builder.clearAccessChain();
1326 node->getLeft()->traverse(this);
1327 spv::Builder::AccessChain lValue = builder.getAccessChain();
1328
1329 // evaluate the right
1330 builder.clearAccessChain();
1331 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001332 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001333
1334 if (node->getOp() != glslang::EOpAssign) {
1335 // the left is also an r-value
1336 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001337 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001338
1339 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001340 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001341 TranslateNoContractionDecoration(node->getType().getQualifier()),
1342 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001343 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001344 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1345 node->getType().getBasicType());
1346
1347 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001348 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001349 }
1350
1351 // store the result
1352 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001353 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001354
1355 // assignments are expressions having an rValue after they are evaluated...
1356 builder.clearAccessChain();
1357 builder.setAccessChainRValue(rValue);
1358 }
1359 return false;
1360 case glslang::EOpIndexDirect:
1361 case glslang::EOpIndexDirectStruct:
1362 {
1363 // Get the left part of the access chain.
1364 node->getLeft()->traverse(this);
1365
1366 // Add the next element in the chain
1367
David Netoa901ffe2016-06-08 14:11:40 +01001368 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001369 if (! node->getLeft()->getType().isArray() &&
1370 node->getLeft()->getType().isVector() &&
1371 node->getOp() == glslang::EOpIndexDirect) {
1372 // This is essentially a hard-coded vector swizzle of size 1,
1373 // so short circuit the access-chain stuff with a swizzle.
1374 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001375 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001376 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001377 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001378 int spvIndex = glslangIndex;
1379 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1380 node->getOp() == glslang::EOpIndexDirectStruct)
1381 {
1382 // This may be, e.g., an anonymous block-member selection, which generally need
1383 // index remapping due to hidden members in anonymous blocks.
1384 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1385 assert(remapper.size() > 0);
1386 spvIndex = remapper[glslangIndex];
1387 }
John Kessenichebb50532016-05-16 19:22:05 -06001388
David Netoa901ffe2016-06-08 14:11:40 +01001389 // normal case for indexing array or structure or block
1390 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1391
1392 // Add capabilities here for accessing PointSize and clip/cull distance.
1393 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001394 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001395 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001396 }
1397 }
1398 return false;
1399 case glslang::EOpIndexIndirect:
1400 {
1401 // Structure or array or vector indirection.
1402 // Will use native SPIR-V access-chain for struct and array indirection;
1403 // matrices are arrays of vectors, so will also work for a matrix.
1404 // Will use the access chain's 'component' for variable index into a vector.
1405
1406 // This adapter is building access chains left to right.
1407 // Set up the access chain to the left.
1408 node->getLeft()->traverse(this);
1409
1410 // save it so that computing the right side doesn't trash it
1411 spv::Builder::AccessChain partial = builder.getAccessChain();
1412
1413 // compute the next index in the chain
1414 builder.clearAccessChain();
1415 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001416 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001417
John Kessenich5611c6d2018-04-05 11:25:02 -06001418 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1419
John Kessenich140f3df2015-06-26 16:58:36 -06001420 // restore the saved access chain
1421 builder.setAccessChain(partial);
1422
1423 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001424 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001425 else
John Kessenichfa668da2015-09-13 14:46:30 -06001426 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001427 }
1428 return false;
1429 case glslang::EOpVectorSwizzle:
1430 {
1431 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001432 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001433 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001434 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001435 }
1436 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001437 case glslang::EOpMatrixSwizzle:
1438 logger->missingFunctionality("matrix swizzle");
1439 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001440 case glslang::EOpLogicalOr:
1441 case glslang::EOpLogicalAnd:
1442 {
1443
1444 // These may require short circuiting, but can sometimes be done as straight
1445 // binary operations. The right operand must be short circuited if it has
1446 // side effects, and should probably be if it is complex.
1447 if (isTrivial(node->getRight()->getAsTyped()))
1448 break; // handle below as a normal binary operation
1449 // otherwise, we need to do dynamic short circuiting on the right operand
1450 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1451 builder.clearAccessChain();
1452 builder.setAccessChainRValue(result);
1453 }
1454 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001455 default:
1456 break;
1457 }
1458
1459 // Assume generic binary op...
1460
John Kessenich32cfd492016-02-02 12:37:46 -07001461 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001462 builder.clearAccessChain();
1463 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001464 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001465
John Kessenich32cfd492016-02-02 12:37:46 -07001466 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001467 builder.clearAccessChain();
1468 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001469 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001470
John Kessenich32cfd492016-02-02 12:37:46 -07001471 // get result
John Kessenichead86222018-03-28 18:01:20 -06001472 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001473 TranslateNoContractionDecoration(node->getType().getQualifier()),
1474 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001475 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001476 convertGlslangToSpvType(node->getType()), left, right,
1477 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001478
John Kessenich50e57562015-12-21 21:21:11 -07001479 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001480 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001481 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001482 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001483 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001484 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001485 return false;
1486 }
John Kessenich140f3df2015-06-26 16:58:36 -06001487}
1488
1489bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1490{
John Kesseniche485c7a2017-05-31 18:50:53 -06001491 builder.setLine(node->getLoc().line);
1492
qining40887662016-04-03 22:20:42 -04001493 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1494 if (node->getType().getQualifier().isSpecConstant())
1495 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1496
John Kessenichfc51d282015-08-19 13:34:18 -06001497 spv::Id result = spv::NoResult;
1498
1499 // try texturing first
1500 result = createImageTextureFunctionCall(node);
1501 if (result != spv::NoResult) {
1502 builder.clearAccessChain();
1503 builder.setAccessChainRValue(result);
1504
1505 return false; // done with this node
1506 }
1507
1508 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001509
1510 if (node->getOp() == glslang::EOpArrayLength) {
1511 // Quite special; won't want to evaluate the operand.
1512
John Kessenich5611c6d2018-04-05 11:25:02 -06001513 // Currently, the front-end does not allow .length() on an array until it is sized,
1514 // except for the last block membeor of an SSBO.
1515 // TODO: If this changes, link-time sized arrays might show up here, and need their
1516 // size extracted.
1517
John Kessenichc9a80832015-09-12 12:17:44 -06001518 // Normal .length() would have been constant folded by the front-end.
1519 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001520 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001521
John Kessenichc9a80832015-09-12 12:17:44 -06001522 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1523 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001524 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1525 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001526
1527 builder.clearAccessChain();
1528 builder.setAccessChainRValue(length);
1529
1530 return false;
1531 }
1532
John Kessenichfc51d282015-08-19 13:34:18 -06001533 // Start by evaluating the operand
1534
John Kessenich8c8505c2016-07-26 12:50:38 -06001535 // Does it need a swizzle inversion? If so, evaluation is inverted;
1536 // operate first on the swizzle base, then apply the swizzle.
1537 spv::Id invertedType = spv::NoType;
1538 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1539 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1540 invertedType = getInvertedSwizzleType(*node->getOperand());
1541
John Kessenich140f3df2015-06-26 16:58:36 -06001542 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001543 if (invertedType != spv::NoType)
1544 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1545 else
1546 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001547
Rex Xufc618912015-09-09 16:42:49 +08001548 spv::Id operand = spv::NoResult;
1549
1550 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1551 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001552 node->getOp() == glslang::EOpAtomicCounter ||
1553 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001554 operand = builder.accessChainGetLValue(); // Special case l-value operands
1555 else
John Kessenich32cfd492016-02-02 12:37:46 -07001556 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001557
John Kessenichead86222018-03-28 18:01:20 -06001558 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001559 TranslateNoContractionDecoration(node->getType().getQualifier()),
1560 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001561
1562 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001563 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001564 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001565
1566 // if not, then possibly an operation
1567 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001568 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001569
1570 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001571 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001572 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001573 builder.addDecoration(result, decorations.nonUniform);
1574 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001575
John Kessenich140f3df2015-06-26 16:58:36 -06001576 builder.clearAccessChain();
1577 builder.setAccessChainRValue(result);
1578
1579 return false; // done with this node
1580 }
1581
1582 // it must be a special case, check...
1583 switch (node->getOp()) {
1584 case glslang::EOpPostIncrement:
1585 case glslang::EOpPostDecrement:
1586 case glslang::EOpPreIncrement:
1587 case glslang::EOpPreDecrement:
1588 {
1589 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001590 spv::Id one = 0;
1591 if (node->getBasicType() == glslang::EbtFloat)
1592 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001593 else if (node->getBasicType() == glslang::EbtDouble)
1594 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001595 else if (node->getBasicType() == glslang::EbtFloat16)
1596 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001597 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1598 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001599 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1600 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001601 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1602 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001603 else
1604 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001605 glslang::TOperator op;
1606 if (node->getOp() == glslang::EOpPreIncrement ||
1607 node->getOp() == glslang::EOpPostIncrement)
1608 op = glslang::EOpAdd;
1609 else
1610 op = glslang::EOpSub;
1611
John Kessenichead86222018-03-28 18:01:20 -06001612 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001613 convertGlslangToSpvType(node->getType()), operand, one,
1614 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001615 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001616
1617 // The result of operation is always stored, but conditionally the
1618 // consumed result. The consumed result is always an r-value.
1619 builder.accessChainStore(result);
1620 builder.clearAccessChain();
1621 if (node->getOp() == glslang::EOpPreIncrement ||
1622 node->getOp() == glslang::EOpPreDecrement)
1623 builder.setAccessChainRValue(result);
1624 else
1625 builder.setAccessChainRValue(operand);
1626 }
1627
1628 return false;
1629
1630 case glslang::EOpEmitStreamVertex:
1631 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1632 return false;
1633 case glslang::EOpEndStreamPrimitive:
1634 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1635 return false;
1636
1637 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001638 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001639 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001640 }
John Kessenich140f3df2015-06-26 16:58:36 -06001641}
1642
1643bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1644{
qining27e04a02016-04-14 16:40:20 -04001645 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1646 if (node->getType().getQualifier().isSpecConstant())
1647 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1648
John Kessenichfc51d282015-08-19 13:34:18 -06001649 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001650 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1651 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001652
1653 // try texturing
1654 result = createImageTextureFunctionCall(node);
1655 if (result != spv::NoResult) {
1656 builder.clearAccessChain();
1657 builder.setAccessChainRValue(result);
1658
1659 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001660#ifdef AMD_EXTENSIONS
1661 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1662#else
John Kessenich56bab042015-09-16 10:54:31 -06001663 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001664#endif
Rex Xufc618912015-09-09 16:42:49 +08001665 // "imageStore" is a special case, which has no result
1666 return false;
1667 }
John Kessenichfc51d282015-08-19 13:34:18 -06001668
John Kessenich140f3df2015-06-26 16:58:36 -06001669 glslang::TOperator binOp = glslang::EOpNull;
1670 bool reduceComparison = true;
1671 bool isMatrix = false;
1672 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001673 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001674
1675 assert(node->getOp());
1676
John Kessenichf6640762016-08-01 19:44:00 -06001677 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001678
1679 switch (node->getOp()) {
1680 case glslang::EOpSequence:
1681 {
1682 if (preVisit)
1683 ++sequenceDepth;
1684 else
1685 --sequenceDepth;
1686
1687 if (sequenceDepth == 1) {
1688 // If this is the parent node of all the functions, we want to see them
1689 // early, so all call points have actual SPIR-V functions to reference.
1690 // In all cases, still let the traverser visit the children for us.
1691 makeFunctions(node->getAsAggregate()->getSequence());
1692
John Kessenich6fccb3c2016-09-19 16:01:41 -06001693 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001694 // anything else gets there, so visit out of order, doing them all now.
1695 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1696
John Kessenich6a60c2f2016-12-08 21:01:59 -07001697 // Initializers are done, don't want to visit again, but functions and link objects need to be processed,
John Kessenich140f3df2015-06-26 16:58:36 -06001698 // so do them manually.
1699 visitFunctions(node->getAsAggregate()->getSequence());
1700
1701 return false;
1702 }
1703
1704 return true;
1705 }
1706 case glslang::EOpLinkerObjects:
1707 {
1708 if (visit == glslang::EvPreVisit)
1709 linkageOnly = true;
1710 else
1711 linkageOnly = false;
1712
1713 return true;
1714 }
1715 case glslang::EOpComma:
1716 {
1717 // processing from left to right naturally leaves the right-most
1718 // lying around in the access chain
1719 glslang::TIntermSequence& glslangOperands = node->getSequence();
1720 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1721 glslangOperands[i]->traverse(this);
1722
1723 return false;
1724 }
1725 case glslang::EOpFunction:
1726 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001727 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001728 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001729 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001730 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001731 } else {
1732 handleFunctionEntry(node);
1733 }
1734 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001735 if (inEntryPoint)
1736 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001737 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001738 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001739 }
1740
1741 return true;
1742 case glslang::EOpParameters:
1743 // Parameters will have been consumed by EOpFunction processing, but not
1744 // the body, so we still visited the function node's children, making this
1745 // child redundant.
1746 return false;
1747 case glslang::EOpFunctionCall:
1748 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001749 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001750 if (node->isUserDefined())
1751 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001752 // assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
John Kessenich6c292d32016-02-15 20:58:50 -07001753 if (result) {
1754 builder.clearAccessChain();
1755 builder.setAccessChainRValue(result);
1756 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001757 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001758
1759 return false;
1760 }
1761 case glslang::EOpConstructMat2x2:
1762 case glslang::EOpConstructMat2x3:
1763 case glslang::EOpConstructMat2x4:
1764 case glslang::EOpConstructMat3x2:
1765 case glslang::EOpConstructMat3x3:
1766 case glslang::EOpConstructMat3x4:
1767 case glslang::EOpConstructMat4x2:
1768 case glslang::EOpConstructMat4x3:
1769 case glslang::EOpConstructMat4x4:
1770 case glslang::EOpConstructDMat2x2:
1771 case glslang::EOpConstructDMat2x3:
1772 case glslang::EOpConstructDMat2x4:
1773 case glslang::EOpConstructDMat3x2:
1774 case glslang::EOpConstructDMat3x3:
1775 case glslang::EOpConstructDMat3x4:
1776 case glslang::EOpConstructDMat4x2:
1777 case glslang::EOpConstructDMat4x3:
1778 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001779 case glslang::EOpConstructIMat2x2:
1780 case glslang::EOpConstructIMat2x3:
1781 case glslang::EOpConstructIMat2x4:
1782 case glslang::EOpConstructIMat3x2:
1783 case glslang::EOpConstructIMat3x3:
1784 case glslang::EOpConstructIMat3x4:
1785 case glslang::EOpConstructIMat4x2:
1786 case glslang::EOpConstructIMat4x3:
1787 case glslang::EOpConstructIMat4x4:
1788 case glslang::EOpConstructUMat2x2:
1789 case glslang::EOpConstructUMat2x3:
1790 case glslang::EOpConstructUMat2x4:
1791 case glslang::EOpConstructUMat3x2:
1792 case glslang::EOpConstructUMat3x3:
1793 case glslang::EOpConstructUMat3x4:
1794 case glslang::EOpConstructUMat4x2:
1795 case glslang::EOpConstructUMat4x3:
1796 case glslang::EOpConstructUMat4x4:
1797 case glslang::EOpConstructBMat2x2:
1798 case glslang::EOpConstructBMat2x3:
1799 case glslang::EOpConstructBMat2x4:
1800 case glslang::EOpConstructBMat3x2:
1801 case glslang::EOpConstructBMat3x3:
1802 case glslang::EOpConstructBMat3x4:
1803 case glslang::EOpConstructBMat4x2:
1804 case glslang::EOpConstructBMat4x3:
1805 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001806 case glslang::EOpConstructF16Mat2x2:
1807 case glslang::EOpConstructF16Mat2x3:
1808 case glslang::EOpConstructF16Mat2x4:
1809 case glslang::EOpConstructF16Mat3x2:
1810 case glslang::EOpConstructF16Mat3x3:
1811 case glslang::EOpConstructF16Mat3x4:
1812 case glslang::EOpConstructF16Mat4x2:
1813 case glslang::EOpConstructF16Mat4x3:
1814 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06001815 isMatrix = true;
1816 // fall through
1817 case glslang::EOpConstructFloat:
1818 case glslang::EOpConstructVec2:
1819 case glslang::EOpConstructVec3:
1820 case glslang::EOpConstructVec4:
1821 case glslang::EOpConstructDouble:
1822 case glslang::EOpConstructDVec2:
1823 case glslang::EOpConstructDVec3:
1824 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001825 case glslang::EOpConstructFloat16:
1826 case glslang::EOpConstructF16Vec2:
1827 case glslang::EOpConstructF16Vec3:
1828 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001829 case glslang::EOpConstructBool:
1830 case glslang::EOpConstructBVec2:
1831 case glslang::EOpConstructBVec3:
1832 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07001833 case glslang::EOpConstructInt8:
1834 case glslang::EOpConstructI8Vec2:
1835 case glslang::EOpConstructI8Vec3:
1836 case glslang::EOpConstructI8Vec4:
1837 case glslang::EOpConstructUint8:
1838 case glslang::EOpConstructU8Vec2:
1839 case glslang::EOpConstructU8Vec3:
1840 case glslang::EOpConstructU8Vec4:
1841 case glslang::EOpConstructInt16:
1842 case glslang::EOpConstructI16Vec2:
1843 case glslang::EOpConstructI16Vec3:
1844 case glslang::EOpConstructI16Vec4:
1845 case glslang::EOpConstructUint16:
1846 case glslang::EOpConstructU16Vec2:
1847 case glslang::EOpConstructU16Vec3:
1848 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001849 case glslang::EOpConstructInt:
1850 case glslang::EOpConstructIVec2:
1851 case glslang::EOpConstructIVec3:
1852 case glslang::EOpConstructIVec4:
1853 case glslang::EOpConstructUint:
1854 case glslang::EOpConstructUVec2:
1855 case glslang::EOpConstructUVec3:
1856 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001857 case glslang::EOpConstructInt64:
1858 case glslang::EOpConstructI64Vec2:
1859 case glslang::EOpConstructI64Vec3:
1860 case glslang::EOpConstructI64Vec4:
1861 case glslang::EOpConstructUint64:
1862 case glslang::EOpConstructU64Vec2:
1863 case glslang::EOpConstructU64Vec3:
1864 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001865 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001866 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001867 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001868 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001869 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001870 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001871 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001872 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001873 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001874 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001875 std::vector<spv::Id> constituents;
1876 for (int c = 0; c < (int)arguments.size(); ++c)
1877 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001878 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001879 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001880 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001881 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001882 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001883
1884 builder.clearAccessChain();
1885 builder.setAccessChainRValue(constructed);
1886
1887 return false;
1888 }
1889
1890 // These six are component-wise compares with component-wise results.
1891 // Forward on to createBinaryOperation(), requesting a vector result.
1892 case glslang::EOpLessThan:
1893 case glslang::EOpGreaterThan:
1894 case glslang::EOpLessThanEqual:
1895 case glslang::EOpGreaterThanEqual:
1896 case glslang::EOpVectorEqual:
1897 case glslang::EOpVectorNotEqual:
1898 {
1899 // Map the operation to a binary
1900 binOp = node->getOp();
1901 reduceComparison = false;
1902 switch (node->getOp()) {
1903 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1904 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1905 default: binOp = node->getOp(); break;
1906 }
1907
1908 break;
1909 }
1910 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001911 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001912 binOp = glslang::EOpMul;
1913 break;
1914 case glslang::EOpOuterProduct:
1915 // two vectors multiplied to make a matrix
1916 binOp = glslang::EOpOuterProduct;
1917 break;
1918 case glslang::EOpDot:
1919 {
qining25262b32016-05-06 17:25:16 -04001920 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001921 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001922 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001923 binOp = glslang::EOpMul;
1924 break;
1925 }
1926 case glslang::EOpMod:
1927 // when an aggregate, this is the floating-point mod built-in function,
1928 // which can be emitted by the one in createBinaryOperation()
1929 binOp = glslang::EOpMod;
1930 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001931 case glslang::EOpEmitVertex:
1932 case glslang::EOpEndPrimitive:
1933 case glslang::EOpBarrier:
1934 case glslang::EOpMemoryBarrier:
1935 case glslang::EOpMemoryBarrierAtomicCounter:
1936 case glslang::EOpMemoryBarrierBuffer:
1937 case glslang::EOpMemoryBarrierImage:
1938 case glslang::EOpMemoryBarrierShared:
1939 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07001940 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001941 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07001942 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001943 case glslang::EOpWorkgroupMemoryBarrier:
1944 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07001945 case glslang::EOpSubgroupBarrier:
1946 case glslang::EOpSubgroupMemoryBarrier:
1947 case glslang::EOpSubgroupMemoryBarrierBuffer:
1948 case glslang::EOpSubgroupMemoryBarrierImage:
1949 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06001950 noReturnValue = true;
1951 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1952 break;
1953
John Kessenich426394d2015-07-23 10:22:48 -06001954 case glslang::EOpAtomicAdd:
1955 case glslang::EOpAtomicMin:
1956 case glslang::EOpAtomicMax:
1957 case glslang::EOpAtomicAnd:
1958 case glslang::EOpAtomicOr:
1959 case glslang::EOpAtomicXor:
1960 case glslang::EOpAtomicExchange:
1961 case glslang::EOpAtomicCompSwap:
1962 atomic = true;
1963 break;
1964
John Kessenich0d0c6d32017-07-23 16:08:26 -06001965 case glslang::EOpAtomicCounterAdd:
1966 case glslang::EOpAtomicCounterSubtract:
1967 case glslang::EOpAtomicCounterMin:
1968 case glslang::EOpAtomicCounterMax:
1969 case glslang::EOpAtomicCounterAnd:
1970 case glslang::EOpAtomicCounterOr:
1971 case glslang::EOpAtomicCounterXor:
1972 case glslang::EOpAtomicCounterExchange:
1973 case glslang::EOpAtomicCounterCompSwap:
1974 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1975 builder.addCapability(spv::CapabilityAtomicStorageOps);
1976 atomic = true;
1977 break;
1978
John Kessenich140f3df2015-06-26 16:58:36 -06001979 default:
1980 break;
1981 }
1982
1983 //
1984 // See if it maps to a regular operation.
1985 //
John Kessenich140f3df2015-06-26 16:58:36 -06001986 if (binOp != glslang::EOpNull) {
1987 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1988 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1989 assert(left && right);
1990
1991 builder.clearAccessChain();
1992 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001993 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001994
1995 builder.clearAccessChain();
1996 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001997 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001998
John Kesseniche485c7a2017-05-31 18:50:53 -06001999 builder.setLine(node->getLoc().line);
John Kessenichead86222018-03-28 18:01:20 -06002000 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002001 TranslateNoContractionDecoration(node->getType().getQualifier()),
2002 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002003 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002004 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002005 left->getType().getBasicType(), reduceComparison);
2006
2007 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002008 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002009 builder.clearAccessChain();
2010 builder.setAccessChainRValue(result);
2011
2012 return false;
2013 }
2014
John Kessenich426394d2015-07-23 10:22:48 -06002015 //
2016 // Create the list of operands.
2017 //
John Kessenich140f3df2015-06-26 16:58:36 -06002018 glslang::TIntermSequence& glslangOperands = node->getSequence();
2019 std::vector<spv::Id> operands;
2020 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002021 // special case l-value operands; there are just a few
2022 bool lvalue = false;
2023 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002024 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002025 case glslang::EOpModf:
2026 if (arg == 1)
2027 lvalue = true;
2028 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002029 case glslang::EOpInterpolateAtSample:
2030 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002031#ifdef AMD_EXTENSIONS
2032 case glslang::EOpInterpolateAtVertex:
2033#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002034 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002035 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002036
2037 // Does it need a swizzle inversion? If so, evaluation is inverted;
2038 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002039 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002040 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2041 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2042 }
Rex Xu7a26c172015-12-08 17:12:09 +08002043 break;
Rex Xud4782c12015-09-06 16:30:11 +08002044 case glslang::EOpAtomicAdd:
2045 case glslang::EOpAtomicMin:
2046 case glslang::EOpAtomicMax:
2047 case glslang::EOpAtomicAnd:
2048 case glslang::EOpAtomicOr:
2049 case glslang::EOpAtomicXor:
2050 case glslang::EOpAtomicExchange:
2051 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002052 case glslang::EOpAtomicCounterAdd:
2053 case glslang::EOpAtomicCounterSubtract:
2054 case glslang::EOpAtomicCounterMin:
2055 case glslang::EOpAtomicCounterMax:
2056 case glslang::EOpAtomicCounterAnd:
2057 case glslang::EOpAtomicCounterOr:
2058 case glslang::EOpAtomicCounterXor:
2059 case glslang::EOpAtomicCounterExchange:
2060 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002061 if (arg == 0)
2062 lvalue = true;
2063 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002064 case glslang::EOpAddCarry:
2065 case glslang::EOpSubBorrow:
2066 if (arg == 2)
2067 lvalue = true;
2068 break;
2069 case glslang::EOpUMulExtended:
2070 case glslang::EOpIMulExtended:
2071 if (arg >= 2)
2072 lvalue = true;
2073 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002074 default:
2075 break;
2076 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002077 builder.clearAccessChain();
2078 if (invertedType != spv::NoType && arg == 0)
2079 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2080 else
2081 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002082 if (lvalue)
2083 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002084 else {
2085 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07002086 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002087 }
John Kessenich140f3df2015-06-26 16:58:36 -06002088 }
John Kessenich426394d2015-07-23 10:22:48 -06002089
John Kesseniche485c7a2017-05-31 18:50:53 -06002090 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06002091 if (atomic) {
2092 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002093 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002094 } else {
2095 // Pass through to generic operations.
2096 switch (glslangOperands.size()) {
2097 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002098 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002099 break;
2100 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002101 {
2102 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002103 TranslateNoContractionDecoration(node->getType().getQualifier()),
2104 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002105 result = createUnaryOperation(
2106 node->getOp(), decorations,
2107 resultType(), operands.front(),
2108 glslangOperands[0]->getAsTyped()->getBasicType());
2109 }
John Kessenich426394d2015-07-23 10:22:48 -06002110 break;
2111 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002112 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002113 break;
2114 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002115 if (invertedType)
2116 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002117 }
2118
2119 if (noReturnValue)
2120 return false;
2121
2122 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002123 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002124 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002125 } else {
2126 builder.clearAccessChain();
2127 builder.setAccessChainRValue(result);
2128 return false;
2129 }
2130}
2131
John Kessenich433e9ff2017-01-26 20:31:11 -07002132// This path handles both if-then-else and ?:
2133// The if-then-else has a node type of void, while
2134// ?: has either a void or a non-void node type
2135//
2136// Leaving the result, when not void:
2137// GLSL only has r-values as the result of a :?, but
2138// if we have an l-value, that can be more efficient if it will
2139// become the base of a complex r-value expression, because the
2140// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002141bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2142{
John Kessenich4bee5312018-02-20 21:29:05 -07002143 // See if it simple and safe, or required, to execute both sides.
2144 // Crucially, side effects must be either semantically required or avoided,
2145 // and there are performance trade-offs.
2146 // Return true if required or a good idea (and safe) to execute both sides,
2147 // false otherwise.
2148 const auto bothSidesPolicy = [&]() -> bool {
2149 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002150 if (node->getTrueBlock() == nullptr ||
2151 node->getFalseBlock() == nullptr)
2152 return false;
2153
John Kessenich4bee5312018-02-20 21:29:05 -07002154 // required? (unless we write additional code to look for side effects
2155 // and make performance trade-offs if none are present)
2156 if (!node->getShortCircuit())
2157 return true;
2158
2159 // if not required to execute both, decide based on performance/practicality...
2160
2161 // see if OpSelect can handle it
2162 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2163 node->getBasicType() == glslang::EbtVoid)
2164 return false;
2165
John Kessenich433e9ff2017-01-26 20:31:11 -07002166 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2167 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2168
2169 // return true if a single operand to ? : is okay for OpSelect
2170 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002171 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002172 };
2173
2174 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2175 operandOkay(node->getFalseBlock()->getAsTyped());
2176 };
2177
John Kessenich4bee5312018-02-20 21:29:05 -07002178 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2179 // emit the condition before doing anything with selection
2180 node->getCondition()->traverse(this);
2181 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2182
2183 // Find a way of executing both sides and selecting the right result.
2184 const auto executeBothSides = [&]() -> void {
2185 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002186 node->getTrueBlock()->traverse(this);
2187 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2188 node->getFalseBlock()->traverse(this);
2189 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2190
John Kesseniche485c7a2017-05-31 18:50:53 -06002191 builder.setLine(node->getLoc().line);
2192
John Kessenich4bee5312018-02-20 21:29:05 -07002193 // done if void
2194 if (node->getBasicType() == glslang::EbtVoid)
2195 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002196
John Kessenich4bee5312018-02-20 21:29:05 -07002197 // emit code to select between trueValue and falseValue
2198
2199 // see if OpSelect can handle it
2200 if (node->getType().isScalar() || node->getType().isVector()) {
2201 // Emit OpSelect for this selection.
2202
2203 // smear condition to vector, if necessary (AST is always scalar)
2204 if (builder.isVector(trueValue))
2205 condition = builder.smearScalar(spv::NoPrecision, condition,
2206 builder.makeVectorType(builder.makeBoolType(),
2207 builder.getNumComponents(trueValue)));
2208
2209 // OpSelect
2210 result = builder.createTriOp(spv::OpSelect,
2211 convertGlslangToSpvType(node->getType()), condition,
2212 trueValue, falseValue);
2213
2214 builder.clearAccessChain();
2215 builder.setAccessChainRValue(result);
2216 } else {
2217 // We need control flow to select the result.
2218 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2219 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2220
2221 // Selection control:
2222 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2223
2224 // make an "if" based on the value created by the condition
2225 spv::Builder::If ifBuilder(condition, control, builder);
2226
2227 // emit the "then" statement
2228 builder.createStore(trueValue, result);
2229 ifBuilder.makeBeginElse();
2230 // emit the "else" statement
2231 builder.createStore(falseValue, result);
2232
2233 // finish off the control flow
2234 ifBuilder.makeEndIf();
2235
2236 builder.clearAccessChain();
2237 builder.setAccessChainLValue(result);
2238 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002239 };
2240
John Kessenich4bee5312018-02-20 21:29:05 -07002241 // Execute the one side needed, as per the condition
2242 const auto executeOneSide = [&]() {
2243 // Always emit control flow.
2244 if (node->getBasicType() != glslang::EbtVoid)
2245 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002246
John Kessenich4bee5312018-02-20 21:29:05 -07002247 // Selection control:
2248 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2249
2250 // make an "if" based on the value created by the condition
2251 spv::Builder::If ifBuilder(condition, control, builder);
2252
2253 // emit the "then" statement
2254 if (node->getTrueBlock() != nullptr) {
2255 node->getTrueBlock()->traverse(this);
2256 if (result != spv::NoResult)
2257 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2258 }
2259
2260 if (node->getFalseBlock() != nullptr) {
2261 ifBuilder.makeBeginElse();
2262 // emit the "else" statement
2263 node->getFalseBlock()->traverse(this);
2264 if (result != spv::NoResult)
2265 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2266 }
2267
2268 // finish off the control flow
2269 ifBuilder.makeEndIf();
2270
2271 if (result != spv::NoResult) {
2272 builder.clearAccessChain();
2273 builder.setAccessChainLValue(result);
2274 }
2275 };
2276
2277 // Try for OpSelect (or a requirement to execute both sides)
2278 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002279 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2280 if (node->getType().getQualifier().isSpecConstant())
2281 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002282 executeBothSides();
2283 } else
2284 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002285
2286 return false;
2287}
2288
2289bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2290{
2291 // emit and get the condition before doing anything with switch
2292 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002293 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002294
Rex Xu57e65922017-07-04 23:23:40 +08002295 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002296 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002297
John Kessenich140f3df2015-06-26 16:58:36 -06002298 // browse the children to sort out code segments
2299 int defaultSegment = -1;
2300 std::vector<TIntermNode*> codeSegments;
2301 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2302 std::vector<int> caseValues;
2303 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2304 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2305 TIntermNode* child = *c;
2306 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002307 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002308 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002309 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002310 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2311 } else
2312 codeSegments.push_back(child);
2313 }
2314
qining25262b32016-05-06 17:25:16 -04002315 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002316 // statements between the last case and the end of the switch statement
2317 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2318 (int)codeSegments.size() == defaultSegment)
2319 codeSegments.push_back(nullptr);
2320
2321 // make the switch statement
2322 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002323 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002324
2325 // emit all the code in the segments
2326 breakForLoop.push(false);
2327 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2328 builder.nextSwitchSegment(segmentBlocks, s);
2329 if (codeSegments[s])
2330 codeSegments[s]->traverse(this);
2331 else
2332 builder.addSwitchBreak();
2333 }
2334 breakForLoop.pop();
2335
2336 builder.endSwitch(segmentBlocks);
2337
2338 return false;
2339}
2340
2341void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2342{
2343 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002344 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002345
2346 builder.clearAccessChain();
2347 builder.setAccessChainRValue(constant);
2348}
2349
2350bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2351{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002352 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002353 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002354
2355 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002356 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2357 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002358
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002359 // Spec requires back edges to target header blocks, and every header block
2360 // must dominate its merge block. Make a header block first to ensure these
2361 // conditions are met. By definition, it will contain OpLoopMerge, followed
2362 // by a block-ending branch. But we don't want to put any other body/test
2363 // instructions in it, since the body/test may have arbitrary instructions,
2364 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002365 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002366 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002367 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002368 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002369 spv::Block& test = builder.makeNewBlock();
2370 builder.createBranch(&test);
2371
2372 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002373 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002374 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002375 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2376
2377 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002378 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002379 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002380 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002381 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002382 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002383
2384 builder.setBuildPoint(&blocks.continue_target);
2385 if (node->getTerminal())
2386 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002387 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002388 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002389 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002390 builder.createBranch(&blocks.body);
2391
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002392 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002393 builder.setBuildPoint(&blocks.body);
2394 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002395 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002396 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002397 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002398
2399 builder.setBuildPoint(&blocks.continue_target);
2400 if (node->getTerminal())
2401 node->getTerminal()->traverse(this);
2402 if (node->getTest()) {
2403 node->getTest()->traverse(this);
2404 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002405 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002406 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002407 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002408 // TODO: unless there was a break/return/discard instruction
2409 // somewhere in the body, this is an infinite loop, so we should
2410 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002411 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002412 }
John Kessenich140f3df2015-06-26 16:58:36 -06002413 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002414 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002415 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002416 return false;
2417}
2418
2419bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2420{
2421 if (node->getExpression())
2422 node->getExpression()->traverse(this);
2423
John Kesseniche485c7a2017-05-31 18:50:53 -06002424 builder.setLine(node->getLoc().line);
2425
John Kessenich140f3df2015-06-26 16:58:36 -06002426 switch (node->getFlowOp()) {
2427 case glslang::EOpKill:
2428 builder.makeDiscard();
2429 break;
2430 case glslang::EOpBreak:
2431 if (breakForLoop.top())
2432 builder.createLoopExit();
2433 else
2434 builder.addSwitchBreak();
2435 break;
2436 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002437 builder.createLoopContinue();
2438 break;
2439 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002440 if (node->getExpression()) {
2441 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2442 spv::Id returnId = accessChainLoad(glslangReturnType);
2443 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2444 builder.clearAccessChain();
2445 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2446 builder.setAccessChainLValue(copyId);
2447 multiTypeStore(glslangReturnType, returnId);
2448 returnId = builder.createLoad(copyId);
2449 }
2450 builder.makeReturn(false, returnId);
2451 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002452 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002453
2454 builder.clearAccessChain();
2455 break;
2456
2457 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002458 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002459 break;
2460 }
2461
2462 return false;
2463}
2464
2465spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2466{
qining25262b32016-05-06 17:25:16 -04002467 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002468 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002469 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002470 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002471 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002472 }
2473
2474 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002475 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002476 spv::Id spvType = convertGlslangToSpvType(node->getType());
2477
Rex Xucabbb782017-03-24 13:41:14 +08002478 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2479 node->getType().containsBasicType(glslang::EbtInt16) ||
2480 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002481 if (contains16BitType) {
2482 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
John Kessenich66011cb2018-03-06 16:12:04 -07002483 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002484 builder.addCapability(spv::CapabilityStorageInputOutput16);
2485 } else if (storageClass == spv::StorageClassPushConstant) {
John Kessenich66011cb2018-03-06 16:12:04 -07002486 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002487 builder.addCapability(spv::CapabilityStoragePushConstant16);
2488 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich66011cb2018-03-06 16:12:04 -07002489 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002490 builder.addCapability(spv::CapabilityStorageUniform16);
2491 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2492 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2493 }
2494 }
Rex Xuf89ad982017-04-07 23:22:33 +08002495
John Kessenich140f3df2015-06-26 16:58:36 -06002496 const char* name = node->getName().c_str();
2497 if (glslang::IsAnonymous(name))
2498 name = "";
2499
2500 return builder.createVariable(storageClass, spvType, name);
2501}
2502
2503// Return type Id of the sampled type.
2504spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2505{
2506 switch (sampler.type) {
2507 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08002508#ifdef AMD_EXTENSIONS
2509 case glslang::EbtFloat16:
2510 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
2511 builder.addCapability(spv::CapabilityFloat16ImageAMD);
2512 return builder.makeFloatType(16);
2513#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002514 case glslang::EbtInt: return builder.makeIntType(32);
2515 case glslang::EbtUint: return builder.makeUintType(32);
2516 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002517 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002518 return builder.makeFloatType(32);
2519 }
2520}
2521
John Kessenich8c8505c2016-07-26 12:50:38 -06002522// If node is a swizzle operation, return the type that should be used if
2523// the swizzle base is first consumed by another operation, before the swizzle
2524// is applied.
2525spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2526{
John Kessenichecba76f2017-01-06 00:34:48 -07002527 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002528 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2529 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2530 else
2531 return spv::NoType;
2532}
2533
2534// When inverting a swizzle with a parent op, this function
2535// will apply the swizzle operation to a completed parent operation.
2536spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2537{
2538 std::vector<unsigned> swizzle;
2539 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2540 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2541}
2542
John Kessenich8c8505c2016-07-26 12:50:38 -06002543// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2544void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2545{
2546 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2547 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2548 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2549}
2550
John Kessenich3ac051e2015-12-20 11:29:16 -07002551// Convert from a glslang type to an SPV type, by calling into a
2552// recursive version of this function. This establishes the inherited
2553// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002554spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2555{
John Kessenichead86222018-03-28 18:01:20 -06002556 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false);
John Kessenich31ed4832015-09-09 17:51:38 -06002557}
2558
2559// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002560// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002561// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06002562spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
2563 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier, bool lastBufferBlockMember)
John Kessenich31ed4832015-09-09 17:51:38 -06002564{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002565 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002566
2567 switch (type.getBasicType()) {
2568 case glslang::EbtVoid:
2569 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002570 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002571 break;
2572 case glslang::EbtFloat:
2573 spvType = builder.makeFloatType(32);
2574 break;
2575 case glslang::EbtDouble:
2576 spvType = builder.makeFloatType(64);
2577 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002578 case glslang::EbtFloat16:
John Kessenich66011cb2018-03-06 16:12:04 -07002579 builder.addCapability(spv::CapabilityFloat16);
2580#if AMD_EXTENSIONS
2581 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2582 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
2583#endif
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002584 spvType = builder.makeFloatType(16);
2585 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002586 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002587 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2588 // a 32-bit int where non-0 means true.
2589 if (explicitLayout != glslang::ElpNone)
2590 spvType = builder.makeUintType(32);
2591 else
2592 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002593 break;
John Kessenich66011cb2018-03-06 16:12:04 -07002594 case glslang::EbtInt8:
2595 builder.addCapability(spv::CapabilityInt8);
2596 spvType = builder.makeIntType(8);
2597 break;
2598 case glslang::EbtUint8:
2599 builder.addCapability(spv::CapabilityInt8);
2600 spvType = builder.makeUintType(8);
2601 break;
2602 case glslang::EbtInt16:
2603 builder.addCapability(spv::CapabilityInt16);
2604#ifdef AMD_EXTENSIONS
2605 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2606 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2607#endif
2608 spvType = builder.makeIntType(16);
2609 break;
2610 case glslang::EbtUint16:
2611 builder.addCapability(spv::CapabilityInt16);
2612#ifdef AMD_EXTENSIONS
2613 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2614 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2615#endif
2616 spvType = builder.makeUintType(16);
2617 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002618 case glslang::EbtInt:
2619 spvType = builder.makeIntType(32);
2620 break;
2621 case glslang::EbtUint:
2622 spvType = builder.makeUintType(32);
2623 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002624 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002625 spvType = builder.makeIntType(64);
2626 break;
2627 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002628 spvType = builder.makeUintType(64);
2629 break;
John Kessenich426394d2015-07-23 10:22:48 -06002630 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002631 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002632 spvType = builder.makeUintType(32);
2633 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002634 case glslang::EbtSampler:
2635 {
2636 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002637 if (sampler.sampler) {
2638 // pure sampler
2639 spvType = builder.makeSamplerType();
2640 } else {
2641 // an image is present, make its type
2642 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2643 sampler.image ? 2 : 1, TranslateImageFormat(type));
2644 if (sampler.combined) {
2645 // already has both image and sampler, make the combined type
2646 spvType = builder.makeSampledImageType(spvType);
2647 }
John Kessenich55e7d112015-11-15 21:33:39 -07002648 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002649 }
John Kessenich140f3df2015-06-26 16:58:36 -06002650 break;
2651 case glslang::EbtStruct:
2652 case glslang::EbtBlock:
2653 {
2654 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002655 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002656
2657 // Try to share structs for different layouts, but not yet for other
2658 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002659 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002660 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002661 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002662 break;
2663
2664 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002665 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002666 memberRemapper[glslangMembers].resize(glslangMembers->size());
2667 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002668 }
2669 break;
2670 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002671 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002672 break;
2673 }
2674
2675 if (type.isMatrix())
2676 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2677 else {
2678 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2679 if (type.getVectorSize() > 1)
2680 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2681 }
2682
2683 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002684 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2685
John Kessenichc9a80832015-09-12 12:17:44 -06002686 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002687 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002688 // We need to decorate array strides for types needing explicit layout, except blocks.
2689 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002690 // Use a dummy glslang type for querying internal strides of
2691 // arrays of arrays, but using just a one-dimensional array.
2692 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06002693 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
2694 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07002695
2696 // Will compute the higher-order strides here, rather than making a whole
2697 // pile of types and doing repetitive recursion on their contents.
2698 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2699 }
John Kessenichf8842e52016-01-04 19:22:56 -07002700
2701 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002702 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002703 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002704 if (stride > 0)
2705 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002706 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002707 }
2708 } else {
2709 // single-dimensional array, and don't yet have stride
2710
John Kessenichf8842e52016-01-04 19:22:56 -07002711 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002712 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2713 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002714 }
John Kessenich31ed4832015-09-09 17:51:38 -06002715
John Kessenichead86222018-03-28 18:01:20 -06002716 // Do the outer dimension, which might not be known for a runtime-sized array.
2717 // (Unsized arrays that survive through linking will be runtime-sized arrays)
2718 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07002719 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06002720 else {
2721 if (!lastBufferBlockMember) {
2722 builder.addExtension("SPV_EXT_descriptor_indexing");
2723 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
2724 }
John Kessenichead86222018-03-28 18:01:20 -06002725 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06002726 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002727 if (stride > 0)
2728 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002729 }
2730
2731 return spvType;
2732}
2733
John Kessenich0e737842017-03-24 18:38:16 -06002734// TODO: this functionality should exist at a higher level, in creating the AST
2735//
2736// Identify interface members that don't have their required extension turned on.
2737//
2738bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2739{
2740 auto& extensions = glslangIntermediate->getRequestedExtensions();
2741
Rex Xubcf291a2017-03-29 23:01:36 +08002742 if (member.getFieldName() == "gl_ViewportMask" &&
2743 extensions.find("GL_NV_viewport_array2") == extensions.end())
2744 return true;
2745 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2746 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2747 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002748 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2749 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2750 return true;
2751 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2752 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2753 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002754 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2755 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2756 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002757
2758 return false;
2759};
2760
John Kessenich6090df02016-06-30 21:18:02 -06002761// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2762// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2763// Mutually recursive with convertGlslangToSpvType().
2764spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2765 const glslang::TTypeList* glslangMembers,
2766 glslang::TLayoutPacking explicitLayout,
2767 const glslang::TQualifier& qualifier)
2768{
2769 // Create a vector of struct types for SPIR-V to consume
2770 std::vector<spv::Id> spvMembers;
2771 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 -06002772 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2773 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2774 if (glslangMember.hiddenMember()) {
2775 ++memberDelta;
2776 if (type.getBasicType() == glslang::EbtBlock)
2777 memberRemapper[glslangMembers][i] = -1;
2778 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002779 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002780 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002781 if (filterMember(glslangMember))
2782 continue;
2783 }
John Kessenich6090df02016-06-30 21:18:02 -06002784 // modify just this child's view of the qualifier
2785 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2786 InheritQualifiers(memberQualifier, qualifier);
2787
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002788 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002789 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002790 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002791
2792 // recurse
John Kessenichead86222018-03-28 18:01:20 -06002793 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
2794 i == (int)glslangMembers->size() - 1;
2795 spvMembers.push_back(
2796 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember));
John Kessenich6090df02016-06-30 21:18:02 -06002797 }
2798 }
2799
2800 // Make the SPIR-V type
2801 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002802 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002803 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2804
2805 // Decorate it
2806 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2807
2808 return spvType;
2809}
2810
2811void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2812 const glslang::TTypeList* glslangMembers,
2813 glslang::TLayoutPacking explicitLayout,
2814 const glslang::TQualifier& qualifier,
2815 spv::Id spvType)
2816{
2817 // Name and decorate the non-hidden members
2818 int offset = -1;
2819 int locationOffset = 0; // for use within the members of this struct
2820 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2821 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2822 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002823 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002824 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002825 if (filterMember(glslangMember))
2826 continue;
2827 }
John Kessenich6090df02016-06-30 21:18:02 -06002828
2829 // modify just this child's view of the qualifier
2830 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2831 InheritQualifiers(memberQualifier, qualifier);
2832
2833 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07002834 if (member < 0)
2835 continue;
2836
2837 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2838 builder.addMemberDecoration(spvType, member,
2839 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2840 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2841 // Add interpolation and auxiliary storage decorations only to
2842 // top-level members of Input and Output storage classes
2843 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2844 type.getQualifier().storage == glslang::EvqVaryingOut) {
2845 if (type.getBasicType() == glslang::EbtBlock ||
2846 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
2847 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2848 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002849 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002850 }
2851 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002852
John Kessenich5d610ee2018-03-07 18:05:55 -07002853 if (type.getBasicType() == glslang::EbtBlock &&
2854 qualifier.storage == glslang::EvqBuffer) {
2855 // Add memory decorations only to top-level members of shader storage block
2856 std::vector<spv::Decoration> memory;
2857 TranslateMemoryDecoration(memberQualifier, memory);
2858 for (unsigned int i = 0; i < memory.size(); ++i)
2859 builder.addMemberDecoration(spvType, member, memory[i]);
2860 }
John Kessenich6090df02016-06-30 21:18:02 -06002861
John Kessenich5d610ee2018-03-07 18:05:55 -07002862 // Location assignment was already completed correctly by the front end,
2863 // just track whether a member needs to be decorated.
2864 // Ignore member locations if the container is an array, as that's
2865 // ill-specified and decisions have been made to not allow this.
2866 if (! type.isArray() && memberQualifier.hasLocation())
2867 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002868
John Kessenich5d610ee2018-03-07 18:05:55 -07002869 if (qualifier.hasLocation()) // track for upcoming inheritance
2870 locationOffset += glslangIntermediate->computeTypeLocationSize(
2871 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06002872
John Kessenich5d610ee2018-03-07 18:05:55 -07002873 // component, XFB, others
2874 if (glslangMember.getQualifier().hasComponent())
2875 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
2876 glslangMember.getQualifier().layoutComponent);
2877 if (glslangMember.getQualifier().hasXfbOffset())
2878 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
2879 glslangMember.getQualifier().layoutXfbOffset);
2880 else if (explicitLayout != glslang::ElpNone) {
2881 // figure out what to do with offset, which is accumulating
2882 int nextOffset;
2883 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2884 if (offset >= 0)
2885 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2886 offset = nextOffset;
2887 }
John Kessenich6090df02016-06-30 21:18:02 -06002888
John Kessenich5d610ee2018-03-07 18:05:55 -07002889 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2890 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
2891 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06002892
John Kessenich5d610ee2018-03-07 18:05:55 -07002893 // built-in variable decorations
2894 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
2895 if (builtIn != spv::BuiltInMax)
2896 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002897
John Kessenich5611c6d2018-04-05 11:25:02 -06002898 // nonuniform
2899 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
2900
John Kessenichead86222018-03-28 18:01:20 -06002901 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
2902 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
2903 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
2904 memberQualifier.semanticName);
2905 }
2906
chaoc771d89f2017-01-13 01:10:53 -08002907#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07002908 if (builtIn == spv::BuiltInLayer) {
2909 // SPV_NV_viewport_array2 extension
2910 if (glslangMember.getQualifier().layoutViewportRelative){
2911 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2912 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2913 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08002914 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002915 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2916 builder.addMemberDecoration(spvType, member,
2917 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
2918 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2919 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2920 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08002921 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002922 }
2923 if (glslangMember.getQualifier().layoutPassthrough) {
2924 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2925 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2926 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2927 }
chaoc771d89f2017-01-13 01:10:53 -08002928#endif
John Kessenich6090df02016-06-30 21:18:02 -06002929 }
2930
2931 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07002932 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2933 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002934 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2935 builder.addCapability(spv::CapabilityGeometryStreams);
2936 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2937 }
John Kessenich6090df02016-06-30 21:18:02 -06002938}
2939
John Kessenich6c292d32016-02-15 20:58:50 -07002940// Turn the expression forming the array size into an id.
2941// This is not quite trivial, because of specialization constants.
2942// Sometimes, a raw constant is turned into an Id, and sometimes
2943// a specialization constant expression is.
2944spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2945{
2946 // First, see if this is sized with a node, meaning a specialization constant:
2947 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2948 if (specNode != nullptr) {
2949 builder.clearAccessChain();
2950 specNode->traverse(this);
2951 return accessChainLoad(specNode->getAsTyped()->getType());
2952 }
qining25262b32016-05-06 17:25:16 -04002953
John Kessenich6c292d32016-02-15 20:58:50 -07002954 // Otherwise, need a compile-time (front end) size, get it:
2955 int size = arraySizes.getDimSize(dim);
2956 assert(size > 0);
2957 return builder.makeUintConstant(size);
2958}
2959
John Kessenich103bef92016-02-08 21:38:15 -07002960// Wrap the builder's accessChainLoad to:
2961// - localize handling of RelaxedPrecision
2962// - use the SPIR-V inferred type instead of another conversion of the glslang type
2963// (avoids unnecessary work and possible type punning for structures)
2964// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002965spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2966{
John Kessenich103bef92016-02-08 21:38:15 -07002967 spv::Id nominalTypeId = builder.accessChainGetInferredType();
John Kessenich5611c6d2018-04-05 11:25:02 -06002968 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
2969 TranslateNonUniformDecoration(type.getQualifier()), nominalTypeId);
John Kessenich103bef92016-02-08 21:38:15 -07002970
2971 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002972 if (type.getBasicType() == glslang::EbtBool) {
2973 if (builder.isScalarType(nominalTypeId)) {
2974 // Conversion for bool
2975 spv::Id boolType = builder.makeBoolType();
2976 if (nominalTypeId != boolType)
2977 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2978 } else if (builder.isVectorType(nominalTypeId)) {
2979 // Conversion for bvec
2980 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2981 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2982 if (nominalTypeId != bvecType)
2983 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2984 }
2985 }
John Kessenich103bef92016-02-08 21:38:15 -07002986
2987 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002988}
2989
Rex Xu27253232016-02-23 17:51:09 +08002990// Wrap the builder's accessChainStore to:
2991// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002992//
2993// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002994void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2995{
2996 // Need to convert to abstract types when necessary
2997 if (type.getBasicType() == glslang::EbtBool) {
2998 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2999
3000 if (builder.isScalarType(nominalTypeId)) {
3001 // Conversion for bool
3002 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003003 if (nominalTypeId != boolType) {
3004 // keep these outside arguments, for determinant order-of-evaluation
3005 spv::Id one = builder.makeUintConstant(1);
3006 spv::Id zero = builder.makeUintConstant(0);
3007 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3008 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003009 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003010 } else if (builder.isVectorType(nominalTypeId)) {
3011 // Conversion for bvec
3012 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3013 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003014 if (nominalTypeId != bvecType) {
3015 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003016 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3017 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3018 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003019 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003020 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3021 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003022 }
3023 }
3024
3025 builder.accessChainStore(rvalue);
3026}
3027
John Kessenich4bf71552016-09-02 11:20:21 -06003028// For storing when types match at the glslang level, but not might match at the
3029// SPIR-V level.
3030//
3031// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003032// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003033// as in a member-decorated way.
3034//
3035// NOTE: This function can handle any store request; if it's not special it
3036// simplifies to a simple OpStore.
3037//
3038// Implicitly uses the existing builder.accessChain as the storage target.
3039void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3040{
John Kessenichb3e24e42016-09-11 12:33:43 -06003041 // we only do the complex path here if it's an aggregate
3042 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003043 accessChainStore(type, rValue);
3044 return;
3045 }
3046
John Kessenichb3e24e42016-09-11 12:33:43 -06003047 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003048 spv::Id rType = builder.getTypeId(rValue);
3049 spv::Id lValue = builder.accessChainGetLValue();
3050 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3051 if (lType == rType) {
3052 accessChainStore(type, rValue);
3053 return;
3054 }
3055
John Kessenichb3e24e42016-09-11 12:33:43 -06003056 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003057 // where the two types were the same type in GLSL. This requires member
3058 // by member copy, recursively.
3059
John Kessenichb3e24e42016-09-11 12:33:43 -06003060 // If an array, copy element by element.
3061 if (type.isArray()) {
3062 glslang::TType glslangElementType(type, 0);
3063 spv::Id elementRType = builder.getContainedTypeId(rType);
3064 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3065 // get the source member
3066 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003067
John Kessenichb3e24e42016-09-11 12:33:43 -06003068 // set up the target storage
3069 builder.clearAccessChain();
3070 builder.setAccessChainLValue(lValue);
3071 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06003072
John Kessenichb3e24e42016-09-11 12:33:43 -06003073 // store the member
3074 multiTypeStore(glslangElementType, elementRValue);
3075 }
3076 } else {
3077 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003078
John Kessenichb3e24e42016-09-11 12:33:43 -06003079 // loop over structure members
3080 const glslang::TTypeList& members = *type.getStruct();
3081 for (int m = 0; m < (int)members.size(); ++m) {
3082 const glslang::TType& glslangMemberType = *members[m].type;
3083
3084 // get the source member
3085 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3086 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3087
3088 // set up the target storage
3089 builder.clearAccessChain();
3090 builder.setAccessChainLValue(lValue);
3091 builder.accessChainPush(builder.makeIntConstant(m));
3092
3093 // store the member
3094 multiTypeStore(glslangMemberType, memberRValue);
3095 }
John Kessenich4bf71552016-09-02 11:20:21 -06003096 }
3097}
3098
John Kessenichf85e8062015-12-19 13:57:10 -07003099// Decide whether or not this type should be
3100// decorated with offsets and strides, and if so
3101// whether std140 or std430 rules should be applied.
3102glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003103{
John Kessenichf85e8062015-12-19 13:57:10 -07003104 // has to be a block
3105 if (type.getBasicType() != glslang::EbtBlock)
3106 return glslang::ElpNone;
3107
3108 // has to be a uniform or buffer block
3109 if (type.getQualifier().storage != glslang::EvqUniform &&
3110 type.getQualifier().storage != glslang::EvqBuffer)
3111 return glslang::ElpNone;
3112
3113 // return the layout to use
3114 switch (type.getQualifier().layoutPacking) {
3115 case glslang::ElpStd140:
3116 case glslang::ElpStd430:
3117 return type.getQualifier().layoutPacking;
3118 default:
3119 return glslang::ElpNone;
3120 }
John Kessenich31ed4832015-09-09 17:51:38 -06003121}
3122
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003123// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003124int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003125{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003126 int size;
John Kessenich49987892015-12-29 17:11:44 -07003127 int stride;
3128 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003129
3130 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003131}
3132
John Kessenich49987892015-12-29 17:11:44 -07003133// 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 -07003134// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003135int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003136{
John Kessenich49987892015-12-29 17:11:44 -07003137 glslang::TType elementType;
3138 elementType.shallowCopy(matrixType);
3139 elementType.clearArraySizes();
3140
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003141 int size;
John Kessenich49987892015-12-29 17:11:44 -07003142 int stride;
3143 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
3144
3145 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003146}
3147
John Kessenich5e4b1242015-08-06 22:53:06 -06003148// Given a member type of a struct, realign the current offset for it, and compute
3149// the next (not yet aligned) offset for the next member, which will get aligned
3150// on the next call.
3151// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3152// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3153// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003154void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003155 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003156{
3157 // this will get a positive value when deemed necessary
3158 nextOffset = -1;
3159
John Kessenich5e4b1242015-08-06 22:53:06 -06003160 // override anything in currentOffset with user-set offset
3161 if (memberType.getQualifier().hasOffset())
3162 currentOffset = memberType.getQualifier().layoutOffset;
3163
3164 // It could be that current linker usage in glslang updated all the layoutOffset,
3165 // in which case the following code does not matter. But, that's not quite right
3166 // once cross-compilation unit GLSL validation is done, as the original user
3167 // settings are needed in layoutOffset, and then the following will come into play.
3168
John Kessenichf85e8062015-12-19 13:57:10 -07003169 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003170 if (! memberType.getQualifier().hasOffset())
3171 currentOffset = -1;
3172
3173 return;
3174 }
3175
John Kessenichf85e8062015-12-19 13:57:10 -07003176 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003177 if (currentOffset < 0)
3178 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003179
John Kessenich5e4b1242015-08-06 22:53:06 -06003180 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3181 // but possibly not yet correctly aligned.
3182
3183 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003184 int dummyStride;
3185 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003186
3187 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003188 // TODO: make this consistent in early phases of code:
3189 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3190 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3191 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06003192 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003193 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003194 int dummySize;
3195 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3196 if (componentAlignment <= 4)
3197 memberAlignment = componentAlignment;
3198 }
3199
3200 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003201 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003202
3203 // Bump up to vec4 if there is a bad straddle
3204 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
3205 glslang::RoundToPow2(currentOffset, 16);
3206
John Kessenich5e4b1242015-08-06 22:53:06 -06003207 nextOffset = currentOffset + memberSize;
3208}
3209
David Netoa901ffe2016-06-08 14:11:40 +01003210void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003211{
David Netoa901ffe2016-06-08 14:11:40 +01003212 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3213 switch (glslangBuiltIn)
3214 {
3215 case glslang::EbvClipDistance:
3216 case glslang::EbvCullDistance:
3217 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003218#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003219 case glslang::EbvViewportMaskNV:
3220 case glslang::EbvSecondaryPositionNV:
3221 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003222 case glslang::EbvPositionPerViewNV:
3223 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08003224#endif
David Netoa901ffe2016-06-08 14:11:40 +01003225 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3226 // Alternately, we could just call this for any glslang built-in, since the
3227 // capability already guards against duplicates.
3228 TranslateBuiltInDecoration(glslangBuiltIn, false);
3229 break;
3230 default:
3231 // Capabilities were already generated when the struct was declared.
3232 break;
3233 }
John Kessenichebb50532016-05-16 19:22:05 -06003234}
3235
John Kessenich6fccb3c2016-09-19 16:01:41 -06003236bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003237{
John Kessenicheee9d532016-09-19 18:09:30 -06003238 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003239}
3240
John Kessenichd41993d2017-09-10 15:21:05 -06003241// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003242// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3243// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd41993d2017-09-10 15:21:05 -06003244bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier)
3245{
John Kessenich6a14f782017-12-04 02:48:10 -07003246 assert(qualifier == glslang::EvqIn ||
3247 qualifier == glslang::EvqOut ||
3248 qualifier == glslang::EvqInOut ||
3249 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003250 return qualifier != glslang::EvqConstReadOnly;
3251}
3252
3253// Is parameter pass-by-original?
3254bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3255 bool implicitThisParam)
3256{
3257 if (implicitThisParam) // implicit this
3258 return true;
3259 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003260 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003261 return paramType.containsOpaque() || // sampler, etc.
3262 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3263}
3264
John Kessenich140f3df2015-06-26 16:58:36 -06003265// Make all the functions, skeletally, without actually visiting their bodies.
3266void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3267{
John Kessenichfad62972017-07-18 02:35:46 -06003268 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
3269 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3270 if (paramPrecision != spv::NoPrecision)
3271 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06003272 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06003273 };
3274
John Kessenich140f3df2015-06-26 16:58:36 -06003275 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3276 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003277 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003278 continue;
3279
3280 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003281 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003282 //
qining25262b32016-05-06 17:25:16 -04003283 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003284 // function. What it is an address of varies:
3285 //
John Kessenich4bf71552016-09-02 11:20:21 -06003286 // - "in" parameters not marked as "const" can be written to without modifying the calling
3287 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003288 //
3289 // - "const in" parameters can just be the r-value, as no writes need occur.
3290 //
John Kessenich4bf71552016-09-02 11:20:21 -06003291 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3292 // 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 -06003293
3294 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003295 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003296 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3297
John Kessenichfad62972017-07-18 02:35:46 -06003298 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3299 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003300
John Kessenichfad62972017-07-18 02:35:46 -06003301 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003302 for (int p = 0; p < (int)parameters.size(); ++p) {
3303 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3304 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003305 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003306 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003307 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003308 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3309 else
John Kessenich4bf71552016-09-02 11:20:21 -06003310 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003311 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003312 paramTypes.push_back(typeId);
3313 }
3314
3315 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003316 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3317 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003318 glslFunction->getName().c_str(), paramTypes,
3319 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003320 if (implicitThis)
3321 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003322
3323 // Track function to emit/call later
3324 functionMap[glslFunction->getName().c_str()] = function;
3325
3326 // Set the parameter id's
3327 for (int p = 0; p < (int)parameters.size(); ++p) {
3328 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3329 // give a name too
3330 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3331 }
3332 }
3333}
3334
3335// Process all the initializers, while skipping the functions and link objects
3336void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3337{
3338 builder.setBuildPoint(shaderEntry->getLastBlock());
3339 for (int i = 0; i < (int)initializers.size(); ++i) {
3340 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3341 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3342
3343 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003344 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003345 initializer->traverse(this);
3346 }
3347 }
3348}
3349
3350// Process all the functions, while skipping initializers.
3351void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3352{
3353 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3354 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003355 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003356 node->traverse(this);
3357 }
3358}
3359
3360void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3361{
qining25262b32016-05-06 17:25:16 -04003362 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003363 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003364 currentFunction = functionMap[node->getName().c_str()];
3365 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003366 builder.setBuildPoint(functionBlock);
3367}
3368
Rex Xu04db3f52015-09-16 11:44:02 +08003369void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003370{
Rex Xufc618912015-09-09 16:42:49 +08003371 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003372
3373 glslang::TSampler sampler = {};
3374 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003375#ifdef AMD_EXTENSIONS
3376 bool f16ShadowCompare = false;
3377#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003378 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003379 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3380 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003381#ifdef AMD_EXTENSIONS
3382 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3383#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003384 }
3385
John Kessenich140f3df2015-06-26 16:58:36 -06003386 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3387 builder.clearAccessChain();
3388 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003389
3390 // Special case l-value operands
3391 bool lvalue = false;
3392 switch (node.getOp()) {
3393 case glslang::EOpImageAtomicAdd:
3394 case glslang::EOpImageAtomicMin:
3395 case glslang::EOpImageAtomicMax:
3396 case glslang::EOpImageAtomicAnd:
3397 case glslang::EOpImageAtomicOr:
3398 case glslang::EOpImageAtomicXor:
3399 case glslang::EOpImageAtomicExchange:
3400 case glslang::EOpImageAtomicCompSwap:
3401 if (i == 0)
3402 lvalue = true;
3403 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003404 case glslang::EOpSparseImageLoad:
3405 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3406 lvalue = true;
3407 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003408#ifdef AMD_EXTENSIONS
3409 case glslang::EOpSparseTexture:
3410 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3411 lvalue = true;
3412 break;
3413 case glslang::EOpSparseTextureClamp:
3414 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3415 lvalue = true;
3416 break;
3417 case glslang::EOpSparseTextureLod:
3418 case glslang::EOpSparseTextureOffset:
3419 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
3420 lvalue = true;
3421 break;
3422#else
Rex Xu48edadf2015-12-31 16:11:41 +08003423 case glslang::EOpSparseTexture:
3424 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3425 lvalue = true;
3426 break;
3427 case glslang::EOpSparseTextureClamp:
3428 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3429 lvalue = true;
3430 break;
3431 case glslang::EOpSparseTextureLod:
3432 case glslang::EOpSparseTextureOffset:
3433 if (i == 3)
3434 lvalue = true;
3435 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003436#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003437 case glslang::EOpSparseTextureFetch:
3438 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3439 lvalue = true;
3440 break;
3441 case glslang::EOpSparseTextureFetchOffset:
3442 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3443 lvalue = true;
3444 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003445#ifdef AMD_EXTENSIONS
3446 case glslang::EOpSparseTextureLodOffset:
3447 case glslang::EOpSparseTextureGrad:
3448 case glslang::EOpSparseTextureOffsetClamp:
3449 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
3450 lvalue = true;
3451 break;
3452 case glslang::EOpSparseTextureGradOffset:
3453 case glslang::EOpSparseTextureGradClamp:
3454 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
3455 lvalue = true;
3456 break;
3457 case glslang::EOpSparseTextureGradOffsetClamp:
3458 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
3459 lvalue = true;
3460 break;
3461#else
Rex Xu48edadf2015-12-31 16:11:41 +08003462 case glslang::EOpSparseTextureLodOffset:
3463 case glslang::EOpSparseTextureGrad:
3464 case glslang::EOpSparseTextureOffsetClamp:
3465 if (i == 4)
3466 lvalue = true;
3467 break;
3468 case glslang::EOpSparseTextureGradOffset:
3469 case glslang::EOpSparseTextureGradClamp:
3470 if (i == 5)
3471 lvalue = true;
3472 break;
3473 case glslang::EOpSparseTextureGradOffsetClamp:
3474 if (i == 6)
3475 lvalue = true;
3476 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003477#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08003478 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003479 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3480 lvalue = true;
3481 break;
3482 case glslang::EOpSparseTextureGatherOffset:
3483 case glslang::EOpSparseTextureGatherOffsets:
3484 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3485 lvalue = true;
3486 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003487#ifdef AMD_EXTENSIONS
3488 case glslang::EOpSparseTextureGatherLod:
3489 if (i == 3)
3490 lvalue = true;
3491 break;
3492 case glslang::EOpSparseTextureGatherLodOffset:
3493 case glslang::EOpSparseTextureGatherLodOffsets:
3494 if (i == 4)
3495 lvalue = true;
3496 break;
Rex Xu129799a2017-07-05 17:23:28 +08003497 case glslang::EOpSparseImageLoadLod:
3498 if (i == 3)
3499 lvalue = true;
3500 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003501#endif
Rex Xufc618912015-09-09 16:42:49 +08003502 default:
3503 break;
3504 }
3505
Rex Xu6b86d492015-09-16 17:48:22 +08003506 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003507 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003508 else
John Kessenich32cfd492016-02-02 12:37:46 -07003509 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003510 }
3511}
3512
John Kessenichfc51d282015-08-19 13:34:18 -06003513void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003514{
John Kessenichfc51d282015-08-19 13:34:18 -06003515 builder.clearAccessChain();
3516 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003517 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003518}
John Kessenich140f3df2015-06-26 16:58:36 -06003519
John Kessenichfc51d282015-08-19 13:34:18 -06003520spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3521{
John Kesseniche485c7a2017-05-31 18:50:53 -06003522 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003523 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003524
3525 builder.setLine(node->getLoc().line);
3526
John Kessenichfc51d282015-08-19 13:34:18 -06003527 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003528 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3529 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08003530#ifdef AMD_EXTENSIONS
3531 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
3532 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
3533 : false;
3534#endif
3535
John Kessenichfc51d282015-08-19 13:34:18 -06003536 std::vector<spv::Id> arguments;
3537 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003538 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003539 else
3540 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003541 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003542
3543 spv::Builder::TextureParameters params = { };
3544 params.sampler = arguments[0];
3545
Rex Xu04db3f52015-09-16 11:44:02 +08003546 glslang::TCrackedTextureOp cracked;
3547 node->crackTexture(sampler, cracked);
3548
amhagan05506bb2017-06-13 16:53:02 -04003549 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003550
John Kessenichfc51d282015-08-19 13:34:18 -06003551 // Check for queries
3552 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003553 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3554 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003555 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003556
John Kessenichfc51d282015-08-19 13:34:18 -06003557 switch (node->getOp()) {
3558 case glslang::EOpImageQuerySize:
3559 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003560 if (arguments.size() > 1) {
3561 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003562 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003563 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003564 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003565 case glslang::EOpImageQuerySamples:
3566 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003567 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003568 case glslang::EOpTextureQueryLod:
3569 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003570 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003571 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003572 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003573 case glslang::EOpSparseTexelsResident:
3574 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003575 default:
3576 assert(0);
3577 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003578 }
John Kessenich140f3df2015-06-26 16:58:36 -06003579 }
3580
LoopDawg4425f242018-02-18 11:40:01 -07003581 int components = node->getType().getVectorSize();
3582
3583 if (node->getOp() == glslang::EOpTextureFetch) {
3584 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3585 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3586 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3587 // here around e.g. which ones return scalars or other types.
3588 components = 4;
3589 }
3590
3591 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3592
3593 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3594
Rex Xufc618912015-09-09 16:42:49 +08003595 // Check for image functions other than queries
3596 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003597 std::vector<spv::Id> operands;
3598 auto opIt = arguments.begin();
3599 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003600
3601 // Handle subpass operations
3602 // TODO: GLSL should change to have the "MS" only on the type rather than the
3603 // built-in function.
3604 if (cracked.subpass) {
3605 // add on the (0,0) coordinate
3606 spv::Id zero = builder.makeIntConstant(0);
3607 std::vector<spv::Id> comps;
3608 comps.push_back(zero);
3609 comps.push_back(zero);
3610 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3611 if (sampler.ms) {
3612 operands.push_back(spv::ImageOperandsSampleMask);
3613 operands.push_back(*(opIt++));
3614 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003615 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3616 builder.setPrecision(result, precision);
3617 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003618 }
3619
John Kessenich56bab042015-09-16 10:54:31 -06003620 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003621#ifdef AMD_EXTENSIONS
3622 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3623#else
John Kessenich56bab042015-09-16 10:54:31 -06003624 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003625#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003626 if (sampler.ms) {
3627 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003628 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003629#ifdef AMD_EXTENSIONS
3630 } else if (cracked.lod) {
3631 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3632 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3633
3634 operands.push_back(spv::ImageOperandsLodMask);
3635 operands.push_back(*opIt);
3636#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003637 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003638 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3639 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003640
St0fFa1184dd2018-04-09 21:08:14 +02003641 std::vector<spv::Id> result( 1, builder.createOp(spv::OpImageRead, resultType(), operands) );
LoopDawg4425f242018-02-18 11:40:01 -07003642 builder.setPrecision(result[0], precision);
3643
3644 // If needed, add a conversion constructor to the proper size.
3645 if (components != node->getType().getVectorSize())
3646 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3647
3648 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08003649#ifdef AMD_EXTENSIONS
3650 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3651#else
John Kessenich56bab042015-09-16 10:54:31 -06003652 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003653#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003654 if (sampler.ms) {
3655 operands.push_back(*(opIt + 1));
3656 operands.push_back(spv::ImageOperandsSampleMask);
3657 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003658#ifdef AMD_EXTENSIONS
3659 } else if (cracked.lod) {
3660 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3661 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3662
3663 operands.push_back(*(opIt + 1));
3664 operands.push_back(spv::ImageOperandsLodMask);
3665 operands.push_back(*opIt);
3666#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003667 } else
3668 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003669 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003670 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3671 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003672 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003673#ifdef AMD_EXTENSIONS
3674 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3675#else
Rex Xu5eafa472016-02-19 22:24:03 +08003676 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003677#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003678 builder.addCapability(spv::CapabilitySparseResidency);
3679 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3680 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3681
3682 if (sampler.ms) {
3683 operands.push_back(spv::ImageOperandsSampleMask);
3684 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003685#ifdef AMD_EXTENSIONS
3686 } else if (cracked.lod) {
3687 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3688 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3689
3690 operands.push_back(spv::ImageOperandsLodMask);
3691 operands.push_back(*opIt++);
3692#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003693 }
3694
3695 // Create the return type that was a special structure
3696 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003697 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003698 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3699 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3700
3701 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3702
3703 // Decode the return type
3704 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3705 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003706 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003707 // Process image atomic operations
3708
3709 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3710 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003711 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003712
John Kessenich8c8505c2016-07-26 12:50:38 -06003713 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003714 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003715
3716 std::vector<spv::Id> operands;
3717 operands.push_back(pointer);
3718 for (; opIt != arguments.end(); ++opIt)
3719 operands.push_back(*opIt);
3720
John Kessenich8c8505c2016-07-26 12:50:38 -06003721 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003722 }
3723 }
3724
amhagan05506bb2017-06-13 16:53:02 -04003725#ifdef AMD_EXTENSIONS
3726 // Check for fragment mask functions other than queries
3727 if (cracked.fragMask) {
3728 assert(sampler.ms);
3729
3730 auto opIt = arguments.begin();
3731 std::vector<spv::Id> operands;
3732
3733 // Extract the image if necessary
3734 if (builder.isSampledImage(params.sampler))
3735 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3736
3737 operands.push_back(params.sampler);
3738 ++opIt;
3739
3740 if (sampler.isSubpass()) {
3741 // add on the (0,0) coordinate
3742 spv::Id zero = builder.makeIntConstant(0);
3743 std::vector<spv::Id> comps;
3744 comps.push_back(zero);
3745 comps.push_back(zero);
3746 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3747 }
3748
3749 for (; opIt != arguments.end(); ++opIt)
3750 operands.push_back(*opIt);
3751
3752 spv::Op fragMaskOp = spv::OpNop;
3753 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3754 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3755 else if (node->getOp() == glslang::EOpFragmentFetch)
3756 fragMaskOp = spv::OpFragmentFetchAMD;
3757
3758 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3759 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3760 return builder.createOp(fragMaskOp, resultType(), operands);
3761 }
3762#endif
3763
Rex Xufc618912015-09-09 16:42:49 +08003764 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003765 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003766 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3767
John Kessenichfc51d282015-08-19 13:34:18 -06003768 // check for bias argument
3769 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003770#ifdef AMD_EXTENSIONS
3771 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3772#else
Rex Xu71519fe2015-11-11 15:35:47 +08003773 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003774#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003775 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003776#ifdef AMD_EXTENSIONS
3777 if (cracked.gather)
3778 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08003779
3780 if (f16ShadowCompare)
3781 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003782#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003783 if (cracked.offset)
3784 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003785#ifdef AMD_EXTENSIONS
3786 else if (cracked.offsets)
3787 ++nonBiasArgCount;
3788#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003789 if (cracked.grad)
3790 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003791 if (cracked.lodClamp)
3792 ++nonBiasArgCount;
3793 if (sparse)
3794 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003795
3796 if ((int)arguments.size() > nonBiasArgCount)
3797 bias = true;
3798 }
3799
John Kessenicha5c33d62016-06-02 23:45:21 -06003800 // See if the sampler param should really be just the SPV image part
3801 if (cracked.fetch) {
3802 // a fetch needs to have the image extracted first
3803 if (builder.isSampledImage(params.sampler))
3804 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3805 }
3806
Rex Xu225e0fc2016-11-17 17:47:59 +08003807#ifdef AMD_EXTENSIONS
3808 if (cracked.gather) {
3809 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3810 if (bias || cracked.lod ||
3811 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3812 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003813 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003814 }
3815 }
3816#endif
3817
John Kessenichfc51d282015-08-19 13:34:18 -06003818 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003819
John Kessenichfc51d282015-08-19 13:34:18 -06003820 params.coords = arguments[1];
3821 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003822 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003823
3824 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08003825#ifdef AMD_EXTENSIONS
3826 if (cubeCompare || f16ShadowCompare) {
3827#else
Rex Xu48edadf2015-12-31 16:11:41 +08003828 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08003829#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003830 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003831 ++extraArgs;
3832 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003833 params.Dref = arguments[2];
3834 ++extraArgs;
3835 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003836 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003837 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003838 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003839 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003840 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003841 dRefComp = builder.getNumComponents(params.coords) - 1;
3842 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003843 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3844 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003845
3846 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003847 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003848 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003849 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003850 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3851 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3852 noImplicitLod = true;
3853 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003854
3855 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003856 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003857 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003858 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003859 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003860
3861 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003862 if (cracked.grad) {
3863 params.gradX = arguments[2 + extraArgs];
3864 params.gradY = arguments[3 + extraArgs];
3865 extraArgs += 2;
3866 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003867
3868 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003869 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003870 params.offset = arguments[2 + extraArgs];
3871 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003872 } else if (cracked.offsets) {
3873 params.offsets = arguments[2 + extraArgs];
3874 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003875 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003876
3877 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003878 if (cracked.lodClamp) {
3879 params.lodClamp = arguments[2 + extraArgs];
3880 ++extraArgs;
3881 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003882
3883 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003884 if (sparse) {
3885 params.texelOut = arguments[2 + extraArgs];
3886 ++extraArgs;
3887 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003888
John Kessenich76d4dfc2016-06-16 12:43:23 -06003889 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003890 if (cracked.gather && ! sampler.shadow) {
3891 // default component is 0, if missing, otherwise an argument
3892 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003893 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003894 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003895 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003896 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003897 }
3898
3899 // bias
3900 if (bias) {
3901 params.bias = arguments[2 + extraArgs];
3902 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003903 }
John Kessenichfc51d282015-08-19 13:34:18 -06003904
John Kessenich65336482016-06-16 14:06:26 -06003905 // projective component (might not to move)
3906 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3907 // are divided by the last component of P."
3908 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3909 // unused components will appear after all used components."
3910 if (cracked.proj) {
3911 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3912 int projTargetComp;
3913 switch (sampler.dim) {
3914 case glslang::Esd1D: projTargetComp = 1; break;
3915 case glslang::Esd2D: projTargetComp = 2; break;
3916 case glslang::EsdRect: projTargetComp = 2; break;
3917 default: projTargetComp = projSourceComp; break;
3918 }
3919 // copy the projective coordinate if we have to
3920 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003921 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003922 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3923 projSourceComp);
3924 params.coords = builder.createCompositeInsert(projComp, params.coords,
3925 builder.getTypeId(params.coords), projTargetComp);
3926 }
3927 }
3928
St0fFa1184dd2018-04-09 21:08:14 +02003929 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07003930 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02003931 );
LoopDawg4425f242018-02-18 11:40:01 -07003932
3933 if (components != node->getType().getVectorSize())
3934 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3935
3936 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06003937}
3938
3939spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3940{
3941 // Grab the function's pointer from the previously created function
3942 spv::Function* function = functionMap[node->getName().c_str()];
3943 if (! function)
3944 return 0;
3945
3946 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3947 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3948
3949 // See comments in makeFunctions() for details about the semantics for parameter passing.
3950 //
3951 // These imply we need a four step process:
3952 // 1. Evaluate the arguments
3953 // 2. Allocate and make copies of in, out, and inout arguments
3954 // 3. Make the call
3955 // 4. Copy back the results
3956
3957 // 1. Evaluate the arguments
3958 std::vector<spv::Builder::AccessChain> lValues;
3959 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003960 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003961 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003962 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003963 // build l-value
3964 builder.clearAccessChain();
3965 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003966 argTypes.push_back(&paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003967 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenich6a14f782017-12-04 02:48:10 -07003968 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0) ||
3969 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003970 // save l-value
3971 lValues.push_back(builder.getAccessChain());
3972 } else {
3973 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003974 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003975 }
3976 }
3977
3978 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3979 // copy the original into that space.
3980 //
3981 // Also, build up the list of actual arguments to pass in for the call
3982 int lValueCount = 0;
3983 int rValueCount = 0;
3984 std::vector<spv::Id> spvArgs;
3985 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003986 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003987 spv::Id arg;
John Kessenichd41993d2017-09-10 15:21:05 -06003988 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003989 builder.setAccessChain(lValues[lValueCount]);
3990 arg = builder.accessChainGetLValue();
3991 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06003992 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003993 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003994 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3995 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3996 // need to copy the input into output space
3997 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003998 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003999 builder.clearAccessChain();
4000 builder.setAccessChainLValue(arg);
4001 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004002 }
4003 ++lValueCount;
4004 } else {
4005 arg = rValues[rValueCount];
4006 ++rValueCount;
4007 }
4008 spvArgs.push_back(arg);
4009 }
4010
4011 // 3. Make the call.
4012 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004013 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004014
4015 // 4. Copy back out an "out" arguments.
4016 lValueCount = 0;
4017 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06004018 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenichd41993d2017-09-10 15:21:05 -06004019 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0))
4020 ++lValueCount;
4021 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004022 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4023 spv::Id copy = builder.createLoad(spvArgs[a]);
4024 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06004025 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004026 }
4027 ++lValueCount;
4028 }
4029 }
4030
4031 return result;
4032}
4033
4034// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004035spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004036 spv::Id typeId, spv::Id left, spv::Id right,
4037 glslang::TBasicType typeProxy, bool reduceComparison)
4038{
John Kessenich66011cb2018-03-06 16:12:04 -07004039 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4040 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004041 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004042
4043 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004044 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004045 bool comparison = false;
4046
4047 switch (op) {
4048 case glslang::EOpAdd:
4049 case glslang::EOpAddAssign:
4050 if (isFloat)
4051 binOp = spv::OpFAdd;
4052 else
4053 binOp = spv::OpIAdd;
4054 break;
4055 case glslang::EOpSub:
4056 case glslang::EOpSubAssign:
4057 if (isFloat)
4058 binOp = spv::OpFSub;
4059 else
4060 binOp = spv::OpISub;
4061 break;
4062 case glslang::EOpMul:
4063 case glslang::EOpMulAssign:
4064 if (isFloat)
4065 binOp = spv::OpFMul;
4066 else
4067 binOp = spv::OpIMul;
4068 break;
4069 case glslang::EOpVectorTimesScalar:
4070 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004071 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004072 if (builder.isVector(right))
4073 std::swap(left, right);
4074 assert(builder.isScalar(right));
4075 needMatchingVectors = false;
4076 binOp = spv::OpVectorTimesScalar;
4077 } else
4078 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004079 break;
4080 case glslang::EOpVectorTimesMatrix:
4081 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004082 binOp = spv::OpVectorTimesMatrix;
4083 break;
4084 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004085 binOp = spv::OpMatrixTimesVector;
4086 break;
4087 case glslang::EOpMatrixTimesScalar:
4088 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004089 binOp = spv::OpMatrixTimesScalar;
4090 break;
4091 case glslang::EOpMatrixTimesMatrix:
4092 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004093 binOp = spv::OpMatrixTimesMatrix;
4094 break;
4095 case glslang::EOpOuterProduct:
4096 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004097 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004098 break;
4099
4100 case glslang::EOpDiv:
4101 case glslang::EOpDivAssign:
4102 if (isFloat)
4103 binOp = spv::OpFDiv;
4104 else if (isUnsigned)
4105 binOp = spv::OpUDiv;
4106 else
4107 binOp = spv::OpSDiv;
4108 break;
4109 case glslang::EOpMod:
4110 case glslang::EOpModAssign:
4111 if (isFloat)
4112 binOp = spv::OpFMod;
4113 else if (isUnsigned)
4114 binOp = spv::OpUMod;
4115 else
4116 binOp = spv::OpSMod;
4117 break;
4118 case glslang::EOpRightShift:
4119 case glslang::EOpRightShiftAssign:
4120 if (isUnsigned)
4121 binOp = spv::OpShiftRightLogical;
4122 else
4123 binOp = spv::OpShiftRightArithmetic;
4124 break;
4125 case glslang::EOpLeftShift:
4126 case glslang::EOpLeftShiftAssign:
4127 binOp = spv::OpShiftLeftLogical;
4128 break;
4129 case glslang::EOpAnd:
4130 case glslang::EOpAndAssign:
4131 binOp = spv::OpBitwiseAnd;
4132 break;
4133 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004134 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004135 binOp = spv::OpLogicalAnd;
4136 break;
4137 case glslang::EOpInclusiveOr:
4138 case glslang::EOpInclusiveOrAssign:
4139 binOp = spv::OpBitwiseOr;
4140 break;
4141 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004142 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004143 binOp = spv::OpLogicalOr;
4144 break;
4145 case glslang::EOpExclusiveOr:
4146 case glslang::EOpExclusiveOrAssign:
4147 binOp = spv::OpBitwiseXor;
4148 break;
4149 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004150 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004151 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004152 break;
4153
4154 case glslang::EOpLessThan:
4155 case glslang::EOpGreaterThan:
4156 case glslang::EOpLessThanEqual:
4157 case glslang::EOpGreaterThanEqual:
4158 case glslang::EOpEqual:
4159 case glslang::EOpNotEqual:
4160 case glslang::EOpVectorEqual:
4161 case glslang::EOpVectorNotEqual:
4162 comparison = true;
4163 break;
4164 default:
4165 break;
4166 }
4167
John Kessenich7c1aa102015-10-15 13:29:11 -06004168 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004169 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004170 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07004171 if (builder.isMatrix(left) || builder.isMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004172 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004173
4174 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004175 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004176 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004177
qining25262b32016-05-06 17:25:16 -04004178 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004179 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004180 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004181 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004182 }
4183
4184 if (! comparison)
4185 return 0;
4186
John Kessenich7c1aa102015-10-15 13:29:11 -06004187 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004188
John Kessenich4583b612016-08-07 19:14:22 -06004189 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004190 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4191 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004192 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004193 return result;
4194 }
John Kessenich140f3df2015-06-26 16:58:36 -06004195
4196 switch (op) {
4197 case glslang::EOpLessThan:
4198 if (isFloat)
4199 binOp = spv::OpFOrdLessThan;
4200 else if (isUnsigned)
4201 binOp = spv::OpULessThan;
4202 else
4203 binOp = spv::OpSLessThan;
4204 break;
4205 case glslang::EOpGreaterThan:
4206 if (isFloat)
4207 binOp = spv::OpFOrdGreaterThan;
4208 else if (isUnsigned)
4209 binOp = spv::OpUGreaterThan;
4210 else
4211 binOp = spv::OpSGreaterThan;
4212 break;
4213 case glslang::EOpLessThanEqual:
4214 if (isFloat)
4215 binOp = spv::OpFOrdLessThanEqual;
4216 else if (isUnsigned)
4217 binOp = spv::OpULessThanEqual;
4218 else
4219 binOp = spv::OpSLessThanEqual;
4220 break;
4221 case glslang::EOpGreaterThanEqual:
4222 if (isFloat)
4223 binOp = spv::OpFOrdGreaterThanEqual;
4224 else if (isUnsigned)
4225 binOp = spv::OpUGreaterThanEqual;
4226 else
4227 binOp = spv::OpSGreaterThanEqual;
4228 break;
4229 case glslang::EOpEqual:
4230 case glslang::EOpVectorEqual:
4231 if (isFloat)
4232 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004233 else if (isBool)
4234 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004235 else
4236 binOp = spv::OpIEqual;
4237 break;
4238 case glslang::EOpNotEqual:
4239 case glslang::EOpVectorNotEqual:
4240 if (isFloat)
4241 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004242 else if (isBool)
4243 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004244 else
4245 binOp = spv::OpINotEqual;
4246 break;
4247 default:
4248 break;
4249 }
4250
qining25262b32016-05-06 17:25:16 -04004251 if (binOp != spv::OpNop) {
4252 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004253 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004254 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004255 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004256 }
John Kessenich140f3df2015-06-26 16:58:36 -06004257
4258 return 0;
4259}
4260
John Kessenich04bb8a02015-12-12 12:28:14 -07004261//
4262// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
4263// These can be any of:
4264//
4265// matrix * scalar
4266// scalar * matrix
4267// matrix * matrix linear algebraic
4268// matrix * vector
4269// vector * matrix
4270// matrix * matrix componentwise
4271// matrix op matrix op in {+, -, /}
4272// matrix op scalar op in {+, -, /}
4273// scalar op matrix op in {+, -, /}
4274//
John Kessenichead86222018-03-28 18:01:20 -06004275spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4276 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07004277{
4278 bool firstClass = true;
4279
4280 // First, handle first-class matrix operations (* and matrix/scalar)
4281 switch (op) {
4282 case spv::OpFDiv:
4283 if (builder.isMatrix(left) && builder.isScalar(right)) {
4284 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01004285 spv::Id resultType = builder.getTypeId(right);
4286 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07004287 op = spv::OpMatrixTimesScalar;
4288 } else
4289 firstClass = false;
4290 break;
4291 case spv::OpMatrixTimesScalar:
4292 if (builder.isMatrix(right))
4293 std::swap(left, right);
4294 assert(builder.isScalar(right));
4295 break;
4296 case spv::OpVectorTimesMatrix:
4297 assert(builder.isVector(left));
4298 assert(builder.isMatrix(right));
4299 break;
4300 case spv::OpMatrixTimesVector:
4301 assert(builder.isMatrix(left));
4302 assert(builder.isVector(right));
4303 break;
4304 case spv::OpMatrixTimesMatrix:
4305 assert(builder.isMatrix(left));
4306 assert(builder.isMatrix(right));
4307 break;
4308 default:
4309 firstClass = false;
4310 break;
4311 }
4312
qining25262b32016-05-06 17:25:16 -04004313 if (firstClass) {
4314 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004315 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004316 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004317 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004318 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004319
LoopDawg592860c2016-06-09 08:57:35 -06004320 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004321 // The result type of all of them is the same type as the (a) matrix operand.
4322 // The algorithm is to:
4323 // - break the matrix(es) into vectors
4324 // - smear any scalar to a vector
4325 // - do vector operations
4326 // - make a matrix out the vector results
4327 switch (op) {
4328 case spv::OpFAdd:
4329 case spv::OpFSub:
4330 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004331 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004332 case spv::OpFMul:
4333 {
4334 // one time set up...
4335 bool leftMat = builder.isMatrix(left);
4336 bool rightMat = builder.isMatrix(right);
4337 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4338 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4339 spv::Id scalarType = builder.getScalarTypeId(typeId);
4340 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4341 std::vector<spv::Id> results;
4342 spv::Id smearVec = spv::NoResult;
4343 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06004344 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004345 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06004346 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004347
4348 // do each vector op
4349 for (unsigned int c = 0; c < numCols; ++c) {
4350 std::vector<unsigned int> indexes;
4351 indexes.push_back(c);
4352 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4353 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004354 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06004355 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004356 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004357 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004358 }
4359
4360 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004361 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004362 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004363 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07004364 }
4365 default:
4366 assert(0);
4367 return spv::NoResult;
4368 }
4369}
4370
John Kessenichead86222018-03-28 18:01:20 -06004371spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
4372 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004373{
4374 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004375 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004376 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07004377 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4378 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004379
4380 switch (op) {
4381 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004382 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004383 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004384 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06004385 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004386 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004387 unaryOp = spv::OpSNegate;
4388 break;
4389
4390 case glslang::EOpLogicalNot:
4391 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004392 unaryOp = spv::OpLogicalNot;
4393 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004394 case glslang::EOpBitwiseNot:
4395 unaryOp = spv::OpNot;
4396 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004397
John Kessenich140f3df2015-06-26 16:58:36 -06004398 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004399 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004400 break;
4401 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004402 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004403 break;
4404 case glslang::EOpTranspose:
4405 unaryOp = spv::OpTranspose;
4406 break;
4407
4408 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004409 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004410 break;
4411 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004412 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004413 break;
4414 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004415 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004416 break;
4417 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004418 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004419 break;
4420 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004421 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004422 break;
4423 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004424 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004425 break;
4426 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004427 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004428 break;
4429 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004430 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004431 break;
4432
4433 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004434 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004435 break;
4436 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004437 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004438 break;
4439 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004440 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004441 break;
4442 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004443 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004444 break;
4445 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004446 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004447 break;
4448 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004449 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004450 break;
4451
4452 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004453 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004454 break;
4455 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004456 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004457 break;
4458
4459 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004460 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004461 break;
4462 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004463 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004464 break;
4465 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004466 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004467 break;
4468 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004469 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004470 break;
4471 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004472 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004473 break;
4474 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004475 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004476 break;
4477
4478 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004479 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004480 break;
4481 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004482 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004483 break;
4484 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004485 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004486 break;
4487 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004488 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004489 break;
4490 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004491 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004492 break;
4493 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004494 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004495 break;
4496
4497 case glslang::EOpIsNan:
4498 unaryOp = spv::OpIsNan;
4499 break;
4500 case glslang::EOpIsInf:
4501 unaryOp = spv::OpIsInf;
4502 break;
LoopDawg592860c2016-06-09 08:57:35 -06004503 case glslang::EOpIsFinite:
4504 unaryOp = spv::OpIsFinite;
4505 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004506
Rex Xucbc426e2015-12-15 16:03:10 +08004507 case glslang::EOpFloatBitsToInt:
4508 case glslang::EOpFloatBitsToUint:
4509 case glslang::EOpIntBitsToFloat:
4510 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004511 case glslang::EOpDoubleBitsToInt64:
4512 case glslang::EOpDoubleBitsToUint64:
4513 case glslang::EOpInt64BitsToDouble:
4514 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004515 case glslang::EOpFloat16BitsToInt16:
4516 case glslang::EOpFloat16BitsToUint16:
4517 case glslang::EOpInt16BitsToFloat16:
4518 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08004519 unaryOp = spv::OpBitcast;
4520 break;
4521
John Kessenich140f3df2015-06-26 16:58:36 -06004522 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004523 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004524 break;
4525 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004526 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004527 break;
4528 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004529 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004530 break;
4531 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004532 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004533 break;
4534 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004535 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004536 break;
4537 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004538 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004539 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004540 case glslang::EOpPackSnorm4x8:
4541 libCall = spv::GLSLstd450PackSnorm4x8;
4542 break;
4543 case glslang::EOpUnpackSnorm4x8:
4544 libCall = spv::GLSLstd450UnpackSnorm4x8;
4545 break;
4546 case glslang::EOpPackUnorm4x8:
4547 libCall = spv::GLSLstd450PackUnorm4x8;
4548 break;
4549 case glslang::EOpUnpackUnorm4x8:
4550 libCall = spv::GLSLstd450UnpackUnorm4x8;
4551 break;
4552 case glslang::EOpPackDouble2x32:
4553 libCall = spv::GLSLstd450PackDouble2x32;
4554 break;
4555 case glslang::EOpUnpackDouble2x32:
4556 libCall = spv::GLSLstd450UnpackDouble2x32;
4557 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004558
Rex Xu8ff43de2016-04-22 16:51:45 +08004559 case glslang::EOpPackInt2x32:
4560 case glslang::EOpUnpackInt2x32:
4561 case glslang::EOpPackUint2x32:
4562 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07004563 case glslang::EOpPack16:
4564 case glslang::EOpPack32:
4565 case glslang::EOpPack64:
4566 case glslang::EOpUnpack32:
4567 case glslang::EOpUnpack16:
4568 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08004569 case glslang::EOpPackInt2x16:
4570 case glslang::EOpUnpackInt2x16:
4571 case glslang::EOpPackUint2x16:
4572 case glslang::EOpUnpackUint2x16:
4573 case glslang::EOpPackInt4x16:
4574 case glslang::EOpUnpackInt4x16:
4575 case glslang::EOpPackUint4x16:
4576 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004577 case glslang::EOpPackFloat2x16:
4578 case glslang::EOpUnpackFloat2x16:
4579 unaryOp = spv::OpBitcast;
4580 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004581
John Kessenich140f3df2015-06-26 16:58:36 -06004582 case glslang::EOpDPdx:
4583 unaryOp = spv::OpDPdx;
4584 break;
4585 case glslang::EOpDPdy:
4586 unaryOp = spv::OpDPdy;
4587 break;
4588 case glslang::EOpFwidth:
4589 unaryOp = spv::OpFwidth;
4590 break;
4591 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004592 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004593 unaryOp = spv::OpDPdxFine;
4594 break;
4595 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004596 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004597 unaryOp = spv::OpDPdyFine;
4598 break;
4599 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004600 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004601 unaryOp = spv::OpFwidthFine;
4602 break;
4603 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004604 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004605 unaryOp = spv::OpDPdxCoarse;
4606 break;
4607 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004608 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004609 unaryOp = spv::OpDPdyCoarse;
4610 break;
4611 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004612 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004613 unaryOp = spv::OpFwidthCoarse;
4614 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004615 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004616 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004617 libCall = spv::GLSLstd450InterpolateAtCentroid;
4618 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004619 case glslang::EOpAny:
4620 unaryOp = spv::OpAny;
4621 break;
4622 case glslang::EOpAll:
4623 unaryOp = spv::OpAll;
4624 break;
4625
4626 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004627 if (isFloat)
4628 libCall = spv::GLSLstd450FAbs;
4629 else
4630 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004631 break;
4632 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004633 if (isFloat)
4634 libCall = spv::GLSLstd450FSign;
4635 else
4636 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004637 break;
4638
John Kessenichfc51d282015-08-19 13:34:18 -06004639 case glslang::EOpAtomicCounterIncrement:
4640 case glslang::EOpAtomicCounterDecrement:
4641 case glslang::EOpAtomicCounter:
4642 {
4643 // Handle all of the atomics in one place, in createAtomicOperation()
4644 std::vector<spv::Id> operands;
4645 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06004646 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004647 }
4648
John Kessenichfc51d282015-08-19 13:34:18 -06004649 case glslang::EOpBitFieldReverse:
4650 unaryOp = spv::OpBitReverse;
4651 break;
4652 case glslang::EOpBitCount:
4653 unaryOp = spv::OpBitCount;
4654 break;
4655 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004656 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004657 break;
4658 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004659 if (isUnsigned)
4660 libCall = spv::GLSLstd450FindUMsb;
4661 else
4662 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004663 break;
4664
Rex Xu574ab042016-04-14 16:53:07 +08004665 case glslang::EOpBallot:
4666 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004667 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004668 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004669 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004670#ifdef AMD_EXTENSIONS
4671 case glslang::EOpMinInvocations:
4672 case glslang::EOpMaxInvocations:
4673 case glslang::EOpAddInvocations:
4674 case glslang::EOpMinInvocationsNonUniform:
4675 case glslang::EOpMaxInvocationsNonUniform:
4676 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004677 case glslang::EOpMinInvocationsInclusiveScan:
4678 case glslang::EOpMaxInvocationsInclusiveScan:
4679 case glslang::EOpAddInvocationsInclusiveScan:
4680 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4681 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4682 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4683 case glslang::EOpMinInvocationsExclusiveScan:
4684 case glslang::EOpMaxInvocationsExclusiveScan:
4685 case glslang::EOpAddInvocationsExclusiveScan:
4686 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4687 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4688 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004689#endif
Rex Xu51596642016-09-21 18:56:12 +08004690 {
4691 std::vector<spv::Id> operands;
4692 operands.push_back(operand);
4693 return createInvocationsOperation(op, typeId, operands, typeProxy);
4694 }
John Kessenich66011cb2018-03-06 16:12:04 -07004695 case glslang::EOpSubgroupAll:
4696 case glslang::EOpSubgroupAny:
4697 case glslang::EOpSubgroupAllEqual:
4698 case glslang::EOpSubgroupBroadcastFirst:
4699 case glslang::EOpSubgroupBallot:
4700 case glslang::EOpSubgroupInverseBallot:
4701 case glslang::EOpSubgroupBallotBitCount:
4702 case glslang::EOpSubgroupBallotInclusiveBitCount:
4703 case glslang::EOpSubgroupBallotExclusiveBitCount:
4704 case glslang::EOpSubgroupBallotFindLSB:
4705 case glslang::EOpSubgroupBallotFindMSB:
4706 case glslang::EOpSubgroupAdd:
4707 case glslang::EOpSubgroupMul:
4708 case glslang::EOpSubgroupMin:
4709 case glslang::EOpSubgroupMax:
4710 case glslang::EOpSubgroupAnd:
4711 case glslang::EOpSubgroupOr:
4712 case glslang::EOpSubgroupXor:
4713 case glslang::EOpSubgroupInclusiveAdd:
4714 case glslang::EOpSubgroupInclusiveMul:
4715 case glslang::EOpSubgroupInclusiveMin:
4716 case glslang::EOpSubgroupInclusiveMax:
4717 case glslang::EOpSubgroupInclusiveAnd:
4718 case glslang::EOpSubgroupInclusiveOr:
4719 case glslang::EOpSubgroupInclusiveXor:
4720 case glslang::EOpSubgroupExclusiveAdd:
4721 case glslang::EOpSubgroupExclusiveMul:
4722 case glslang::EOpSubgroupExclusiveMin:
4723 case glslang::EOpSubgroupExclusiveMax:
4724 case glslang::EOpSubgroupExclusiveAnd:
4725 case glslang::EOpSubgroupExclusiveOr:
4726 case glslang::EOpSubgroupExclusiveXor:
4727 case glslang::EOpSubgroupQuadSwapHorizontal:
4728 case glslang::EOpSubgroupQuadSwapVertical:
4729 case glslang::EOpSubgroupQuadSwapDiagonal: {
4730 std::vector<spv::Id> operands;
4731 operands.push_back(operand);
4732 return createSubgroupOperation(op, typeId, operands, typeProxy);
4733 }
Rex Xu9d93a232016-05-05 12:30:44 +08004734#ifdef AMD_EXTENSIONS
4735 case glslang::EOpMbcnt:
4736 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4737 libCall = spv::MbcntAMD;
4738 break;
4739
4740 case glslang::EOpCubeFaceIndex:
4741 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4742 libCall = spv::CubeFaceIndexAMD;
4743 break;
4744
4745 case glslang::EOpCubeFaceCoord:
4746 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4747 libCall = spv::CubeFaceCoordAMD;
4748 break;
4749#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05004750#ifdef NV_EXTENSIONS
4751 case glslang::EOpSubgroupPartition:
4752 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
4753 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
4754 unaryOp = spv::OpGroupNonUniformPartitionNV;
4755 break;
4756#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004757 default:
4758 return 0;
4759 }
4760
4761 spv::Id id;
4762 if (libCall >= 0) {
4763 std::vector<spv::Id> args;
4764 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004765 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004766 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004767 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004768 }
John Kessenich140f3df2015-06-26 16:58:36 -06004769
John Kessenichead86222018-03-28 18:01:20 -06004770 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004771 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004772 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004773}
4774
John Kessenich7a53f762016-01-20 11:19:27 -07004775// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06004776spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4777 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07004778{
4779 // Handle unary operations vector by vector.
4780 // The result type is the same type as the original type.
4781 // The algorithm is to:
4782 // - break the matrix into vectors
4783 // - apply the operation to each vector
4784 // - make a matrix out the vector results
4785
4786 // get the types sorted out
4787 int numCols = builder.getNumColumns(operand);
4788 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004789 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4790 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004791 std::vector<spv::Id> results;
4792
4793 // do each vector op
4794 for (int c = 0; c < numCols; ++c) {
4795 std::vector<unsigned int> indexes;
4796 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004797 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4798 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06004799 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004800 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004801 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004802 }
4803
4804 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004805 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004806 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004807 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07004808}
4809
John Kessenich66011cb2018-03-06 16:12:04 -07004810spv::Id TGlslangToSpvTraverser::createConversionOperation(glslang::TOperator op, spv::Id operand, int vectorSize)
4811{
4812 spv::Op convOp = spv::OpNop;
4813 spv::Id type = 0;
4814
4815 spv::Id result = 0;
4816
4817 switch(op) {
4818 case glslang::EOpConvInt8ToUint16:
4819 convOp = spv::OpSConvert;
4820 type = builder.makeIntType(16);
4821 break;
4822 case glslang::EOpConvInt8ToUint:
4823 convOp = spv::OpSConvert;
4824 type = builder.makeIntType(32);
4825 break;
4826 case glslang::EOpConvInt8ToUint64:
4827 convOp = spv::OpSConvert;
4828 type = builder.makeIntType(64);
4829 break;
4830 case glslang::EOpConvInt16ToUint8:
4831 convOp = spv::OpSConvert;
4832 type = builder.makeIntType(8);
4833 break;
4834 case glslang::EOpConvInt16ToUint:
4835 convOp = spv::OpSConvert;
4836 type = builder.makeIntType(32);
4837 break;
4838 case glslang::EOpConvInt16ToUint64:
4839 convOp = spv::OpSConvert;
4840 type = builder.makeIntType(64);
4841 break;
4842 case glslang::EOpConvIntToUint8:
4843 convOp = spv::OpSConvert;
4844 type = builder.makeIntType(8);
4845 break;
4846 case glslang::EOpConvIntToUint16:
4847 convOp = spv::OpSConvert;
4848 type = builder.makeIntType(16);
4849 break;
4850 case glslang::EOpConvIntToUint64:
4851 convOp = spv::OpSConvert;
4852 type = builder.makeIntType(64);
4853 break;
4854 case glslang::EOpConvInt64ToUint8:
4855 convOp = spv::OpSConvert;
4856 type = builder.makeIntType(8);
4857 break;
4858 case glslang::EOpConvInt64ToUint16:
4859 convOp = spv::OpSConvert;
4860 type = builder.makeIntType(16);
4861 break;
4862 case glslang::EOpConvInt64ToUint:
4863 convOp = spv::OpSConvert;
4864 type = builder.makeIntType(32);
4865 break;
4866 case glslang::EOpConvUint8ToInt16:
4867 convOp = spv::OpUConvert;
4868 type = builder.makeIntType(16);
4869 break;
4870 case glslang::EOpConvUint8ToInt:
4871 convOp = spv::OpUConvert;
4872 type = builder.makeIntType(32);
4873 break;
4874 case glslang::EOpConvUint8ToInt64:
4875 convOp = spv::OpUConvert;
4876 type = builder.makeIntType(64);
4877 break;
4878 case glslang::EOpConvUint16ToInt8:
4879 convOp = spv::OpUConvert;
4880 type = builder.makeIntType(8);
4881 break;
4882 case glslang::EOpConvUint16ToInt:
4883 convOp = spv::OpUConvert;
4884 type = builder.makeIntType(32);
4885 break;
4886 case glslang::EOpConvUint16ToInt64:
4887 convOp = spv::OpUConvert;
4888 type = builder.makeIntType(64);
4889 break;
4890 case glslang::EOpConvUintToInt8:
4891 convOp = spv::OpUConvert;
4892 type = builder.makeIntType(8);
4893 break;
4894 case glslang::EOpConvUintToInt16:
4895 convOp = spv::OpUConvert;
4896 type = builder.makeIntType(16);
4897 break;
4898 case glslang::EOpConvUintToInt64:
4899 convOp = spv::OpUConvert;
4900 type = builder.makeIntType(64);
4901 break;
4902 case glslang::EOpConvUint64ToInt8:
4903 convOp = spv::OpUConvert;
4904 type = builder.makeIntType(8);
4905 break;
4906 case glslang::EOpConvUint64ToInt16:
4907 convOp = spv::OpUConvert;
4908 type = builder.makeIntType(16);
4909 break;
4910 case glslang::EOpConvUint64ToInt:
4911 convOp = spv::OpUConvert;
4912 type = builder.makeIntType(32);
4913 break;
4914
4915 default:
4916 assert(false && "Default missing");
4917 break;
4918 }
4919
4920 if (vectorSize > 0)
4921 type = builder.makeVectorType(type, vectorSize);
4922
4923 result = builder.createUnaryOp(convOp, type, operand);
4924 return result;
4925}
4926
John Kessenichead86222018-03-28 18:01:20 -06004927spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
4928 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004929{
4930 spv::Op convOp = spv::OpNop;
4931 spv::Id zero = 0;
4932 spv::Id one = 0;
4933
4934 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4935
4936 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07004937 case glslang::EOpConvInt8ToBool:
4938 case glslang::EOpConvUint8ToBool:
4939 zero = builder.makeUint8Constant(0);
4940 zero = makeSmearedConstant(zero, vectorSize);
4941 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08004942 case glslang::EOpConvInt16ToBool:
4943 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07004944 zero = builder.makeUint16Constant(0);
4945 zero = makeSmearedConstant(zero, vectorSize);
4946 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4947 case glslang::EOpConvIntToBool:
4948 case glslang::EOpConvUintToBool:
4949 zero = builder.makeUintConstant(0);
4950 zero = makeSmearedConstant(zero, vectorSize);
4951 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4952 case glslang::EOpConvInt64ToBool:
4953 case glslang::EOpConvUint64ToBool:
4954 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004955 zero = makeSmearedConstant(zero, vectorSize);
4956 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4957
4958 case glslang::EOpConvFloatToBool:
4959 zero = builder.makeFloatConstant(0.0F);
4960 zero = makeSmearedConstant(zero, vectorSize);
4961 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4962
4963 case glslang::EOpConvDoubleToBool:
4964 zero = builder.makeDoubleConstant(0.0);
4965 zero = makeSmearedConstant(zero, vectorSize);
4966 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4967
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004968 case glslang::EOpConvFloat16ToBool:
4969 zero = builder.makeFloat16Constant(0.0F);
4970 zero = makeSmearedConstant(zero, vectorSize);
4971 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004972
John Kessenich140f3df2015-06-26 16:58:36 -06004973 case glslang::EOpConvBoolToFloat:
4974 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004975 zero = builder.makeFloatConstant(0.0F);
4976 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004977 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004978
John Kessenich140f3df2015-06-26 16:58:36 -06004979 case glslang::EOpConvBoolToDouble:
4980 convOp = spv::OpSelect;
4981 zero = builder.makeDoubleConstant(0.0);
4982 one = builder.makeDoubleConstant(1.0);
4983 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004984
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004985 case glslang::EOpConvBoolToFloat16:
4986 convOp = spv::OpSelect;
4987 zero = builder.makeFloat16Constant(0.0F);
4988 one = builder.makeFloat16Constant(1.0F);
4989 break;
John Kessenich66011cb2018-03-06 16:12:04 -07004990
4991 case glslang::EOpConvBoolToInt8:
4992 zero = builder.makeInt8Constant(0);
4993 one = builder.makeInt8Constant(1);
4994 convOp = spv::OpSelect;
4995 break;
4996
4997 case glslang::EOpConvBoolToUint8:
4998 zero = builder.makeUint8Constant(0);
4999 one = builder.makeUint8Constant(1);
5000 convOp = spv::OpSelect;
5001 break;
5002
5003 case glslang::EOpConvBoolToInt16:
5004 zero = builder.makeInt16Constant(0);
5005 one = builder.makeInt16Constant(1);
5006 convOp = spv::OpSelect;
5007 break;
5008
5009 case glslang::EOpConvBoolToUint16:
5010 zero = builder.makeUint16Constant(0);
5011 one = builder.makeUint16Constant(1);
5012 convOp = spv::OpSelect;
5013 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005014
John Kessenich140f3df2015-06-26 16:58:36 -06005015 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005016 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005017 if (op == glslang::EOpConvBoolToInt64)
5018 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005019 else
5020 zero = builder.makeIntConstant(0);
5021
5022 if (op == glslang::EOpConvBoolToInt64)
5023 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005024 else
5025 one = builder.makeIntConstant(1);
5026
John Kessenich140f3df2015-06-26 16:58:36 -06005027 convOp = spv::OpSelect;
5028 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005029
John Kessenich140f3df2015-06-26 16:58:36 -06005030 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005031 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005032 if (op == glslang::EOpConvBoolToUint64)
5033 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005034 else
5035 zero = builder.makeUintConstant(0);
5036
5037 if (op == glslang::EOpConvBoolToUint64)
5038 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005039 else
5040 one = builder.makeUintConstant(1);
5041
John Kessenich140f3df2015-06-26 16:58:36 -06005042 convOp = spv::OpSelect;
5043 break;
5044
John Kessenich66011cb2018-03-06 16:12:04 -07005045 case glslang::EOpConvInt8ToFloat16:
5046 case glslang::EOpConvInt8ToFloat:
5047 case glslang::EOpConvInt8ToDouble:
5048 case glslang::EOpConvInt16ToFloat16:
5049 case glslang::EOpConvInt16ToFloat:
5050 case glslang::EOpConvInt16ToDouble:
5051 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005052 case glslang::EOpConvIntToFloat:
5053 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005054 case glslang::EOpConvInt64ToFloat:
5055 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005056 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005057 convOp = spv::OpConvertSToF;
5058 break;
5059
John Kessenich66011cb2018-03-06 16:12:04 -07005060 case glslang::EOpConvUint8ToFloat16:
5061 case glslang::EOpConvUint8ToFloat:
5062 case glslang::EOpConvUint8ToDouble:
5063 case glslang::EOpConvUint16ToFloat16:
5064 case glslang::EOpConvUint16ToFloat:
5065 case glslang::EOpConvUint16ToDouble:
5066 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005067 case glslang::EOpConvUintToFloat:
5068 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005069 case glslang::EOpConvUint64ToFloat:
5070 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005071 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005072 convOp = spv::OpConvertUToF;
5073 break;
5074
5075 case glslang::EOpConvDoubleToFloat:
5076 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005077 case glslang::EOpConvDoubleToFloat16:
5078 case glslang::EOpConvFloat16ToDouble:
5079 case glslang::EOpConvFloatToFloat16:
5080 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005081 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005082 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005083 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005084 break;
5085
John Kessenich66011cb2018-03-06 16:12:04 -07005086 case glslang::EOpConvFloat16ToInt8:
5087 case glslang::EOpConvFloatToInt8:
5088 case glslang::EOpConvDoubleToInt8:
5089 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005090 case glslang::EOpConvFloatToInt16:
5091 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005092 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005093 case glslang::EOpConvFloatToInt:
5094 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005095 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005096 case glslang::EOpConvFloatToInt64:
5097 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005098 convOp = spv::OpConvertFToS;
5099 break;
5100
John Kessenich66011cb2018-03-06 16:12:04 -07005101 case glslang::EOpConvUint8ToInt8:
5102 case glslang::EOpConvInt8ToUint8:
5103 case glslang::EOpConvUint16ToInt16:
5104 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005105 case glslang::EOpConvUintToInt:
5106 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005107 case glslang::EOpConvUint64ToInt64:
5108 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005109 if (builder.isInSpecConstCodeGenMode()) {
5110 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005111 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5112 zero = builder.makeUint8Constant(0);
5113 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005114 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005115 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5116 zero = builder.makeUint64Constant(0);
5117 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005118 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005119 }
qining189b2032016-04-12 23:16:20 -04005120 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005121 // Use OpIAdd, instead of OpBitcast to do the conversion when
5122 // generating for OpSpecConstantOp instruction.
5123 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5124 }
5125 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005126 convOp = spv::OpBitcast;
5127 break;
5128
John Kessenich66011cb2018-03-06 16:12:04 -07005129 case glslang::EOpConvFloat16ToUint8:
5130 case glslang::EOpConvFloatToUint8:
5131 case glslang::EOpConvDoubleToUint8:
5132 case glslang::EOpConvFloat16ToUint16:
5133 case glslang::EOpConvFloatToUint16:
5134 case glslang::EOpConvDoubleToUint16:
5135 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005136 case glslang::EOpConvFloatToUint:
5137 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005138 case glslang::EOpConvFloatToUint64:
5139 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005140 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005141 convOp = spv::OpConvertFToU;
5142 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005143
John Kessenich66011cb2018-03-06 16:12:04 -07005144 case glslang::EOpConvInt8ToInt16:
5145 case glslang::EOpConvInt8ToInt:
5146 case glslang::EOpConvInt8ToInt64:
5147 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005148 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005149 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005150 case glslang::EOpConvIntToInt8:
5151 case glslang::EOpConvIntToInt16:
5152 case glslang::EOpConvIntToInt64:
5153 case glslang::EOpConvInt64ToInt8:
5154 case glslang::EOpConvInt64ToInt16:
5155 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005156 convOp = spv::OpSConvert;
5157 break;
5158
John Kessenich66011cb2018-03-06 16:12:04 -07005159 case glslang::EOpConvUint8ToUint16:
5160 case glslang::EOpConvUint8ToUint:
5161 case glslang::EOpConvUint8ToUint64:
5162 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005163 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005164 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005165 case glslang::EOpConvUintToUint8:
5166 case glslang::EOpConvUintToUint16:
5167 case glslang::EOpConvUintToUint64:
5168 case glslang::EOpConvUint64ToUint8:
5169 case glslang::EOpConvUint64ToUint16:
5170 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005171 convOp = spv::OpUConvert;
5172 break;
5173
John Kessenich66011cb2018-03-06 16:12:04 -07005174 case glslang::EOpConvInt8ToUint16:
5175 case glslang::EOpConvInt8ToUint:
5176 case glslang::EOpConvInt8ToUint64:
5177 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005178 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005179 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005180 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005181 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005182 case glslang::EOpConvIntToUint64:
5183 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005184 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005185 case glslang::EOpConvInt64ToUint:
5186 case glslang::EOpConvUint8ToInt16:
5187 case glslang::EOpConvUint8ToInt:
5188 case glslang::EOpConvUint8ToInt64:
5189 case glslang::EOpConvUint16ToInt8:
5190 case glslang::EOpConvUint16ToInt:
5191 case glslang::EOpConvUint16ToInt64:
5192 case glslang::EOpConvUintToInt8:
5193 case glslang::EOpConvUintToInt16:
5194 case glslang::EOpConvUintToInt64:
5195 case glslang::EOpConvUint64ToInt8:
5196 case glslang::EOpConvUint64ToInt16:
5197 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005198 // OpSConvert/OpUConvert + OpBitCast
John Kessenich66011cb2018-03-06 16:12:04 -07005199 operand = createConversionOperation(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005200
5201 if (builder.isInSpecConstCodeGenMode()) {
5202 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005203 switch(op) {
5204 case glslang::EOpConvInt16ToUint8:
5205 case glslang::EOpConvIntToUint8:
5206 case glslang::EOpConvInt64ToUint8:
5207 case glslang::EOpConvUint16ToInt8:
5208 case glslang::EOpConvUintToInt8:
5209 case glslang::EOpConvUint64ToInt8:
5210 zero = builder.makeUint8Constant(0);
5211 break;
5212 case glslang::EOpConvInt8ToUint16:
5213 case glslang::EOpConvIntToUint16:
5214 case glslang::EOpConvInt64ToUint16:
5215 case glslang::EOpConvUint8ToInt16:
5216 case glslang::EOpConvUintToInt16:
5217 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005218 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005219 break;
5220 case glslang::EOpConvInt8ToUint:
5221 case glslang::EOpConvInt16ToUint:
5222 case glslang::EOpConvInt64ToUint:
5223 case glslang::EOpConvUint8ToInt:
5224 case glslang::EOpConvUint16ToInt:
5225 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005226 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005227 break;
5228 case glslang::EOpConvInt8ToUint64:
5229 case glslang::EOpConvInt16ToUint64:
5230 case glslang::EOpConvIntToUint64:
5231 case glslang::EOpConvUint8ToInt64:
5232 case glslang::EOpConvUint16ToInt64:
5233 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005234 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005235 break;
5236 default:
5237 assert(false && "Default missing");
5238 break;
5239 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005240 zero = makeSmearedConstant(zero, vectorSize);
5241 // Use OpIAdd, instead of OpBitcast to do the conversion when
5242 // generating for OpSpecConstantOp instruction.
5243 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5244 }
5245 // For normal run-time conversion instruction, use OpBitcast.
5246 convOp = spv::OpBitcast;
5247 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005248 default:
5249 break;
5250 }
5251
5252 spv::Id result = 0;
5253 if (convOp == spv::OpNop)
5254 return result;
5255
5256 if (convOp == spv::OpSelect) {
5257 zero = makeSmearedConstant(zero, vectorSize);
5258 one = makeSmearedConstant(one, vectorSize);
5259 result = builder.createTriOp(convOp, destType, operand, one, zero);
5260 } else
5261 result = builder.createUnaryOp(convOp, destType, operand);
5262
John Kessenichead86222018-03-28 18:01:20 -06005263 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005264 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005265 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06005266}
5267
5268spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
5269{
5270 if (vectorSize == 0)
5271 return constant;
5272
5273 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
5274 std::vector<spv::Id> components;
5275 for (int c = 0; c < vectorSize; ++c)
5276 components.push_back(constant);
5277 return builder.makeCompositeConstant(vectorTypeId, components);
5278}
5279
John Kessenich426394d2015-07-23 10:22:48 -06005280// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07005281spv::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 -06005282{
5283 spv::Op opCode = spv::OpNop;
5284
5285 switch (op) {
5286 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08005287 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005288 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06005289 opCode = spv::OpAtomicIAdd;
5290 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06005291 case glslang::EOpAtomicCounterSubtract:
5292 opCode = spv::OpAtomicISub;
5293 break;
John Kessenich426394d2015-07-23 10:22:48 -06005294 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08005295 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005296 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08005297 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06005298 break;
5299 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08005300 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005301 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08005302 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06005303 break;
5304 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08005305 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005306 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06005307 opCode = spv::OpAtomicAnd;
5308 break;
5309 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08005310 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005311 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06005312 opCode = spv::OpAtomicOr;
5313 break;
5314 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08005315 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005316 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06005317 opCode = spv::OpAtomicXor;
5318 break;
5319 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08005320 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005321 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06005322 opCode = spv::OpAtomicExchange;
5323 break;
5324 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08005325 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005326 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06005327 opCode = spv::OpAtomicCompareExchange;
5328 break;
5329 case glslang::EOpAtomicCounterIncrement:
5330 opCode = spv::OpAtomicIIncrement;
5331 break;
5332 case glslang::EOpAtomicCounterDecrement:
5333 opCode = spv::OpAtomicIDecrement;
5334 break;
5335 case glslang::EOpAtomicCounter:
5336 opCode = spv::OpAtomicLoad;
5337 break;
5338 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005339 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06005340 break;
5341 }
5342
Rex Xue8fe8b02017-09-26 15:42:56 +08005343 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
5344 builder.addCapability(spv::CapabilityInt64Atomics);
5345
John Kessenich426394d2015-07-23 10:22:48 -06005346 // Sort out the operands
5347 // - mapping from glslang -> SPV
5348 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06005349 // - compare-exchange swaps the value and comparator
5350 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06005351 // - EOpAtomicCounterDecrement needs a post decrement
John Kessenich426394d2015-07-23 10:22:48 -06005352 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
5353 auto opIt = operands.begin(); // walk the glslang operands
5354 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08005355 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
5356 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
5357 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08005358 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
5359 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08005360 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06005361 spvAtomicOperands.push_back(*(opIt + 1));
5362 spvAtomicOperands.push_back(*opIt);
5363 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08005364 }
John Kessenich426394d2015-07-23 10:22:48 -06005365
John Kessenich3e60a6f2015-09-14 22:45:16 -06005366 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06005367 for (; opIt != operands.end(); ++opIt)
5368 spvAtomicOperands.push_back(*opIt);
5369
John Kessenich48d6e792017-10-06 21:21:48 -06005370 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
5371
5372 // GLSL and HLSL atomic-counter decrement return post-decrement value,
5373 // while SPIR-V returns pre-decrement value. Translate between these semantics.
5374 if (op == glslang::EOpAtomicCounterDecrement)
5375 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
5376
5377 return resultId;
John Kessenich426394d2015-07-23 10:22:48 -06005378}
5379
John Kessenich91cef522016-05-05 16:45:40 -06005380// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08005381spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06005382{
John Kessenich66011cb2018-03-06 16:12:04 -07005383 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5384 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08005385
Rex Xu51596642016-09-21 18:56:12 +08005386 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08005387 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08005388 spv::GroupOperation groupOperation = spv::GroupOperationMax;
5389
chaocf200da82016-12-20 12:44:35 -08005390 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
5391 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08005392 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
5393 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005394 } else if (op == glslang::EOpAnyInvocation ||
5395 op == glslang::EOpAllInvocations ||
5396 op == glslang::EOpAllInvocationsEqual) {
5397 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
5398 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08005399 } else {
5400 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04005401#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08005402 if (op == glslang::EOpMinInvocationsNonUniform ||
5403 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08005404 op == glslang::EOpAddInvocationsNonUniform ||
5405 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5406 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5407 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
5408 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
5409 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
5410 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08005411 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04005412#endif
Rex Xu51596642016-09-21 18:56:12 +08005413
5414 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08005415#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08005416 switch (op) {
5417 case glslang::EOpMinInvocations:
5418 case glslang::EOpMaxInvocations:
5419 case glslang::EOpAddInvocations:
5420 case glslang::EOpMinInvocationsNonUniform:
5421 case glslang::EOpMaxInvocationsNonUniform:
5422 case glslang::EOpAddInvocationsNonUniform:
5423 groupOperation = spv::GroupOperationReduce;
5424 spvGroupOperands.push_back(groupOperation);
5425 break;
5426 case glslang::EOpMinInvocationsInclusiveScan:
5427 case glslang::EOpMaxInvocationsInclusiveScan:
5428 case glslang::EOpAddInvocationsInclusiveScan:
5429 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5430 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5431 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5432 groupOperation = spv::GroupOperationInclusiveScan;
5433 spvGroupOperands.push_back(groupOperation);
5434 break;
5435 case glslang::EOpMinInvocationsExclusiveScan:
5436 case glslang::EOpMaxInvocationsExclusiveScan:
5437 case glslang::EOpAddInvocationsExclusiveScan:
5438 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5439 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5440 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5441 groupOperation = spv::GroupOperationExclusiveScan;
5442 spvGroupOperands.push_back(groupOperation);
5443 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07005444 default:
5445 break;
Rex Xu430ef402016-10-14 17:22:23 +08005446 }
Rex Xu9d93a232016-05-05 12:30:44 +08005447#endif
Rex Xu51596642016-09-21 18:56:12 +08005448 }
5449
5450 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
5451 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06005452
5453 switch (op) {
5454 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005455 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08005456 break;
John Kessenich91cef522016-05-05 16:45:40 -06005457 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005458 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08005459 break;
John Kessenich91cef522016-05-05 16:45:40 -06005460 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005461 opCode = spv::OpSubgroupAllEqualKHR;
5462 break;
Rex Xu51596642016-09-21 18:56:12 +08005463 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08005464 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08005465 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005466 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005467 break;
5468 case glslang::EOpReadFirstInvocation:
5469 opCode = spv::OpSubgroupFirstInvocationKHR;
5470 break;
5471 case glslang::EOpBallot:
5472 {
5473 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
5474 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
5475 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
5476 //
5477 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
5478 //
5479 spv::Id uintType = builder.makeUintType(32);
5480 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
5481 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
5482
5483 std::vector<spv::Id> components;
5484 components.push_back(builder.createCompositeExtract(result, uintType, 0));
5485 components.push_back(builder.createCompositeExtract(result, uintType, 1));
5486
5487 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
5488 return builder.createUnaryOp(spv::OpBitcast, typeId,
5489 builder.createCompositeConstruct(uvec2Type, components));
5490 }
5491
Rex Xu9d93a232016-05-05 12:30:44 +08005492#ifdef AMD_EXTENSIONS
5493 case glslang::EOpMinInvocations:
5494 case glslang::EOpMaxInvocations:
5495 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08005496 case glslang::EOpMinInvocationsInclusiveScan:
5497 case glslang::EOpMaxInvocationsInclusiveScan:
5498 case glslang::EOpAddInvocationsInclusiveScan:
5499 case glslang::EOpMinInvocationsExclusiveScan:
5500 case glslang::EOpMaxInvocationsExclusiveScan:
5501 case glslang::EOpAddInvocationsExclusiveScan:
5502 if (op == glslang::EOpMinInvocations ||
5503 op == glslang::EOpMinInvocationsInclusiveScan ||
5504 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005505 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005506 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005507 else {
5508 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005509 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005510 else
Rex Xu51596642016-09-21 18:56:12 +08005511 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005512 }
Rex Xu430ef402016-10-14 17:22:23 +08005513 } else if (op == glslang::EOpMaxInvocations ||
5514 op == glslang::EOpMaxInvocationsInclusiveScan ||
5515 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005516 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005517 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005518 else {
5519 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005520 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005521 else
Rex Xu51596642016-09-21 18:56:12 +08005522 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005523 }
5524 } else {
5525 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005526 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005527 else
Rex Xu51596642016-09-21 18:56:12 +08005528 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005529 }
5530
Rex Xu2bbbe062016-08-23 15:41:05 +08005531 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005532 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005533
5534 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005535 case glslang::EOpMinInvocationsNonUniform:
5536 case glslang::EOpMaxInvocationsNonUniform:
5537 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005538 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5539 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5540 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5541 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5542 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5543 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5544 if (op == glslang::EOpMinInvocationsNonUniform ||
5545 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5546 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005547 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005548 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005549 else {
5550 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005551 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005552 else
Rex Xu51596642016-09-21 18:56:12 +08005553 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005554 }
5555 }
Rex Xu430ef402016-10-14 17:22:23 +08005556 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5557 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5558 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005559 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005560 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005561 else {
5562 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005563 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005564 else
Rex Xu51596642016-09-21 18:56:12 +08005565 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005566 }
5567 }
5568 else {
5569 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005570 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005571 else
Rex Xu51596642016-09-21 18:56:12 +08005572 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005573 }
5574
Rex Xu2bbbe062016-08-23 15:41:05 +08005575 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005576 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005577
5578 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005579#endif
John Kessenich91cef522016-05-05 16:45:40 -06005580 default:
5581 logger->missingFunctionality("invocation operation");
5582 return spv::NoResult;
5583 }
Rex Xu51596642016-09-21 18:56:12 +08005584
5585 assert(opCode != spv::OpNop);
5586 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005587}
5588
Rex Xu2bbbe062016-08-23 15:41:05 +08005589// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005590spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005591{
Rex Xub7072052016-09-26 15:53:40 +08005592#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005593 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5594 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005595 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005596 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005597 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5598 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5599 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005600#else
5601 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5602 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005603 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5604 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005605#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005606
5607 // Handle group invocation operations scalar by scalar.
5608 // The result type is the same type as the original type.
5609 // The algorithm is to:
5610 // - break the vector into scalars
5611 // - apply the operation to each scalar
5612 // - make a vector out the scalar results
5613
5614 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005615 int numComponents = builder.getNumComponents(operands[0]);
5616 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005617 std::vector<spv::Id> results;
5618
5619 // do each scalar op
5620 for (int comp = 0; comp < numComponents; ++comp) {
5621 std::vector<unsigned int> indexes;
5622 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005623 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005624 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005625 if (op == spv::OpSubgroupReadInvocationKHR) {
5626 spvGroupOperands.push_back(scalar);
5627 spvGroupOperands.push_back(operands[1]);
5628 } else if (op == spv::OpGroupBroadcast) {
5629 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005630 spvGroupOperands.push_back(scalar);
5631 spvGroupOperands.push_back(operands[1]);
5632 } else {
chaocf200da82016-12-20 12:44:35 -08005633 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005634 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005635 spvGroupOperands.push_back(scalar);
5636 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005637
Rex Xub7072052016-09-26 15:53:40 +08005638 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005639 }
5640
5641 // put the pieces together
5642 return builder.createCompositeConstruct(typeId, results);
5643}
Rex Xu2bbbe062016-08-23 15:41:05 +08005644
John Kessenich66011cb2018-03-06 16:12:04 -07005645// Create subgroup invocation operations.
5646spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
5647{
5648 // Add the required capabilities.
5649 switch (op) {
5650 case glslang::EOpSubgroupElect:
5651 builder.addCapability(spv::CapabilityGroupNonUniform);
5652 break;
5653 case glslang::EOpSubgroupAll:
5654 case glslang::EOpSubgroupAny:
5655 case glslang::EOpSubgroupAllEqual:
5656 builder.addCapability(spv::CapabilityGroupNonUniform);
5657 builder.addCapability(spv::CapabilityGroupNonUniformVote);
5658 break;
5659 case glslang::EOpSubgroupBroadcast:
5660 case glslang::EOpSubgroupBroadcastFirst:
5661 case glslang::EOpSubgroupBallot:
5662 case glslang::EOpSubgroupInverseBallot:
5663 case glslang::EOpSubgroupBallotBitExtract:
5664 case glslang::EOpSubgroupBallotBitCount:
5665 case glslang::EOpSubgroupBallotInclusiveBitCount:
5666 case glslang::EOpSubgroupBallotExclusiveBitCount:
5667 case glslang::EOpSubgroupBallotFindLSB:
5668 case glslang::EOpSubgroupBallotFindMSB:
5669 builder.addCapability(spv::CapabilityGroupNonUniform);
5670 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
5671 break;
5672 case glslang::EOpSubgroupShuffle:
5673 case glslang::EOpSubgroupShuffleXor:
5674 builder.addCapability(spv::CapabilityGroupNonUniform);
5675 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
5676 break;
5677 case glslang::EOpSubgroupShuffleUp:
5678 case glslang::EOpSubgroupShuffleDown:
5679 builder.addCapability(spv::CapabilityGroupNonUniform);
5680 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
5681 break;
5682 case glslang::EOpSubgroupAdd:
5683 case glslang::EOpSubgroupMul:
5684 case glslang::EOpSubgroupMin:
5685 case glslang::EOpSubgroupMax:
5686 case glslang::EOpSubgroupAnd:
5687 case glslang::EOpSubgroupOr:
5688 case glslang::EOpSubgroupXor:
5689 case glslang::EOpSubgroupInclusiveAdd:
5690 case glslang::EOpSubgroupInclusiveMul:
5691 case glslang::EOpSubgroupInclusiveMin:
5692 case glslang::EOpSubgroupInclusiveMax:
5693 case glslang::EOpSubgroupInclusiveAnd:
5694 case glslang::EOpSubgroupInclusiveOr:
5695 case glslang::EOpSubgroupInclusiveXor:
5696 case glslang::EOpSubgroupExclusiveAdd:
5697 case glslang::EOpSubgroupExclusiveMul:
5698 case glslang::EOpSubgroupExclusiveMin:
5699 case glslang::EOpSubgroupExclusiveMax:
5700 case glslang::EOpSubgroupExclusiveAnd:
5701 case glslang::EOpSubgroupExclusiveOr:
5702 case glslang::EOpSubgroupExclusiveXor:
5703 builder.addCapability(spv::CapabilityGroupNonUniform);
5704 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
5705 break;
5706 case glslang::EOpSubgroupClusteredAdd:
5707 case glslang::EOpSubgroupClusteredMul:
5708 case glslang::EOpSubgroupClusteredMin:
5709 case glslang::EOpSubgroupClusteredMax:
5710 case glslang::EOpSubgroupClusteredAnd:
5711 case glslang::EOpSubgroupClusteredOr:
5712 case glslang::EOpSubgroupClusteredXor:
5713 builder.addCapability(spv::CapabilityGroupNonUniform);
5714 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
5715 break;
5716 case glslang::EOpSubgroupQuadBroadcast:
5717 case glslang::EOpSubgroupQuadSwapHorizontal:
5718 case glslang::EOpSubgroupQuadSwapVertical:
5719 case glslang::EOpSubgroupQuadSwapDiagonal:
5720 builder.addCapability(spv::CapabilityGroupNonUniform);
5721 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
5722 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005723#ifdef NV_EXTENSIONS
5724 case glslang::EOpSubgroupPartitionedAdd:
5725 case glslang::EOpSubgroupPartitionedMul:
5726 case glslang::EOpSubgroupPartitionedMin:
5727 case glslang::EOpSubgroupPartitionedMax:
5728 case glslang::EOpSubgroupPartitionedAnd:
5729 case glslang::EOpSubgroupPartitionedOr:
5730 case glslang::EOpSubgroupPartitionedXor:
5731 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5732 case glslang::EOpSubgroupPartitionedInclusiveMul:
5733 case glslang::EOpSubgroupPartitionedInclusiveMin:
5734 case glslang::EOpSubgroupPartitionedInclusiveMax:
5735 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5736 case glslang::EOpSubgroupPartitionedInclusiveOr:
5737 case glslang::EOpSubgroupPartitionedInclusiveXor:
5738 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5739 case glslang::EOpSubgroupPartitionedExclusiveMul:
5740 case glslang::EOpSubgroupPartitionedExclusiveMin:
5741 case glslang::EOpSubgroupPartitionedExclusiveMax:
5742 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5743 case glslang::EOpSubgroupPartitionedExclusiveOr:
5744 case glslang::EOpSubgroupPartitionedExclusiveXor:
5745 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
5746 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
5747 break;
5748#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005749 default: assert(0 && "Unhandled subgroup operation!");
5750 }
5751
5752 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
5753 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
5754 const bool isBool = typeProxy == glslang::EbtBool;
5755
5756 spv::Op opCode = spv::OpNop;
5757
5758 // Figure out which opcode to use.
5759 switch (op) {
5760 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
5761 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
5762 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
5763 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
5764 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
5765 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
5766 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
5767 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
5768 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
5769 case glslang::EOpSubgroupBallotBitCount:
5770 case glslang::EOpSubgroupBallotInclusiveBitCount:
5771 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
5772 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
5773 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
5774 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
5775 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
5776 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
5777 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
5778 case glslang::EOpSubgroupAdd:
5779 case glslang::EOpSubgroupInclusiveAdd:
5780 case glslang::EOpSubgroupExclusiveAdd:
5781 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005782#ifdef NV_EXTENSIONS
5783 case glslang::EOpSubgroupPartitionedAdd:
5784 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5785 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5786#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005787 if (isFloat) {
5788 opCode = spv::OpGroupNonUniformFAdd;
5789 } else {
5790 opCode = spv::OpGroupNonUniformIAdd;
5791 }
5792 break;
5793 case glslang::EOpSubgroupMul:
5794 case glslang::EOpSubgroupInclusiveMul:
5795 case glslang::EOpSubgroupExclusiveMul:
5796 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005797#ifdef NV_EXTENSIONS
5798 case glslang::EOpSubgroupPartitionedMul:
5799 case glslang::EOpSubgroupPartitionedInclusiveMul:
5800 case glslang::EOpSubgroupPartitionedExclusiveMul:
5801#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005802 if (isFloat) {
5803 opCode = spv::OpGroupNonUniformFMul;
5804 } else {
5805 opCode = spv::OpGroupNonUniformIMul;
5806 }
5807 break;
5808 case glslang::EOpSubgroupMin:
5809 case glslang::EOpSubgroupInclusiveMin:
5810 case glslang::EOpSubgroupExclusiveMin:
5811 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005812#ifdef NV_EXTENSIONS
5813 case glslang::EOpSubgroupPartitionedMin:
5814 case glslang::EOpSubgroupPartitionedInclusiveMin:
5815 case glslang::EOpSubgroupPartitionedExclusiveMin:
5816#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005817 if (isFloat) {
5818 opCode = spv::OpGroupNonUniformFMin;
5819 } else if (isUnsigned) {
5820 opCode = spv::OpGroupNonUniformUMin;
5821 } else {
5822 opCode = spv::OpGroupNonUniformSMin;
5823 }
5824 break;
5825 case glslang::EOpSubgroupMax:
5826 case glslang::EOpSubgroupInclusiveMax:
5827 case glslang::EOpSubgroupExclusiveMax:
5828 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005829#ifdef NV_EXTENSIONS
5830 case glslang::EOpSubgroupPartitionedMax:
5831 case glslang::EOpSubgroupPartitionedInclusiveMax:
5832 case glslang::EOpSubgroupPartitionedExclusiveMax:
5833#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005834 if (isFloat) {
5835 opCode = spv::OpGroupNonUniformFMax;
5836 } else if (isUnsigned) {
5837 opCode = spv::OpGroupNonUniformUMax;
5838 } else {
5839 opCode = spv::OpGroupNonUniformSMax;
5840 }
5841 break;
5842 case glslang::EOpSubgroupAnd:
5843 case glslang::EOpSubgroupInclusiveAnd:
5844 case glslang::EOpSubgroupExclusiveAnd:
5845 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005846#ifdef NV_EXTENSIONS
5847 case glslang::EOpSubgroupPartitionedAnd:
5848 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5849 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5850#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005851 if (isBool) {
5852 opCode = spv::OpGroupNonUniformLogicalAnd;
5853 } else {
5854 opCode = spv::OpGroupNonUniformBitwiseAnd;
5855 }
5856 break;
5857 case glslang::EOpSubgroupOr:
5858 case glslang::EOpSubgroupInclusiveOr:
5859 case glslang::EOpSubgroupExclusiveOr:
5860 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005861#ifdef NV_EXTENSIONS
5862 case glslang::EOpSubgroupPartitionedOr:
5863 case glslang::EOpSubgroupPartitionedInclusiveOr:
5864 case glslang::EOpSubgroupPartitionedExclusiveOr:
5865#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005866 if (isBool) {
5867 opCode = spv::OpGroupNonUniformLogicalOr;
5868 } else {
5869 opCode = spv::OpGroupNonUniformBitwiseOr;
5870 }
5871 break;
5872 case glslang::EOpSubgroupXor:
5873 case glslang::EOpSubgroupInclusiveXor:
5874 case glslang::EOpSubgroupExclusiveXor:
5875 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005876#ifdef NV_EXTENSIONS
5877 case glslang::EOpSubgroupPartitionedXor:
5878 case glslang::EOpSubgroupPartitionedInclusiveXor:
5879 case glslang::EOpSubgroupPartitionedExclusiveXor:
5880#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005881 if (isBool) {
5882 opCode = spv::OpGroupNonUniformLogicalXor;
5883 } else {
5884 opCode = spv::OpGroupNonUniformBitwiseXor;
5885 }
5886 break;
5887 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
5888 case glslang::EOpSubgroupQuadSwapHorizontal:
5889 case glslang::EOpSubgroupQuadSwapVertical:
5890 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
5891 default: assert(0 && "Unhandled subgroup operation!");
5892 }
5893
5894 std::vector<spv::Id> spvGroupOperands;
5895
5896 // Every operation begins with the Execution Scope operand.
5897 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
5898
5899 // Next, for all operations that use a Group Operation, push that as an operand.
5900 switch (op) {
5901 default: break;
5902 case glslang::EOpSubgroupBallotBitCount:
5903 case glslang::EOpSubgroupAdd:
5904 case glslang::EOpSubgroupMul:
5905 case glslang::EOpSubgroupMin:
5906 case glslang::EOpSubgroupMax:
5907 case glslang::EOpSubgroupAnd:
5908 case glslang::EOpSubgroupOr:
5909 case glslang::EOpSubgroupXor:
5910 spvGroupOperands.push_back(spv::GroupOperationReduce);
5911 break;
5912 case glslang::EOpSubgroupBallotInclusiveBitCount:
5913 case glslang::EOpSubgroupInclusiveAdd:
5914 case glslang::EOpSubgroupInclusiveMul:
5915 case glslang::EOpSubgroupInclusiveMin:
5916 case glslang::EOpSubgroupInclusiveMax:
5917 case glslang::EOpSubgroupInclusiveAnd:
5918 case glslang::EOpSubgroupInclusiveOr:
5919 case glslang::EOpSubgroupInclusiveXor:
5920 spvGroupOperands.push_back(spv::GroupOperationInclusiveScan);
5921 break;
5922 case glslang::EOpSubgroupBallotExclusiveBitCount:
5923 case glslang::EOpSubgroupExclusiveAdd:
5924 case glslang::EOpSubgroupExclusiveMul:
5925 case glslang::EOpSubgroupExclusiveMin:
5926 case glslang::EOpSubgroupExclusiveMax:
5927 case glslang::EOpSubgroupExclusiveAnd:
5928 case glslang::EOpSubgroupExclusiveOr:
5929 case glslang::EOpSubgroupExclusiveXor:
5930 spvGroupOperands.push_back(spv::GroupOperationExclusiveScan);
5931 break;
5932 case glslang::EOpSubgroupClusteredAdd:
5933 case glslang::EOpSubgroupClusteredMul:
5934 case glslang::EOpSubgroupClusteredMin:
5935 case glslang::EOpSubgroupClusteredMax:
5936 case glslang::EOpSubgroupClusteredAnd:
5937 case glslang::EOpSubgroupClusteredOr:
5938 case glslang::EOpSubgroupClusteredXor:
5939 spvGroupOperands.push_back(spv::GroupOperationClusteredReduce);
5940 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005941#ifdef NV_EXTENSIONS
5942 case glslang::EOpSubgroupPartitionedAdd:
5943 case glslang::EOpSubgroupPartitionedMul:
5944 case glslang::EOpSubgroupPartitionedMin:
5945 case glslang::EOpSubgroupPartitionedMax:
5946 case glslang::EOpSubgroupPartitionedAnd:
5947 case glslang::EOpSubgroupPartitionedOr:
5948 case glslang::EOpSubgroupPartitionedXor:
5949 spvGroupOperands.push_back(spv::GroupOperationPartitionedReduceNV);
5950 break;
5951 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5952 case glslang::EOpSubgroupPartitionedInclusiveMul:
5953 case glslang::EOpSubgroupPartitionedInclusiveMin:
5954 case glslang::EOpSubgroupPartitionedInclusiveMax:
5955 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5956 case glslang::EOpSubgroupPartitionedInclusiveOr:
5957 case glslang::EOpSubgroupPartitionedInclusiveXor:
5958 spvGroupOperands.push_back(spv::GroupOperationPartitionedInclusiveScanNV);
5959 break;
5960 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5961 case glslang::EOpSubgroupPartitionedExclusiveMul:
5962 case glslang::EOpSubgroupPartitionedExclusiveMin:
5963 case glslang::EOpSubgroupPartitionedExclusiveMax:
5964 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5965 case glslang::EOpSubgroupPartitionedExclusiveOr:
5966 case glslang::EOpSubgroupPartitionedExclusiveXor:
5967 spvGroupOperands.push_back(spv::GroupOperationPartitionedExclusiveScanNV);
5968 break;
5969#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005970 }
5971
5972 // Push back the operands next.
5973 for (auto opIt : operands) {
5974 spvGroupOperands.push_back(opIt);
5975 }
5976
5977 // Some opcodes have additional operands.
5978 switch (op) {
5979 default: break;
5980 case glslang::EOpSubgroupQuadSwapHorizontal: spvGroupOperands.push_back(builder.makeUintConstant(0)); break;
5981 case glslang::EOpSubgroupQuadSwapVertical: spvGroupOperands.push_back(builder.makeUintConstant(1)); break;
5982 case glslang::EOpSubgroupQuadSwapDiagonal: spvGroupOperands.push_back(builder.makeUintConstant(2)); break;
5983 }
5984
5985 return builder.createOp(opCode, typeId, spvGroupOperands);
5986}
5987
John Kessenich5e4b1242015-08-06 22:53:06 -06005988spv::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 -06005989{
John Kessenich66011cb2018-03-06 16:12:04 -07005990 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5991 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06005992
John Kessenich140f3df2015-06-26 16:58:36 -06005993 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005994 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005995 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005996 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005997 spv::Id typeId0 = 0;
5998 if (consumedOperands > 0)
5999 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006000 spv::Id typeId1 = 0;
6001 if (consumedOperands > 1)
6002 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006003 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006004
6005 switch (op) {
6006 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006007 if (isFloat)
6008 libCall = spv::GLSLstd450FMin;
6009 else if (isUnsigned)
6010 libCall = spv::GLSLstd450UMin;
6011 else
6012 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006013 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006014 break;
6015 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006016 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006017 break;
6018 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006019 if (isFloat)
6020 libCall = spv::GLSLstd450FMax;
6021 else if (isUnsigned)
6022 libCall = spv::GLSLstd450UMax;
6023 else
6024 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006025 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006026 break;
6027 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006028 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006029 break;
6030 case glslang::EOpDot:
6031 opCode = spv::OpDot;
6032 break;
6033 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006034 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006035 break;
6036
6037 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006038 if (isFloat)
6039 libCall = spv::GLSLstd450FClamp;
6040 else if (isUnsigned)
6041 libCall = spv::GLSLstd450UClamp;
6042 else
6043 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006044 builder.promoteScalar(precision, operands.front(), operands[1]);
6045 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006046 break;
6047 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006048 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6049 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006050 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006051 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006052 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006053 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006054 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006055 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006056 break;
6057 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006058 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006059 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006060 break;
6061 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006062 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006063 builder.promoteScalar(precision, operands[0], operands[2]);
6064 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006065 break;
6066
6067 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006068 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006069 break;
6070 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006071 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006072 break;
6073 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006074 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006075 break;
6076 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006077 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006078 break;
6079 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006080 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006081 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006082 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07006083 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08006084 libCall = spv::GLSLstd450InterpolateAtSample;
6085 break;
6086 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07006087 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08006088 libCall = spv::GLSLstd450InterpolateAtOffset;
6089 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006090 case glslang::EOpAddCarry:
6091 opCode = spv::OpIAddCarry;
6092 typeId = builder.makeStructResultType(typeId0, typeId0);
6093 consumedOperands = 2;
6094 break;
6095 case glslang::EOpSubBorrow:
6096 opCode = spv::OpISubBorrow;
6097 typeId = builder.makeStructResultType(typeId0, typeId0);
6098 consumedOperands = 2;
6099 break;
6100 case glslang::EOpUMulExtended:
6101 opCode = spv::OpUMulExtended;
6102 typeId = builder.makeStructResultType(typeId0, typeId0);
6103 consumedOperands = 2;
6104 break;
6105 case glslang::EOpIMulExtended:
6106 opCode = spv::OpSMulExtended;
6107 typeId = builder.makeStructResultType(typeId0, typeId0);
6108 consumedOperands = 2;
6109 break;
6110 case glslang::EOpBitfieldExtract:
6111 if (isUnsigned)
6112 opCode = spv::OpBitFieldUExtract;
6113 else
6114 opCode = spv::OpBitFieldSExtract;
6115 break;
6116 case glslang::EOpBitfieldInsert:
6117 opCode = spv::OpBitFieldInsert;
6118 break;
6119
6120 case glslang::EOpFma:
6121 libCall = spv::GLSLstd450Fma;
6122 break;
6123 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006124 {
6125 libCall = spv::GLSLstd450FrexpStruct;
6126 assert(builder.isPointerType(typeId1));
6127 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006128 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006129 if (builder.getNumComponents(operands[0]) == 1)
6130 frexpIntType = builder.makeIntegerType(width, true);
6131 else
6132 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6133 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6134 consumedOperands = 1;
6135 }
John Kessenich55e7d112015-11-15 21:33:39 -07006136 break;
6137 case glslang::EOpLdexp:
6138 libCall = spv::GLSLstd450Ldexp;
6139 break;
6140
Rex Xu574ab042016-04-14 16:53:07 +08006141 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08006142 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08006143
John Kessenich66011cb2018-03-06 16:12:04 -07006144 case glslang::EOpSubgroupBroadcast:
6145 case glslang::EOpSubgroupBallotBitExtract:
6146 case glslang::EOpSubgroupShuffle:
6147 case glslang::EOpSubgroupShuffleXor:
6148 case glslang::EOpSubgroupShuffleUp:
6149 case glslang::EOpSubgroupShuffleDown:
6150 case glslang::EOpSubgroupClusteredAdd:
6151 case glslang::EOpSubgroupClusteredMul:
6152 case glslang::EOpSubgroupClusteredMin:
6153 case glslang::EOpSubgroupClusteredMax:
6154 case glslang::EOpSubgroupClusteredAnd:
6155 case glslang::EOpSubgroupClusteredOr:
6156 case glslang::EOpSubgroupClusteredXor:
6157 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006158#ifdef NV_EXTENSIONS
6159 case glslang::EOpSubgroupPartitionedAdd:
6160 case glslang::EOpSubgroupPartitionedMul:
6161 case glslang::EOpSubgroupPartitionedMin:
6162 case glslang::EOpSubgroupPartitionedMax:
6163 case glslang::EOpSubgroupPartitionedAnd:
6164 case glslang::EOpSubgroupPartitionedOr:
6165 case glslang::EOpSubgroupPartitionedXor:
6166 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6167 case glslang::EOpSubgroupPartitionedInclusiveMul:
6168 case glslang::EOpSubgroupPartitionedInclusiveMin:
6169 case glslang::EOpSubgroupPartitionedInclusiveMax:
6170 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6171 case glslang::EOpSubgroupPartitionedInclusiveOr:
6172 case glslang::EOpSubgroupPartitionedInclusiveXor:
6173 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6174 case glslang::EOpSubgroupPartitionedExclusiveMul:
6175 case glslang::EOpSubgroupPartitionedExclusiveMin:
6176 case glslang::EOpSubgroupPartitionedExclusiveMax:
6177 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6178 case glslang::EOpSubgroupPartitionedExclusiveOr:
6179 case glslang::EOpSubgroupPartitionedExclusiveXor:
6180#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006181 return createSubgroupOperation(op, typeId, operands, typeProxy);
6182
Rex Xu9d93a232016-05-05 12:30:44 +08006183#ifdef AMD_EXTENSIONS
6184 case glslang::EOpSwizzleInvocations:
6185 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6186 libCall = spv::SwizzleInvocationsAMD;
6187 break;
6188 case glslang::EOpSwizzleInvocationsMasked:
6189 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6190 libCall = spv::SwizzleInvocationsMaskedAMD;
6191 break;
6192 case glslang::EOpWriteInvocation:
6193 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6194 libCall = spv::WriteInvocationAMD;
6195 break;
6196
6197 case glslang::EOpMin3:
6198 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6199 if (isFloat)
6200 libCall = spv::FMin3AMD;
6201 else {
6202 if (isUnsigned)
6203 libCall = spv::UMin3AMD;
6204 else
6205 libCall = spv::SMin3AMD;
6206 }
6207 break;
6208 case glslang::EOpMax3:
6209 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6210 if (isFloat)
6211 libCall = spv::FMax3AMD;
6212 else {
6213 if (isUnsigned)
6214 libCall = spv::UMax3AMD;
6215 else
6216 libCall = spv::SMax3AMD;
6217 }
6218 break;
6219 case glslang::EOpMid3:
6220 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6221 if (isFloat)
6222 libCall = spv::FMid3AMD;
6223 else {
6224 if (isUnsigned)
6225 libCall = spv::UMid3AMD;
6226 else
6227 libCall = spv::SMid3AMD;
6228 }
6229 break;
6230
6231 case glslang::EOpInterpolateAtVertex:
6232 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
6233 libCall = spv::InterpolateAtVertexAMD;
6234 break;
6235#endif
6236
John Kessenich140f3df2015-06-26 16:58:36 -06006237 default:
6238 return 0;
6239 }
6240
6241 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07006242 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05006243 // Use an extended instruction from the standard library.
6244 // Construct the call arguments, without modifying the original operands vector.
6245 // We might need the remaining arguments, e.g. in the EOpFrexp case.
6246 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08006247 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07006248 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07006249 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06006250 case 0:
6251 // should all be handled by visitAggregate and createNoArgOperation
6252 assert(0);
6253 return 0;
6254 case 1:
6255 // should all be handled by createUnaryOperation
6256 assert(0);
6257 return 0;
6258 case 2:
6259 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
6260 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006261 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006262 // anything 3 or over doesn't have l-value operands, so all should be consumed
6263 assert(consumedOperands == operands.size());
6264 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06006265 break;
6266 }
6267 }
6268
John Kessenich55e7d112015-11-15 21:33:39 -07006269 // Decode the return types that were structures
6270 switch (op) {
6271 case glslang::EOpAddCarry:
6272 case glslang::EOpSubBorrow:
6273 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6274 id = builder.createCompositeExtract(id, typeId0, 0);
6275 break;
6276 case glslang::EOpUMulExtended:
6277 case glslang::EOpIMulExtended:
6278 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
6279 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6280 break;
6281 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006282 {
6283 assert(operands.size() == 2);
6284 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
6285 // "exp" is floating-point type (from HLSL intrinsic)
6286 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
6287 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
6288 builder.createStore(member1, operands[1]);
6289 } else
6290 // "exp" is integer type (from GLSL built-in function)
6291 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
6292 id = builder.createCompositeExtract(id, typeId0, 0);
6293 }
John Kessenich55e7d112015-11-15 21:33:39 -07006294 break;
6295 default:
6296 break;
6297 }
6298
John Kessenich32cfd492016-02-02 12:37:46 -07006299 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006300}
6301
Rex Xu9d93a232016-05-05 12:30:44 +08006302// Intrinsics with no arguments (or no return value, and no precision).
6303spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06006304{
6305 // TODO: get the barrier operands correct
6306
6307 switch (op) {
6308 case glslang::EOpEmitVertex:
6309 builder.createNoResultOp(spv::OpEmitVertex);
6310 return 0;
6311 case glslang::EOpEndPrimitive:
6312 builder.createNoResultOp(spv::OpEndPrimitive);
6313 return 0;
6314 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006315 if (glslangIntermediate->getStage() == EShLangTessControl) {
6316 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
6317 // TODO: prefer the following, when available:
6318 // builder.createControlBarrier(spv::ScopePatch, spv::ScopePatch,
6319 // spv::MemorySemanticsPatchMask |
6320 // spv::MemorySemanticsAcquireReleaseMask);
6321 } else {
6322 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6323 spv::MemorySemanticsWorkgroupMemoryMask |
6324 spv::MemorySemanticsAcquireReleaseMask);
6325 }
John Kessenich140f3df2015-06-26 16:58:36 -06006326 return 0;
6327 case glslang::EOpMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006328 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory |
6329 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006330 return 0;
6331 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich82979362017-12-11 04:02:24 -07006332 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask |
6333 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006334 return 0;
6335 case glslang::EOpMemoryBarrierBuffer:
John Kessenich82979362017-12-11 04:02:24 -07006336 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6337 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006338 return 0;
6339 case glslang::EOpMemoryBarrierImage:
John Kessenich82979362017-12-11 04:02:24 -07006340 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask |
6341 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006342 return 0;
6343 case glslang::EOpMemoryBarrierShared:
John Kessenich82979362017-12-11 04:02:24 -07006344 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask |
6345 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006346 return 0;
6347 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006348 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
6349 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006350 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06006351 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006352 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07006353 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07006354 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006355 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07006356 case glslang::EOpDeviceMemoryBarrier:
6357 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6358 spv::MemorySemanticsImageMemoryMask |
6359 spv::MemorySemanticsAcquireReleaseMask);
6360 return 0;
6361 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
6362 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6363 spv::MemorySemanticsImageMemoryMask |
6364 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006365 return 0;
6366 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07006367 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6368 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006369 return 0;
6370 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006371 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6372 spv::MemorySemanticsWorkgroupMemoryMask |
6373 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006374 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07006375 case glslang::EOpSubgroupBarrier:
6376 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6377 spv::MemorySemanticsAcquireReleaseMask);
6378 return spv::NoResult;
6379 case glslang::EOpSubgroupMemoryBarrier:
6380 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6381 spv::MemorySemanticsAcquireReleaseMask);
6382 return spv::NoResult;
6383 case glslang::EOpSubgroupMemoryBarrierBuffer:
6384 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
6385 spv::MemorySemanticsAcquireReleaseMask);
6386 return spv::NoResult;
6387 case glslang::EOpSubgroupMemoryBarrierImage:
6388 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
6389 spv::MemorySemanticsAcquireReleaseMask);
6390 return spv::NoResult;
6391 case glslang::EOpSubgroupMemoryBarrierShared:
6392 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6393 spv::MemorySemanticsAcquireReleaseMask);
6394 return spv::NoResult;
6395 case glslang::EOpSubgroupElect: {
6396 std::vector<spv::Id> operands;
6397 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
6398 }
Rex Xu9d93a232016-05-05 12:30:44 +08006399#ifdef AMD_EXTENSIONS
6400 case glslang::EOpTime:
6401 {
6402 std::vector<spv::Id> args; // Dummy arguments
6403 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
6404 return builder.setPrecision(id, precision);
6405 }
6406#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006407 default:
Lei Zhang17535f72016-05-04 15:55:59 -04006408 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06006409 return 0;
6410 }
6411}
6412
6413spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
6414{
John Kessenich2f273362015-07-18 22:34:27 -06006415 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06006416 spv::Id id;
6417 if (symbolValues.end() != iter) {
6418 id = iter->second;
6419 return id;
6420 }
6421
6422 // it was not found, create it
6423 id = createSpvVariable(symbol);
6424 symbolValues[symbol->getId()] = id;
6425
Rex Xuc884b4a2016-06-29 15:03:44 +08006426 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006427 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
6428 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
6429 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07006430 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07006431 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06006432 if (symbol->getQualifier().hasIndex())
6433 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
6434 if (symbol->getQualifier().hasComponent())
6435 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06006436 // atomic counters use this:
6437 if (symbol->getQualifier().hasOffset())
6438 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006439 }
6440
scygan2c864272016-05-18 18:09:17 +02006441 if (symbol->getQualifier().hasLocation())
6442 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07006443 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07006444 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07006445 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06006446 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07006447 }
John Kessenich140f3df2015-06-26 16:58:36 -06006448 if (symbol->getQualifier().hasSet())
6449 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07006450 else if (IsDescriptorResource(symbol->getType())) {
6451 // default to 0
6452 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
6453 }
John Kessenich140f3df2015-06-26 16:58:36 -06006454 if (symbol->getQualifier().hasBinding())
6455 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07006456 if (symbol->getQualifier().hasAttachment())
6457 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06006458 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07006459 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06006460 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06006461 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07006462 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06006463 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07006464 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
6465 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
6466 builder.addDecoration(id, spv::DecorationXfbStride, stride);
6467 }
6468 if (symbol->getQualifier().hasXfbOffset())
6469 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006470 }
6471
Rex Xu1da878f2016-02-21 20:59:01 +08006472 if (symbol->getType().isImage()) {
6473 std::vector<spv::Decoration> memory;
6474 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
6475 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07006476 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08006477 }
6478
John Kessenich140f3df2015-06-26 16:58:36 -06006479 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06006480 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06006481 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07006482 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06006483
John Kessenich5611c6d2018-04-05 11:25:02 -06006484 // nonuniform
6485 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
6486
John Kessenichecba76f2017-01-06 00:34:48 -07006487#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08006488 if (builtIn == spv::BuiltInSampleMask) {
6489 spv::Decoration decoration;
6490 // GL_NV_sample_mask_override_coverage extension
6491 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08006492 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08006493 else
6494 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07006495 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08006496 if (decoration != spv::DecorationMax) {
6497 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
6498 }
6499 }
chaoc771d89f2017-01-13 01:10:53 -08006500 else if (builtIn == spv::BuiltInLayer) {
6501 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06006502 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006503 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08006504 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
6505 builder.addExtension(spv::E_SPV_NV_viewport_array2);
6506 }
John Kessenichb41bff62017-08-11 13:07:17 -06006507 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006508 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
6509 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08006510 builder.addCapability(spv::CapabilityShaderStereoViewNV);
6511 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
6512 }
6513 }
6514
chaoc6e5acae2016-12-20 13:28:52 -08006515 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006516 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08006517 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08006518 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
6519 }
chaoc0ad6a4e2016-12-19 16:29:34 -08006520#endif
6521
John Kessenich5d610ee2018-03-07 18:05:55 -07006522 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
6523 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
6524 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
6525 symbol->getType().getQualifier().semanticName);
6526 }
6527
John Kessenich140f3df2015-06-26 16:58:36 -06006528 return id;
6529}
6530
John Kessenich55e7d112015-11-15 21:33:39 -07006531// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07006532// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07006533//
6534// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
6535//
6536// Recursively walk the nodes. The nodes form a tree whose leaves are
6537// regular constants, which themselves are trees that createSpvConstant()
6538// recursively walks. So, this function walks the "top" of the tree:
6539// - emit specialization constant-building instructions for specConstant
6540// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04006541spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07006542{
John Kessenich7cc0e282016-03-20 00:46:02 -06006543 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07006544
qining4f4bb812016-04-03 23:55:17 -04006545 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07006546 if (! node.getQualifier().specConstant) {
6547 // hand off to the non-spec-constant path
6548 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
6549 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04006550 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07006551 nextConst, false);
6552 }
6553
6554 // We now know we have a specialization constant to build
6555
John Kessenichd94c0032016-05-30 19:29:40 -06006556 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04006557 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
6558 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
6559 std::vector<spv::Id> dimConstId;
6560 for (int dim = 0; dim < 3; ++dim) {
6561 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
6562 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07006563 if (specConst) {
6564 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
6565 glslangIntermediate->getLocalSizeSpecId(dim));
6566 }
qining4f4bb812016-04-03 23:55:17 -04006567 }
6568 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
6569 }
6570
6571 // An AST node labelled as specialization constant should be a symbol node.
6572 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
6573 if (auto* sn = node.getAsSymbolNode()) {
6574 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04006575 // Traverse the constant constructor sub tree like generating normal run-time instructions.
6576 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
6577 // will set the builder into spec constant op instruction generating mode.
6578 sub_tree->traverse(this);
6579 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04006580 } else if (auto* const_union_array = &sn->getConstArray()){
6581 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01006582 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
6583 builder.addName(id, sn->getName().c_str());
6584 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07006585 }
6586 }
qining4f4bb812016-04-03 23:55:17 -04006587
6588 // Neither a front-end constant node, nor a specialization constant node with constant union array or
6589 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04006590 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04006591 exit(1);
6592 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07006593}
6594
John Kessenich140f3df2015-06-26 16:58:36 -06006595// Use 'consts' as the flattened glslang source of scalar constants to recursively
6596// build the aggregate SPIR-V constant.
6597//
6598// If there are not enough elements present in 'consts', 0 will be substituted;
6599// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
6600//
qining08408382016-03-21 09:51:37 -04006601spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06006602{
6603 // vector of constants for SPIR-V
6604 std::vector<spv::Id> spvConsts;
6605
6606 // Type is used for struct and array constants
6607 spv::Id typeId = convertGlslangToSpvType(glslangType);
6608
6609 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006610 glslang::TType elementType(glslangType, 0);
6611 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04006612 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006613 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006614 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06006615 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04006616 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006617 } else if (glslangType.getStruct()) {
6618 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
6619 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04006620 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06006621 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06006622 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
6623 bool zero = nextConst >= consts.size();
6624 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006625 case glslang::EbtInt8:
6626 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
6627 break;
6628 case glslang::EbtUint8:
6629 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
6630 break;
6631 case glslang::EbtInt16:
6632 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
6633 break;
6634 case glslang::EbtUint16:
6635 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
6636 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006637 case glslang::EbtInt:
6638 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
6639 break;
6640 case glslang::EbtUint:
6641 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
6642 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006643 case glslang::EbtInt64:
6644 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
6645 break;
6646 case glslang::EbtUint64:
6647 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
6648 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006649 case glslang::EbtFloat:
6650 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
6651 break;
6652 case glslang::EbtDouble:
6653 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
6654 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006655 case glslang::EbtFloat16:
6656 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
6657 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006658 case glslang::EbtBool:
6659 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
6660 break;
6661 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006662 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06006663 break;
6664 }
6665 ++nextConst;
6666 }
6667 } else {
6668 // we have a non-aggregate (scalar) constant
6669 bool zero = nextConst >= consts.size();
6670 spv::Id scalar = 0;
6671 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006672 case glslang::EbtInt8:
6673 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
6674 break;
6675 case glslang::EbtUint8:
6676 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
6677 break;
6678 case glslang::EbtInt16:
6679 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
6680 break;
6681 case glslang::EbtUint16:
6682 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
6683 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006684 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07006685 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006686 break;
6687 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07006688 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006689 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006690 case glslang::EbtInt64:
6691 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
6692 break;
6693 case glslang::EbtUint64:
6694 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
6695 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006696 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07006697 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006698 break;
6699 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07006700 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006701 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006702 case glslang::EbtFloat16:
6703 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
6704 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006705 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07006706 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006707 break;
6708 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006709 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06006710 break;
6711 }
6712 ++nextConst;
6713 return scalar;
6714 }
6715
6716 return builder.makeCompositeConstant(typeId, spvConsts);
6717}
6718
John Kessenich7c1aa102015-10-15 13:29:11 -06006719// Return true if the node is a constant or symbol whose reading has no
6720// non-trivial observable cost or effect.
6721bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
6722{
6723 // don't know what this is
6724 if (node == nullptr)
6725 return false;
6726
6727 // a constant is safe
6728 if (node->getAsConstantUnion() != nullptr)
6729 return true;
6730
6731 // not a symbol means non-trivial
6732 if (node->getAsSymbolNode() == nullptr)
6733 return false;
6734
6735 // a symbol, depends on what's being read
6736 switch (node->getType().getQualifier().storage) {
6737 case glslang::EvqTemporary:
6738 case glslang::EvqGlobal:
6739 case glslang::EvqIn:
6740 case glslang::EvqInOut:
6741 case glslang::EvqConst:
6742 case glslang::EvqConstReadOnly:
6743 case glslang::EvqUniform:
6744 return true;
6745 default:
6746 return false;
6747 }
qining25262b32016-05-06 17:25:16 -04006748}
John Kessenich7c1aa102015-10-15 13:29:11 -06006749
6750// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06006751// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06006752// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06006753// Return true if trivial.
6754bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
6755{
6756 if (node == nullptr)
6757 return false;
6758
John Kessenich84cc15f2017-05-24 16:44:47 -06006759 // count non scalars as trivial, as well as anything coming from HLSL
6760 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06006761 return true;
6762
John Kessenich7c1aa102015-10-15 13:29:11 -06006763 // symbols and constants are trivial
6764 if (isTrivialLeaf(node))
6765 return true;
6766
6767 // otherwise, it needs to be a simple operation or one or two leaf nodes
6768
6769 // not a simple operation
6770 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
6771 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
6772 if (binaryNode == nullptr && unaryNode == nullptr)
6773 return false;
6774
6775 // not on leaf nodes
6776 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
6777 return false;
6778
6779 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
6780 return false;
6781 }
6782
6783 switch (node->getAsOperator()->getOp()) {
6784 case glslang::EOpLogicalNot:
6785 case glslang::EOpConvIntToBool:
6786 case glslang::EOpConvUintToBool:
6787 case glslang::EOpConvFloatToBool:
6788 case glslang::EOpConvDoubleToBool:
6789 case glslang::EOpEqual:
6790 case glslang::EOpNotEqual:
6791 case glslang::EOpLessThan:
6792 case glslang::EOpGreaterThan:
6793 case glslang::EOpLessThanEqual:
6794 case glslang::EOpGreaterThanEqual:
6795 case glslang::EOpIndexDirect:
6796 case glslang::EOpIndexDirectStruct:
6797 case glslang::EOpLogicalXor:
6798 case glslang::EOpAny:
6799 case glslang::EOpAll:
6800 return true;
6801 default:
6802 return false;
6803 }
6804}
6805
6806// Emit short-circuiting code, where 'right' is never evaluated unless
6807// the left side is true (for &&) or false (for ||).
6808spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
6809{
6810 spv::Id boolTypeId = builder.makeBoolType();
6811
6812 // emit left operand
6813 builder.clearAccessChain();
6814 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006815 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006816
6817 // Operands to accumulate OpPhi operands
6818 std::vector<spv::Id> phiOperands;
6819 // accumulate left operand's phi information
6820 phiOperands.push_back(leftId);
6821 phiOperands.push_back(builder.getBuildPoint()->getId());
6822
6823 // Make the two kinds of operation symmetric with a "!"
6824 // || => emit "if (! left) result = right"
6825 // && => emit "if ( left) result = right"
6826 //
6827 // TODO: this runtime "not" for || could be avoided by adding functionality
6828 // to 'builder' to have an "else" without an "then"
6829 if (op == glslang::EOpLogicalOr)
6830 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
6831
6832 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08006833 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06006834
6835 // emit right operand as the "then" part of the "if"
6836 builder.clearAccessChain();
6837 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006838 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006839
6840 // accumulate left operand's phi information
6841 phiOperands.push_back(rightId);
6842 phiOperands.push_back(builder.getBuildPoint()->getId());
6843
6844 // finish the "if"
6845 ifBuilder.makeEndIf();
6846
6847 // phi together the two results
6848 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
6849}
6850
Frank Henigman541f7bb2018-01-16 00:18:26 -05006851#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08006852// Return type Id of the imported set of extended instructions corresponds to the name.
6853// Import this set if it has not been imported yet.
6854spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
6855{
6856 if (extBuiltinMap.find(name) != extBuiltinMap.end())
6857 return extBuiltinMap[name];
6858 else {
Rex Xu51596642016-09-21 18:56:12 +08006859 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08006860 spv::Id extBuiltins = builder.import(name);
6861 extBuiltinMap[name] = extBuiltins;
6862 return extBuiltins;
6863 }
6864}
Frank Henigman541f7bb2018-01-16 00:18:26 -05006865#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006866
John Kessenich140f3df2015-06-26 16:58:36 -06006867}; // end anonymous namespace
6868
6869namespace glslang {
6870
John Kessenich68d78fd2015-07-12 19:28:10 -06006871void GetSpirvVersion(std::string& version)
6872{
John Kessenich9e55f632015-07-15 10:03:39 -06006873 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06006874 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07006875 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06006876 version = buf;
6877}
6878
John Kessenicha372a3e2017-11-02 22:32:14 -06006879// For low-order part of the generator's magic number. Bump up
6880// when there is a change in the style (e.g., if SSA form changes,
6881// or a different instruction sequence to do something gets used).
6882int GetSpirvGeneratorVersion()
6883{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07006884 // return 1; // start
6885 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07006886 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07006887 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07006888 // return 5; // make OpArrayLength result type be an int with signedness of 0
6889 return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
6890 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenicha372a3e2017-11-02 22:32:14 -06006891}
6892
John Kessenich140f3df2015-06-26 16:58:36 -06006893// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006894void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06006895{
6896 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06006897 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006898 if (out.fail())
6899 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06006900 for (int i = 0; i < (int)spirv.size(); ++i) {
6901 unsigned int word = spirv[i];
6902 out.write((const char*)&word, 4);
6903 }
6904 out.close();
6905}
6906
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006907// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08006908void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006909{
6910 std::ofstream out;
6911 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006912 if (out.fail())
6913 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07006914 out << "\t// " <<
6915 glslang::GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
6916 std::endl;
Flavio15017db2017-02-15 14:29:33 -08006917 if (varName != nullptr) {
6918 out << "\t #pragma once" << std::endl;
6919 out << "const uint32_t " << varName << "[] = {" << std::endl;
6920 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006921 const int WORDS_PER_LINE = 8;
6922 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
6923 out << "\t";
6924 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
6925 const unsigned int word = spirv[i + j];
6926 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
6927 if (i + j + 1 < (int)spirv.size()) {
6928 out << ",";
6929 }
6930 }
6931 out << std::endl;
6932 }
Flavio15017db2017-02-15 14:29:33 -08006933 if (varName != nullptr) {
6934 out << "};";
6935 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006936 out.close();
6937}
6938
John Kessenich140f3df2015-06-26 16:58:36 -06006939//
6940// Set up the glslang traversal
6941//
John Kessenich121853f2017-05-31 17:11:16 -06006942void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06006943{
Lei Zhang17535f72016-05-04 15:55:59 -04006944 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06006945 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04006946}
6947
John Kessenich121853f2017-05-31 17:11:16 -06006948void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
6949 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04006950{
John Kessenich140f3df2015-06-26 16:58:36 -06006951 TIntermNode* root = intermediate.getTreeRoot();
6952
6953 if (root == 0)
6954 return;
6955
John Kessenich121853f2017-05-31 17:11:16 -06006956 glslang::SpvOptions defaultOptions;
6957 if (options == nullptr)
6958 options = &defaultOptions;
6959
John Kessenich140f3df2015-06-26 16:58:36 -06006960 glslang::GetThreadPoolAllocator().push();
6961
John Kessenich2b5ea9f2018-01-31 18:35:56 -07006962 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06006963 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07006964 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06006965 it.dumpSpv(spirv);
6966
GregFfb03a552018-03-29 11:49:14 -06006967#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06006968 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
6969 // eg. forward and remove memory writes of opaque types.
6970 if ((intermediate.getSource() == EShSourceHlsl ||
6971 options->optimizeSize) &&
6972 !options->disableOptimizer) {
6973 spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
6974
6975 spvtools::Optimizer optimizer(target_env);
6976 optimizer.SetMessageConsumer([](spv_message_level_t level,
6977 const char* source,
6978 const spv_position_t& position,
6979 const char* message) {
6980 std::cerr << StringifyMessage(level, source, position, message)
6981 << std::endl;
6982 });
6983
GregFeecb8742018-03-26 12:11:55 -06006984 optimizer.RegisterPass(CreateMergeReturnPass());
GregFcd1f1692017-09-21 18:40:22 -06006985 optimizer.RegisterPass(CreateInlineExhaustivePass());
GregFe0639282017-12-21 10:55:57 -07006986 optimizer.RegisterPass(CreateEliminateDeadFunctionsPass());
6987 optimizer.RegisterPass(CreateScalarReplacementPass());
GregFcd1f1692017-09-21 18:40:22 -06006988 optimizer.RegisterPass(CreateLocalAccessChainConvertPass());
6989 optimizer.RegisterPass(CreateLocalSingleBlockLoadStoreElimPass());
6990 optimizer.RegisterPass(CreateLocalSingleStoreElimPass());
GregFeecb8742018-03-26 12:11:55 -06006991 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFcd1f1692017-09-21 18:40:22 -06006992 optimizer.RegisterPass(CreateInsertExtractElimPass());
GregF8a4848f2018-02-07 16:04:42 -07006993 optimizer.RegisterPass(CreateDeadInsertElimPass());
GregFcd1f1692017-09-21 18:40:22 -06006994 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFeecb8742018-03-26 12:11:55 -06006995 optimizer.RegisterPass(CreateCCPPass());
6996 optimizer.RegisterPass(CreateSimplificationPass());
GregFcd1f1692017-09-21 18:40:22 -06006997 optimizer.RegisterPass(CreateDeadBranchElimPass());
GregFcc80d802017-10-23 16:48:42 -06006998 optimizer.RegisterPass(CreateCFGCleanupPass());
GregFcd1f1692017-09-21 18:40:22 -06006999 optimizer.RegisterPass(CreateBlockMergePass());
7000 optimizer.RegisterPass(CreateLocalMultiStoreElimPass());
GregFeecb8742018-03-26 12:11:55 -06007001 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFcd1f1692017-09-21 18:40:22 -06007002 optimizer.RegisterPass(CreateInsertExtractElimPass());
GregF8a4848f2018-02-07 16:04:42 -07007003 optimizer.RegisterPass(CreateDeadInsertElimPass());
7004 if (options->optimizeSize) {
7005 optimizer.RegisterPass(CreateRedundancyEliminationPass());
7006 // TODO(greg-lunarg): Add this when AMD driver issues are resolved
7007 // optimizer.RegisterPass(CreateCommonUniformElimPass());
7008 }
GregFcd1f1692017-09-21 18:40:22 -06007009 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFcd1f1692017-09-21 18:40:22 -06007010
7011 if (!optimizer.Run(spirv.data(), spirv.size(), &spirv))
7012 return;
GregFcd1f1692017-09-21 18:40:22 -06007013 }
7014#endif
7015
John Kessenich140f3df2015-06-26 16:58:36 -06007016 glslang::GetThreadPoolAllocator().pop();
7017}
7018
7019}; // end namespace glslang