blob: ec1b5308d912590930d01b2e5726a63082768760 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
3// Copyright (C) 2015-2016 Google, Inc.
John Kessenich66011cb2018-03-06 16:12:04 -07004// Copyright (C) 2017 ARM Limited.
John Kessenich140f3df2015-06-26 16:58:36 -06005//
John Kessenich927608b2017-01-06 12:34:14 -07006// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06007//
John Kessenich927608b2017-01-06 12:34:14 -07008// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions
10// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060011//
12// Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//
15// Redistributions in binary form must reproduce the above
16// copyright notice, this list of conditions and the following
17// disclaimer in the documentation and/or other materials provided
18// with the distribution.
19//
20// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21// contributors may be used to endorse or promote products derived
22// from this software without specific prior written permission.
23//
John Kessenich927608b2017-01-06 12:34:14 -070024// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060036
37//
John Kessenich140f3df2015-06-26 16:58:36 -060038// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080046 #include "GLSL.std.450.h"
47 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070048 #include "GLSL.ext.EXT.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080050 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080051#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080052#ifdef NV_EXTENSIONS
53 #include "GLSL.ext.NV.h"
54#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060055}
John Kessenich140f3df2015-06-26 16:58:36 -060056
GregFfb03a552018-03-29 11:49:14 -060057#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -060058 #include "spirv-tools/optimizer.hpp"
59 #include "message.h"
GregFcd1f1692017-09-21 18:40:22 -060060#endif
61
GregFfb03a552018-03-29 11:49:14 -060062#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -060063using namespace spvtools;
64#endif
65
John Kessenich140f3df2015-06-26 16:58:36 -060066// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020067#include "../glslang/MachineIndependent/localintermediate.h"
68#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060069#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050070#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060071
John Kessenich140f3df2015-06-26 16:58:36 -060072#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050073#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040074#include <list>
75#include <map>
76#include <stack>
77#include <string>
78#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060079
80namespace {
81
qining4c912612016-04-01 10:35:16 -040082namespace {
83class SpecConstantOpModeGuard {
84public:
85 SpecConstantOpModeGuard(spv::Builder* builder)
86 : builder_(builder) {
87 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040088 }
89 ~SpecConstantOpModeGuard() {
90 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
91 : builder_->setToNormalCodeGenMode();
92 }
qining40887662016-04-03 22:20:42 -040093 void turnOnSpecConstantOpMode() {
94 builder_->setToSpecConstCodeGenMode();
95 }
qining4c912612016-04-01 10:35:16 -040096
97private:
98 spv::Builder* builder_;
99 bool previous_flag_;
100};
John Kessenichead86222018-03-28 18:01:20 -0600101
102struct OpDecorations {
103 spv::Decoration precision;
104 spv::Decoration noContraction;
John Kessenich5611c6d2018-04-05 11:25:02 -0600105 spv::Decoration nonUniform;
John Kessenichead86222018-03-28 18:01:20 -0600106};
107
108} // namespace
qining4c912612016-04-01 10:35:16 -0400109
John Kessenich140f3df2015-06-26 16:58:36 -0600110//
111// The main holder of information for translating glslang to SPIR-V.
112//
113// Derives from the AST walking base class.
114//
115class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
116public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700117 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
118 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700119 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600120
121 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
122 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
123 void visitConstantUnion(glslang::TIntermConstantUnion*);
124 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
125 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
126 void visitSymbol(glslang::TIntermSymbol* symbol);
127 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
128 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
129 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
130
John Kessenichfca82622016-11-26 13:23:20 -0700131 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700132 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600133
134protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700135 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
136 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
137
Rex Xu17ff3432016-10-14 17:41:45 +0800138 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800139 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600140 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100141 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700142 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700143 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
144 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenicha2858d92018-01-31 08:11:18 -0700145 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, unsigned int& dependencyLength) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600146 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600147 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich140f3df2015-06-26 16:58:36 -0600148 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
149 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600150 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
151 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
152 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600153 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kessenichead86222018-03-28 18:01:20 -0600154 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
155 bool lastBufferBlockMember);
John Kessenich0e737842017-03-24 18:38:16 -0600156 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600157 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
158 glslang::TLayoutPacking, const glslang::TQualifier&);
159 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
160 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700161 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700162 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800163 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600164 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700165 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700166 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
167 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700168 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
169 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100170 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600171
John Kessenich6fccb3c2016-09-19 16:01:41 -0600172 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600173 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600174 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600175 void makeFunctions(const glslang::TIntermSequence&);
176 void makeGlobalInitializers(const glslang::TIntermSequence&);
177 void visitFunctions(const glslang::TIntermSequence&);
178 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800179 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600180 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
181 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600182 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
183
John Kessenichead86222018-03-28 18:01:20 -0600184 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
185 glslang::TBasicType typeProxy, bool reduceComparison = true);
186 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
187 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
188 glslang::TBasicType typeProxy);
189 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
190 glslang::TBasicType typeProxy);
191 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
192 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600193 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600194 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800195 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800196 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800197 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700198 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600199 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800200 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600201 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
qining08408382016-03-21 09:51:37 -0400202 spv::Id createSpvConstant(const glslang::TIntermTyped&);
203 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600204 bool isTrivialLeaf(const glslang::TIntermTyped* node);
205 bool isTrivial(const glslang::TIntermTyped* node);
206 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500207#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800208 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500209#endif
John Kessenich66011cb2018-03-06 16:12:04 -0700210 void addPre13Extension(const char* ext)
211 {
212 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
213 builder.addExtension(ext);
214 }
John Kessenich140f3df2015-06-26 16:58:36 -0600215
John Kessenich121853f2017-05-31 17:11:16 -0600216 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600217 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600218 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700219 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600220 int sequenceDepth;
221
Lei Zhang17535f72016-05-04 15:55:59 -0400222 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400223
John Kessenich140f3df2015-06-26 16:58:36 -0600224 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
225 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700226 bool inEntryPoint;
227 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700228 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700229 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600230 const glslang::TIntermediate* glslangIntermediate;
231 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800232 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600233
John Kessenich2f273362015-07-18 22:34:27 -0600234 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600235 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600236 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700237 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700238 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
239 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600240 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700241 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
John Kessenich140f3df2015-06-26 16:58:36 -0600242};
243
244//
245// Helper functions for translating glslang representations to SPIR-V enumerants.
246//
247
248// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700249spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600250{
John Kessenich66e2faf2016-03-12 18:34:36 -0700251 switch (source) {
252 case glslang::EShSourceGlsl:
253 switch (profile) {
254 case ENoProfile:
255 case ECoreProfile:
256 case ECompatibilityProfile:
257 return spv::SourceLanguageGLSL;
258 case EEsProfile:
259 return spv::SourceLanguageESSL;
260 default:
261 return spv::SourceLanguageUnknown;
262 }
263 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600264 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600265 default:
266 return spv::SourceLanguageUnknown;
267 }
268}
269
270// Translate glslang language (stage) to SPIR-V execution model.
271spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
272{
273 switch (stage) {
274 case EShLangVertex: return spv::ExecutionModelVertex;
275 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
276 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
277 case EShLangGeometry: return spv::ExecutionModelGeometry;
278 case EShLangFragment: return spv::ExecutionModelFragment;
279 case EShLangCompute: return spv::ExecutionModelGLCompute;
280 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700281 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600282 return spv::ExecutionModelFragment;
283 }
284}
285
John Kessenich140f3df2015-06-26 16:58:36 -0600286// Translate glslang sampler type to SPIR-V dimensionality.
287spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
288{
289 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700290 case glslang::Esd1D: return spv::Dim1D;
291 case glslang::Esd2D: return spv::Dim2D;
292 case glslang::Esd3D: return spv::Dim3D;
293 case glslang::EsdCube: return spv::DimCube;
294 case glslang::EsdRect: return spv::DimRect;
295 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700296 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600297 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700298 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600299 return spv::Dim2D;
300 }
301}
302
John Kessenichf6640762016-08-01 19:44:00 -0600303// Translate glslang precision to SPIR-V precision decorations.
304spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600305{
John Kessenichf6640762016-08-01 19:44:00 -0600306 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700307 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600308 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600309 default:
310 return spv::NoPrecision;
311 }
312}
313
John Kessenichf6640762016-08-01 19:44:00 -0600314// Translate glslang type to SPIR-V precision decorations.
315spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
316{
317 return TranslatePrecisionDecoration(type.getQualifier().precision);
318}
319
John Kessenich140f3df2015-06-26 16:58:36 -0600320// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600321spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600322{
323 if (type.getBasicType() == glslang::EbtBlock) {
324 switch (type.getQualifier().storage) {
325 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600326 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600327 case glslang::EvqVaryingIn: return spv::DecorationBlock;
328 case glslang::EvqVaryingOut: return spv::DecorationBlock;
329 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700330 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600331 break;
332 }
333 }
334
John Kessenich4016e382016-07-15 11:53:56 -0600335 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600336}
337
Rex Xu1da878f2016-02-21 20:59:01 +0800338// Translate glslang type to SPIR-V memory decorations.
339void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
340{
341 if (qualifier.coherent)
342 memory.push_back(spv::DecorationCoherent);
John Kessenich14b85d32018-06-04 15:36:03 -0600343 if (qualifier.volatil) {
Rex Xu1da878f2016-02-21 20:59:01 +0800344 memory.push_back(spv::DecorationVolatile);
John Kessenich14b85d32018-06-04 15:36:03 -0600345 memory.push_back(spv::DecorationCoherent);
346 }
Rex Xu1da878f2016-02-21 20:59:01 +0800347 if (qualifier.restrict)
348 memory.push_back(spv::DecorationRestrict);
349 if (qualifier.readonly)
350 memory.push_back(spv::DecorationNonWritable);
351 if (qualifier.writeonly)
352 memory.push_back(spv::DecorationNonReadable);
353}
354
John Kessenich140f3df2015-06-26 16:58:36 -0600355// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700356spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600357{
358 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700359 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600360 case glslang::ElmRowMajor:
361 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700362 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600363 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700364 default:
365 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600366 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600367 }
368 } else {
369 switch (type.getBasicType()) {
370 default:
John Kessenich4016e382016-07-15 11:53:56 -0600371 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600372 break;
373 case glslang::EbtBlock:
374 switch (type.getQualifier().storage) {
375 case glslang::EvqUniform:
376 case glslang::EvqBuffer:
377 switch (type.getQualifier().layoutPacking) {
378 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600379 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
380 default:
John Kessenich4016e382016-07-15 11:53:56 -0600381 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600382 }
383 case glslang::EvqVaryingIn:
384 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700385 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600386 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600387 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700388 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600389 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600390 }
391 }
392 }
393}
394
395// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600396// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700397// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800398spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600399{
Rex Xubbceed72016-05-21 09:40:44 +0800400 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700401 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600402 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800403 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700404 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700405 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600406 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800407#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800408 else if (qualifier.explicitInterp) {
409 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800410 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800411 }
Rex Xu9d93a232016-05-05 12:30:44 +0800412#endif
Rex Xubbceed72016-05-21 09:40:44 +0800413 else
John Kessenich4016e382016-07-15 11:53:56 -0600414 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800415}
416
417// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600418// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800419// should be applied.
420spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
421{
422 if (qualifier.patch)
423 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700424 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600425 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700426 else if (qualifier.sample) {
427 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600428 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700429 } else
John Kessenich4016e382016-07-15 11:53:56 -0600430 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600431}
432
John Kessenich92187592016-02-01 13:45:25 -0700433// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700434spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600435{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700436 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600437 return spv::DecorationInvariant;
438 else
John Kessenich4016e382016-07-15 11:53:56 -0600439 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600440}
441
qining9220dbb2016-05-04 17:34:38 -0400442// If glslang type is noContraction, return SPIR-V NoContraction decoration.
443spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
444{
445 if (qualifier.noContraction)
446 return spv::DecorationNoContraction;
447 else
John Kessenich4016e382016-07-15 11:53:56 -0600448 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400449}
450
John Kessenich5611c6d2018-04-05 11:25:02 -0600451// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
452spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
453{
454 if (qualifier.isNonUniform()) {
455 builder.addExtension("SPV_EXT_descriptor_indexing");
456 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
457 return spv::DecorationNonUniformEXT;
458 } else
459 return spv::DecorationMax;
460}
461
David Netoa901ffe2016-06-08 14:11:40 +0100462// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
463// associated capabilities when required. For some built-in variables, a capability
464// is generated only when using the variable in an executable instruction, but not when
465// just declaring a struct member variable with it. This is true for PointSize,
466// ClipDistance, and CullDistance.
467spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600468{
469 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700470 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600471 // Defer adding the capability until the built-in is actually used.
472 if (! memberDeclaration) {
473 switch (glslangIntermediate->getStage()) {
474 case EShLangGeometry:
475 builder.addCapability(spv::CapabilityGeometryPointSize);
476 break;
477 case EShLangTessControl:
478 case EShLangTessEvaluation:
479 builder.addCapability(spv::CapabilityTessellationPointSize);
480 break;
481 default:
482 break;
483 }
John Kessenich92187592016-02-01 13:45:25 -0700484 }
485 return spv::BuiltInPointSize;
486
John Kessenichebb50532016-05-16 19:22:05 -0600487 // These *Distance capabilities logically belong here, but if the member is declared and
488 // then never used, consumers of SPIR-V prefer the capability not be declared.
489 // They are now generated when used, rather than here when declared.
490 // Potentially, the specification should be more clear what the minimum
491 // use needed is to trigger the capability.
492 //
John Kessenich92187592016-02-01 13:45:25 -0700493 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100494 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800495 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700496 return spv::BuiltInClipDistance;
497
498 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100499 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800500 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700501 return spv::BuiltInCullDistance;
502
503 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600504 builder.addCapability(spv::CapabilityMultiViewport);
505 if (glslangIntermediate->getStage() == EShLangVertex ||
506 glslangIntermediate->getStage() == EShLangTessControl ||
507 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800508
John Kessenichba6a3c22017-09-13 13:22:50 -0600509 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
510 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800511 }
John Kessenich92187592016-02-01 13:45:25 -0700512 return spv::BuiltInViewportIndex;
513
John Kessenich5e801132016-02-15 11:09:46 -0700514 case glslang::EbvSampleId:
515 builder.addCapability(spv::CapabilitySampleRateShading);
516 return spv::BuiltInSampleId;
517
518 case glslang::EbvSamplePosition:
519 builder.addCapability(spv::CapabilitySampleRateShading);
520 return spv::BuiltInSamplePosition;
521
522 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700523 return spv::BuiltInSampleMask;
524
John Kessenich78a45572016-07-08 14:05:15 -0600525 case glslang::EbvLayer:
John Kessenichba6a3c22017-09-13 13:22:50 -0600526 builder.addCapability(spv::CapabilityGeometry);
527 if (glslangIntermediate->getStage() == EShLangVertex ||
528 glslangIntermediate->getStage() == EShLangTessControl ||
529 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800530
John Kessenichba6a3c22017-09-13 13:22:50 -0600531 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
532 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800533 }
John Kessenich78a45572016-07-08 14:05:15 -0600534 return spv::BuiltInLayer;
535
John Kessenich140f3df2015-06-26 16:58:36 -0600536 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600537 case glslang::EbvVertexId: return spv::BuiltInVertexId;
538 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700539 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
540 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800541
John Kessenichda581a22015-10-14 14:10:30 -0600542 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700543 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800544 builder.addCapability(spv::CapabilityDrawParameters);
545 return spv::BuiltInBaseVertex;
546
John Kessenichda581a22015-10-14 14:10:30 -0600547 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700548 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800549 builder.addCapability(spv::CapabilityDrawParameters);
550 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200551
John Kessenichda581a22015-10-14 14:10:30 -0600552 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700553 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800554 builder.addCapability(spv::CapabilityDrawParameters);
555 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200556
557 case glslang::EbvPrimitiveId:
558 if (glslangIntermediate->getStage() == EShLangFragment)
559 builder.addCapability(spv::CapabilityGeometry);
560 return spv::BuiltInPrimitiveId;
561
Rex Xu37cdcee2017-06-29 17:46:34 +0800562 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800563 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
564 builder.addCapability(spv::CapabilityStencilExportEXT);
565 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800566
John Kessenich140f3df2015-06-26 16:58:36 -0600567 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600568 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
569 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
570 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
571 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
572 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
573 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
574 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600575 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
576 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
577 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
578 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
579 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
580 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
581 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
582 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800583
Rex Xu574ab042016-04-14 16:53:07 +0800584 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800585 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800586 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
587 return spv::BuiltInSubgroupSize;
588
Rex Xu574ab042016-04-14 16:53:07 +0800589 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800590 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800591 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
592 return spv::BuiltInSubgroupLocalInvocationId;
593
Rex Xu574ab042016-04-14 16:53:07 +0800594 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800595 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
596 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
597 return spv::BuiltInSubgroupEqMaskKHR;
598
Rex Xu574ab042016-04-14 16:53:07 +0800599 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800600 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
601 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
602 return spv::BuiltInSubgroupGeMaskKHR;
603
Rex Xu574ab042016-04-14 16:53:07 +0800604 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800605 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
606 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
607 return spv::BuiltInSubgroupGtMaskKHR;
608
Rex Xu574ab042016-04-14 16:53:07 +0800609 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800610 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
611 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
612 return spv::BuiltInSubgroupLeMaskKHR;
613
Rex Xu574ab042016-04-14 16:53:07 +0800614 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800615 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
616 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
617 return spv::BuiltInSubgroupLtMaskKHR;
618
John Kessenich66011cb2018-03-06 16:12:04 -0700619 case glslang::EbvNumSubgroups:
620 builder.addCapability(spv::CapabilityGroupNonUniform);
621 return spv::BuiltInNumSubgroups;
622
623 case glslang::EbvSubgroupID:
624 builder.addCapability(spv::CapabilityGroupNonUniform);
625 return spv::BuiltInSubgroupId;
626
627 case glslang::EbvSubgroupSize2:
628 builder.addCapability(spv::CapabilityGroupNonUniform);
629 return spv::BuiltInSubgroupSize;
630
631 case glslang::EbvSubgroupInvocation2:
632 builder.addCapability(spv::CapabilityGroupNonUniform);
633 return spv::BuiltInSubgroupLocalInvocationId;
634
635 case glslang::EbvSubgroupEqMask2:
636 builder.addCapability(spv::CapabilityGroupNonUniform);
637 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
638 return spv::BuiltInSubgroupEqMask;
639
640 case glslang::EbvSubgroupGeMask2:
641 builder.addCapability(spv::CapabilityGroupNonUniform);
642 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
643 return spv::BuiltInSubgroupGeMask;
644
645 case glslang::EbvSubgroupGtMask2:
646 builder.addCapability(spv::CapabilityGroupNonUniform);
647 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
648 return spv::BuiltInSubgroupGtMask;
649
650 case glslang::EbvSubgroupLeMask2:
651 builder.addCapability(spv::CapabilityGroupNonUniform);
652 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
653 return spv::BuiltInSubgroupLeMask;
654
655 case glslang::EbvSubgroupLtMask2:
656 builder.addCapability(spv::CapabilityGroupNonUniform);
657 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
658 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800659#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800660 case glslang::EbvBaryCoordNoPersp:
661 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
662 return spv::BuiltInBaryCoordNoPerspAMD;
663
664 case glslang::EbvBaryCoordNoPerspCentroid:
665 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
666 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
667
668 case glslang::EbvBaryCoordNoPerspSample:
669 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
670 return spv::BuiltInBaryCoordNoPerspSampleAMD;
671
672 case glslang::EbvBaryCoordSmooth:
673 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
674 return spv::BuiltInBaryCoordSmoothAMD;
675
676 case glslang::EbvBaryCoordSmoothCentroid:
677 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
678 return spv::BuiltInBaryCoordSmoothCentroidAMD;
679
680 case glslang::EbvBaryCoordSmoothSample:
681 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
682 return spv::BuiltInBaryCoordSmoothSampleAMD;
683
684 case glslang::EbvBaryCoordPullModel:
685 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
686 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800687#endif
chaoc771d89f2017-01-13 01:10:53 -0800688
John Kessenich6c8aaac2017-02-27 01:20:51 -0700689 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700690 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700691 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700692 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700693
694 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700695 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700696 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700697 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700698
chaoc771d89f2017-01-13 01:10:53 -0800699#ifdef NV_EXTENSIONS
700 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800701 if (!memberDeclaration) {
702 builder.addExtension(spv::E_SPV_NV_viewport_array2);
703 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
704 }
chaoc771d89f2017-01-13 01:10:53 -0800705 return spv::BuiltInViewportMaskNV;
706 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800707 if (!memberDeclaration) {
708 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
709 builder.addCapability(spv::CapabilityShaderStereoViewNV);
710 }
chaoc771d89f2017-01-13 01:10:53 -0800711 return spv::BuiltInSecondaryPositionNV;
712 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800713 if (!memberDeclaration) {
714 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
715 builder.addCapability(spv::CapabilityShaderStereoViewNV);
716 }
chaoc771d89f2017-01-13 01:10:53 -0800717 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800718 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800719 if (!memberDeclaration) {
720 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
721 builder.addCapability(spv::CapabilityPerViewAttributesNV);
722 }
chaocdf3956c2017-02-14 14:52:34 -0800723 return spv::BuiltInPositionPerViewNV;
724 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800725 if (!memberDeclaration) {
726 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
727 builder.addCapability(spv::CapabilityPerViewAttributesNV);
728 }
chaocdf3956c2017-02-14 14:52:34 -0800729 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700730 case glslang::EbvFragFullyCoveredNV:
731 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
732 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
733 return spv::BuiltInFullyCoveredEXT;
chaoc771d89f2017-01-13 01:10:53 -0800734#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800735 default:
736 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600737 }
738}
739
Rex Xufc618912015-09-09 16:42:49 +0800740// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700741spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800742{
743 assert(type.getBasicType() == glslang::EbtSampler);
744
John Kessenich5d0fa972016-02-15 11:57:00 -0700745 // Check for capabilities
746 switch (type.getQualifier().layoutFormat) {
747 case glslang::ElfRg32f:
748 case glslang::ElfRg16f:
749 case glslang::ElfR11fG11fB10f:
750 case glslang::ElfR16f:
751 case glslang::ElfRgba16:
752 case glslang::ElfRgb10A2:
753 case glslang::ElfRg16:
754 case glslang::ElfRg8:
755 case glslang::ElfR16:
756 case glslang::ElfR8:
757 case glslang::ElfRgba16Snorm:
758 case glslang::ElfRg16Snorm:
759 case glslang::ElfRg8Snorm:
760 case glslang::ElfR16Snorm:
761 case glslang::ElfR8Snorm:
762
763 case glslang::ElfRg32i:
764 case glslang::ElfRg16i:
765 case glslang::ElfRg8i:
766 case glslang::ElfR16i:
767 case glslang::ElfR8i:
768
769 case glslang::ElfRgb10a2ui:
770 case glslang::ElfRg32ui:
771 case glslang::ElfRg16ui:
772 case glslang::ElfRg8ui:
773 case glslang::ElfR16ui:
774 case glslang::ElfR8ui:
775 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
776 break;
777
778 default:
779 break;
780 }
781
782 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800783 switch (type.getQualifier().layoutFormat) {
784 case glslang::ElfNone: return spv::ImageFormatUnknown;
785 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
786 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
787 case glslang::ElfR32f: return spv::ImageFormatR32f;
788 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
789 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
790 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
791 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
792 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
793 case glslang::ElfR16f: return spv::ImageFormatR16f;
794 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
795 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
796 case glslang::ElfRg16: return spv::ImageFormatRg16;
797 case glslang::ElfRg8: return spv::ImageFormatRg8;
798 case glslang::ElfR16: return spv::ImageFormatR16;
799 case glslang::ElfR8: return spv::ImageFormatR8;
800 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
801 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
802 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
803 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
804 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
805 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
806 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
807 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
808 case glslang::ElfR32i: return spv::ImageFormatR32i;
809 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
810 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
811 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
812 case glslang::ElfR16i: return spv::ImageFormatR16i;
813 case glslang::ElfR8i: return spv::ImageFormatR8i;
814 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
815 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
816 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
817 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
818 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
819 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
820 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
821 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
822 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
823 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600824 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800825 }
826}
827
John Kesseniche18fd202018-01-30 11:01:39 -0700828spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +0800829{
John Kesseniche18fd202018-01-30 11:01:39 -0700830 if (selectionNode.getFlatten())
831 return spv::SelectionControlFlattenMask;
832 if (selectionNode.getDontFlatten())
833 return spv::SelectionControlDontFlattenMask;
834 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +0800835}
836
John Kesseniche18fd202018-01-30 11:01:39 -0700837spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -0600838{
John Kesseniche18fd202018-01-30 11:01:39 -0700839 if (switchNode.getFlatten())
840 return spv::SelectionControlFlattenMask;
841 if (switchNode.getDontFlatten())
842 return spv::SelectionControlDontFlattenMask;
843 return spv::SelectionControlMaskNone;
844}
845
John Kessenicha2858d92018-01-31 08:11:18 -0700846// return a non-0 dependency if the dependency argument must be set
847spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
848 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -0700849{
850 spv::LoopControlMask control = spv::LoopControlMaskNone;
851
852 if (loopNode.getDontUnroll())
853 control = control | spv::LoopControlDontUnrollMask;
854 if (loopNode.getUnroll())
855 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -0700856 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -0700857 control = control | spv::LoopControlDependencyInfiniteMask;
858 else if (loopNode.getLoopDependency() > 0) {
859 control = control | spv::LoopControlDependencyLengthMask;
860 dependencyLength = loopNode.getLoopDependency();
861 }
John Kesseniche18fd202018-01-30 11:01:39 -0700862
863 return control;
steve-lunargf1709e72017-05-02 20:14:50 -0600864}
865
John Kessenicha5c5fb62017-05-05 05:09:58 -0600866// Translate glslang type to SPIR-V storage class.
867spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
868{
869 if (type.getQualifier().isPipeInput())
870 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600871 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -0600872 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600873
874 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
875 type.getQualifier().storage == glslang::EvqUniform) {
876 if (type.getBasicType() == glslang::EbtAtomicUint)
877 return spv::StorageClassAtomicCounter;
878 if (type.containsOpaque())
879 return spv::StorageClassUniformConstant;
880 }
881
882 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -0700883 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -0600884 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600885 }
886
887 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600888 if (type.getQualifier().layoutPushConstant)
889 return spv::StorageClassPushConstant;
890 if (type.getBasicType() == glslang::EbtBlock)
891 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600892 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600893 }
John Kessenichbed4e4f2017-09-08 02:38:07 -0600894
895 switch (type.getQualifier().storage) {
896 case glslang::EvqShared: return spv::StorageClassWorkgroup;
897 case glslang::EvqGlobal: return spv::StorageClassPrivate;
898 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
899 case glslang::EvqTemporary: return spv::StorageClassFunction;
900 default:
901 assert(0);
902 break;
903 }
904
905 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600906}
907
John Kessenich5611c6d2018-04-05 11:25:02 -0600908// Add capabilities pertaining to how an array is indexed.
909void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
910 const glslang::TType& indexType)
911{
912 if (indexType.getQualifier().isNonUniform()) {
913 // deal with an asserted non-uniform index
914 if (baseType.getBasicType() == glslang::EbtSampler) {
915 if (baseType.getQualifier().hasAttachment())
916 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
917 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
918 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
919 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
920 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
921 else if (baseType.isImage())
922 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
923 else if (baseType.isTexture())
924 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
925 } else if (baseType.getBasicType() == glslang::EbtBlock) {
926 if (baseType.getQualifier().storage == glslang::EvqBuffer)
927 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
928 else if (baseType.getQualifier().storage == glslang::EvqUniform)
929 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
930 }
931 } else {
932 // assume a dynamically uniform index
933 if (baseType.getBasicType() == glslang::EbtSampler) {
934 if (baseType.getQualifier().hasAttachment())
935 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
936 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
937 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
938 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
939 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
940 }
941 }
942}
943
qining25262b32016-05-06 17:25:16 -0400944// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700945// descriptor set.
946bool IsDescriptorResource(const glslang::TType& type)
947{
John Kessenichf7497e22016-03-08 21:36:22 -0700948 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700949 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700950 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700951
952 // non block...
953 // basically samplerXXX/subpass/sampler/texture are all included
954 // if they are the global-scope-class, not the function parameter
955 // (or local, if they ever exist) class.
956 if (type.getBasicType() == glslang::EbtSampler)
957 return type.getQualifier().isUniformOrBuffer();
958
959 // None of the above.
960 return false;
961}
962
John Kesseniche0b6cad2015-12-24 10:30:13 -0700963void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
964{
965 if (child.layoutMatrix == glslang::ElmNone)
966 child.layoutMatrix = parent.layoutMatrix;
967
968 if (parent.invariant)
969 child.invariant = true;
970 if (parent.nopersp)
971 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800972#ifdef AMD_EXTENSIONS
973 if (parent.explicitInterp)
974 child.explicitInterp = true;
975#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700976 if (parent.flat)
977 child.flat = true;
978 if (parent.centroid)
979 child.centroid = true;
980 if (parent.patch)
981 child.patch = true;
982 if (parent.sample)
983 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800984 if (parent.coherent)
985 child.coherent = true;
986 if (parent.volatil)
987 child.volatil = true;
988 if (parent.restrict)
989 child.restrict = true;
990 if (parent.readonly)
991 child.readonly = true;
992 if (parent.writeonly)
993 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700994}
995
John Kessenichf2b7f332016-09-01 17:05:23 -0600996bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700997{
John Kessenich7b9fa252016-01-21 18:56:57 -0700998 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600999 // - struct members might inherit from a struct declaration
1000 // (note that non-block structs don't explicitly inherit,
1001 // only implicitly, meaning no decoration involved)
1002 // - affect decorations on the struct members
1003 // (note smooth does not, and expecting something like volatile
1004 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001005 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001006 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001007}
1008
John Kessenich140f3df2015-06-26 16:58:36 -06001009//
1010// Implement the TGlslangToSpvTraverser class.
1011//
1012
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001013TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001014 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1015 : TIntermTraverser(true, false, true),
1016 options(options),
1017 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001018 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001019 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001020 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001021 glslangIntermediate(glslangIntermediate)
1022{
1023 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1024
1025 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001026 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1027 glslangIntermediate->getVersion());
1028
John Kessenich121853f2017-05-31 17:11:16 -06001029 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001030 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001031 builder.setSourceFile(glslangIntermediate->getSourceFile());
1032
1033 // Set the source shader's text. If for SPV version 1.0, include
1034 // a preamble in comments stating the OpModuleProcessed instructions.
1035 // Otherwise, emit those as actual instructions.
1036 std::string text;
1037 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1038 for (int p = 0; p < (int)processes.size(); ++p) {
1039 if (glslangIntermediate->getSpv().spv < 0x00010100) {
1040 text.append("// OpModuleProcessed ");
1041 text.append(processes[p]);
1042 text.append("\n");
1043 } else
1044 builder.addModuleProcessed(processes[p]);
1045 }
1046 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
1047 text.append("#line 1\n");
1048 text.append(glslangIntermediate->getSourceText());
1049 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -06001050 }
John Kessenich140f3df2015-06-26 16:58:36 -06001051 stdBuiltins = builder.import("GLSL.std.450");
1052 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -06001053 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1054 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001055
1056 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001057 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1058 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001059 builder.addSourceExtension(it->c_str());
1060
1061 // Add the top-level modes for this shader.
1062
John Kessenich92187592016-02-01 13:45:25 -07001063 if (glslangIntermediate->getXfbMode()) {
1064 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001065 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001066 }
John Kessenich140f3df2015-06-26 16:58:36 -06001067
1068 unsigned int mode;
1069 switch (glslangIntermediate->getStage()) {
1070 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001071 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001072 break;
1073
steve-lunarge7412492017-03-23 11:56:07 -06001074 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001075 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001076 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001077
steve-lunarge7412492017-03-23 11:56:07 -06001078 glslang::TLayoutGeometry primitive;
1079
1080 if (glslangIntermediate->getStage() == EShLangTessControl) {
1081 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1082 primitive = glslangIntermediate->getOutputPrimitive();
1083 } else {
1084 primitive = glslangIntermediate->getInputPrimitive();
1085 }
1086
1087 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001088 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1089 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1090 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001091 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001092 }
John Kessenich4016e382016-07-15 11:53:56 -06001093 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001094 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1095
John Kesseniche6903322015-10-13 16:29:02 -06001096 switch (glslangIntermediate->getVertexSpacing()) {
1097 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1098 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1099 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001100 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001101 }
John Kessenich4016e382016-07-15 11:53:56 -06001102 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001103 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1104
1105 switch (glslangIntermediate->getVertexOrder()) {
1106 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1107 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001108 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001109 }
John Kessenich4016e382016-07-15 11:53:56 -06001110 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001111 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1112
1113 if (glslangIntermediate->getPointMode())
1114 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001115 break;
1116
1117 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001118 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001119 switch (glslangIntermediate->getInputPrimitive()) {
1120 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1121 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1122 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001123 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001124 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001125 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001126 }
John Kessenich4016e382016-07-15 11:53:56 -06001127 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001128 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001129
John Kessenich140f3df2015-06-26 16:58:36 -06001130 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1131
1132 switch (glslangIntermediate->getOutputPrimitive()) {
1133 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1134 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1135 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001136 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001137 }
John Kessenich4016e382016-07-15 11:53:56 -06001138 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001139 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1140 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1141 break;
1142
1143 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001144 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001145 if (glslangIntermediate->getPixelCenterInteger())
1146 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001147
John Kessenich140f3df2015-06-26 16:58:36 -06001148 if (glslangIntermediate->getOriginUpperLeft())
1149 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001150 else
1151 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001152
1153 if (glslangIntermediate->getEarlyFragmentTests())
1154 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1155
chaocc1204522017-06-30 17:14:30 -07001156 if (glslangIntermediate->getPostDepthCoverage()) {
1157 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1158 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1159 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1160 }
1161
John Kesseniche6903322015-10-13 16:29:02 -06001162 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001163 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1164 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001165 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001166 }
John Kessenich4016e382016-07-15 11:53:56 -06001167 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001168 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1169
1170 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1171 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001172 break;
1173
1174 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001175 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001176 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1177 glslangIntermediate->getLocalSize(1),
1178 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001179 break;
1180
1181 default:
1182 break;
1183 }
John Kessenich140f3df2015-06-26 16:58:36 -06001184}
1185
John Kessenichfca82622016-11-26 13:23:20 -07001186// Finish creating SPV, after the traversal is complete.
1187void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001188{
John Kessenich517fe7a2016-11-26 13:31:47 -07001189 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001190 builder.setBuildPoint(shaderEntry->getLastBlock());
1191 builder.leaveFunction();
1192 }
1193
John Kessenich7ba63412015-12-20 17:37:07 -07001194 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001195 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1196 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001197
qiningda397332016-03-09 19:54:03 -05001198 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001199}
1200
John Kessenichfca82622016-11-26 13:23:20 -07001201// Write the SPV into 'out'.
1202void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001203{
John Kessenichfca82622016-11-26 13:23:20 -07001204 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001205}
1206
1207//
1208// Implement the traversal functions.
1209//
1210// Return true from interior nodes to have the external traversal
1211// continue on to children. Return false if children were
1212// already processed.
1213//
1214
1215//
qining25262b32016-05-06 17:25:16 -04001216// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001217// - uniform/input reads
1218// - output writes
1219// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1220// - something simple that degenerates into the last bullet
1221//
1222void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1223{
qining75d1d802016-04-06 14:42:01 -04001224 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1225 if (symbol->getType().getQualifier().isSpecConstant())
1226 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1227
John Kessenich140f3df2015-06-26 16:58:36 -06001228 // getSymbolId() will set up all the IO decorations on the first call.
1229 // Formal function parameters were mapped during makeFunctions().
1230 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001231
1232 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1233 if (builder.isPointer(id)) {
1234 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001235 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1236 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1237 iOSet.insert(id);
1238 }
John Kessenich7ba63412015-12-20 17:37:07 -07001239 }
1240
1241 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001242 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001243 // Prepare to generate code for the access
1244
1245 // L-value chains will be computed left to right. We're on the symbol now,
1246 // which is the left-most part of the access chain, so now is "clear" time,
1247 // followed by setting the base.
1248 builder.clearAccessChain();
1249
1250 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001251 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001252 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001253 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001254 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001255 // These are also pure R-values.
1256 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001257 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001258 builder.setAccessChainRValue(id);
1259 else
1260 builder.setAccessChainLValue(id);
1261 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001262
1263 // Process linkage-only nodes for any special additional interface work.
1264 if (linkageOnly) {
1265 if (glslangIntermediate->getHlslFunctionality1()) {
1266 // Map implicit counter buffers to their originating buffers, which should have been
1267 // seen by now, given earlier pruning of unused counters, and preservation of order
1268 // of declaration.
1269 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1270 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1271 // Save possible originating buffers for counter buffers, keyed by
1272 // making the potential counter-buffer name.
1273 std::string keyName = symbol->getName().c_str();
1274 keyName = glslangIntermediate->addCounterBufferName(keyName);
1275 counterOriginator[keyName] = symbol;
1276 } else {
1277 // Handle a counter buffer, by finding the saved originating buffer.
1278 std::string keyName = symbol->getName().c_str();
1279 auto it = counterOriginator.find(keyName);
1280 if (it != counterOriginator.end()) {
1281 id = getSymbolId(it->second);
1282 if (id != spv::NoResult) {
1283 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001284 if (counterId != spv::NoResult) {
1285 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001286 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001287 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001288 }
1289 }
1290 }
1291 }
1292 }
1293 }
John Kessenich140f3df2015-06-26 16:58:36 -06001294}
1295
1296bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1297{
John Kesseniche485c7a2017-05-31 18:50:53 -06001298 builder.setLine(node->getLoc().line);
1299
qining40887662016-04-03 22:20:42 -04001300 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1301 if (node->getType().getQualifier().isSpecConstant())
1302 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1303
John Kessenich140f3df2015-06-26 16:58:36 -06001304 // First, handle special cases
1305 switch (node->getOp()) {
1306 case glslang::EOpAssign:
1307 case glslang::EOpAddAssign:
1308 case glslang::EOpSubAssign:
1309 case glslang::EOpMulAssign:
1310 case glslang::EOpVectorTimesMatrixAssign:
1311 case glslang::EOpVectorTimesScalarAssign:
1312 case glslang::EOpMatrixTimesScalarAssign:
1313 case glslang::EOpMatrixTimesMatrixAssign:
1314 case glslang::EOpDivAssign:
1315 case glslang::EOpModAssign:
1316 case glslang::EOpAndAssign:
1317 case glslang::EOpInclusiveOrAssign:
1318 case glslang::EOpExclusiveOrAssign:
1319 case glslang::EOpLeftShiftAssign:
1320 case glslang::EOpRightShiftAssign:
1321 // A bin-op assign "a += b" means the same thing as "a = a + b"
1322 // where a is evaluated before b. For a simple assignment, GLSL
1323 // says to evaluate the left before the right. So, always, left
1324 // node then right node.
1325 {
1326 // get the left l-value, save it away
1327 builder.clearAccessChain();
1328 node->getLeft()->traverse(this);
1329 spv::Builder::AccessChain lValue = builder.getAccessChain();
1330
1331 // evaluate the right
1332 builder.clearAccessChain();
1333 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001334 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001335
1336 if (node->getOp() != glslang::EOpAssign) {
1337 // the left is also an r-value
1338 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001339 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001340
1341 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001342 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001343 TranslateNoContractionDecoration(node->getType().getQualifier()),
1344 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001345 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001346 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1347 node->getType().getBasicType());
1348
1349 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001350 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001351 }
1352
1353 // store the result
1354 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001355 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001356
1357 // assignments are expressions having an rValue after they are evaluated...
1358 builder.clearAccessChain();
1359 builder.setAccessChainRValue(rValue);
1360 }
1361 return false;
1362 case glslang::EOpIndexDirect:
1363 case glslang::EOpIndexDirectStruct:
1364 {
1365 // Get the left part of the access chain.
1366 node->getLeft()->traverse(this);
1367
1368 // Add the next element in the chain
1369
David Netoa901ffe2016-06-08 14:11:40 +01001370 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001371 if (! node->getLeft()->getType().isArray() &&
1372 node->getLeft()->getType().isVector() &&
1373 node->getOp() == glslang::EOpIndexDirect) {
1374 // This is essentially a hard-coded vector swizzle of size 1,
1375 // so short circuit the access-chain stuff with a swizzle.
1376 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001377 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001378 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001379 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001380 int spvIndex = glslangIndex;
1381 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1382 node->getOp() == glslang::EOpIndexDirectStruct)
1383 {
1384 // This may be, e.g., an anonymous block-member selection, which generally need
1385 // index remapping due to hidden members in anonymous blocks.
1386 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1387 assert(remapper.size() > 0);
1388 spvIndex = remapper[glslangIndex];
1389 }
John Kessenichebb50532016-05-16 19:22:05 -06001390
David Netoa901ffe2016-06-08 14:11:40 +01001391 // normal case for indexing array or structure or block
1392 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1393
1394 // Add capabilities here for accessing PointSize and clip/cull distance.
1395 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001396 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001397 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001398 }
1399 }
1400 return false;
1401 case glslang::EOpIndexIndirect:
1402 {
1403 // Structure or array or vector indirection.
1404 // Will use native SPIR-V access-chain for struct and array indirection;
1405 // matrices are arrays of vectors, so will also work for a matrix.
1406 // Will use the access chain's 'component' for variable index into a vector.
1407
1408 // This adapter is building access chains left to right.
1409 // Set up the access chain to the left.
1410 node->getLeft()->traverse(this);
1411
1412 // save it so that computing the right side doesn't trash it
1413 spv::Builder::AccessChain partial = builder.getAccessChain();
1414
1415 // compute the next index in the chain
1416 builder.clearAccessChain();
1417 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001418 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001419
John Kessenich5611c6d2018-04-05 11:25:02 -06001420 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1421
John Kessenich140f3df2015-06-26 16:58:36 -06001422 // restore the saved access chain
1423 builder.setAccessChain(partial);
1424
1425 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001426 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001427 else
John Kessenichfa668da2015-09-13 14:46:30 -06001428 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001429 }
1430 return false;
1431 case glslang::EOpVectorSwizzle:
1432 {
1433 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001434 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001435 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001436 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001437 }
1438 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001439 case glslang::EOpMatrixSwizzle:
1440 logger->missingFunctionality("matrix swizzle");
1441 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001442 case glslang::EOpLogicalOr:
1443 case glslang::EOpLogicalAnd:
1444 {
1445
1446 // These may require short circuiting, but can sometimes be done as straight
1447 // binary operations. The right operand must be short circuited if it has
1448 // side effects, and should probably be if it is complex.
1449 if (isTrivial(node->getRight()->getAsTyped()))
1450 break; // handle below as a normal binary operation
1451 // otherwise, we need to do dynamic short circuiting on the right operand
1452 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1453 builder.clearAccessChain();
1454 builder.setAccessChainRValue(result);
1455 }
1456 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001457 default:
1458 break;
1459 }
1460
1461 // Assume generic binary op...
1462
John Kessenich32cfd492016-02-02 12:37:46 -07001463 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001464 builder.clearAccessChain();
1465 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001466 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001467
John Kessenich32cfd492016-02-02 12:37:46 -07001468 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001469 builder.clearAccessChain();
1470 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001471 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001472
John Kessenich32cfd492016-02-02 12:37:46 -07001473 // get result
John Kessenichead86222018-03-28 18:01:20 -06001474 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001475 TranslateNoContractionDecoration(node->getType().getQualifier()),
1476 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001477 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001478 convertGlslangToSpvType(node->getType()), left, right,
1479 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001480
John Kessenich50e57562015-12-21 21:21:11 -07001481 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001482 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001483 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001484 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001485 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001486 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001487 return false;
1488 }
John Kessenich140f3df2015-06-26 16:58:36 -06001489}
1490
1491bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1492{
John Kesseniche485c7a2017-05-31 18:50:53 -06001493 builder.setLine(node->getLoc().line);
1494
qining40887662016-04-03 22:20:42 -04001495 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1496 if (node->getType().getQualifier().isSpecConstant())
1497 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1498
John Kessenichfc51d282015-08-19 13:34:18 -06001499 spv::Id result = spv::NoResult;
1500
1501 // try texturing first
1502 result = createImageTextureFunctionCall(node);
1503 if (result != spv::NoResult) {
1504 builder.clearAccessChain();
1505 builder.setAccessChainRValue(result);
1506
1507 return false; // done with this node
1508 }
1509
1510 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001511
1512 if (node->getOp() == glslang::EOpArrayLength) {
1513 // Quite special; won't want to evaluate the operand.
1514
John Kessenich5611c6d2018-04-05 11:25:02 -06001515 // Currently, the front-end does not allow .length() on an array until it is sized,
1516 // except for the last block membeor of an SSBO.
1517 // TODO: If this changes, link-time sized arrays might show up here, and need their
1518 // size extracted.
1519
John Kessenichc9a80832015-09-12 12:17:44 -06001520 // Normal .length() would have been constant folded by the front-end.
1521 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001522 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001523
John Kessenichc9a80832015-09-12 12:17:44 -06001524 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1525 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001526 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1527 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001528
1529 builder.clearAccessChain();
1530 builder.setAccessChainRValue(length);
1531
1532 return false;
1533 }
1534
John Kessenichfc51d282015-08-19 13:34:18 -06001535 // Start by evaluating the operand
1536
John Kessenich8c8505c2016-07-26 12:50:38 -06001537 // Does it need a swizzle inversion? If so, evaluation is inverted;
1538 // operate first on the swizzle base, then apply the swizzle.
1539 spv::Id invertedType = spv::NoType;
1540 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1541 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1542 invertedType = getInvertedSwizzleType(*node->getOperand());
1543
John Kessenich140f3df2015-06-26 16:58:36 -06001544 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001545 if (invertedType != spv::NoType)
1546 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1547 else
1548 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001549
Rex Xufc618912015-09-09 16:42:49 +08001550 spv::Id operand = spv::NoResult;
1551
1552 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1553 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001554 node->getOp() == glslang::EOpAtomicCounter ||
1555 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001556 operand = builder.accessChainGetLValue(); // Special case l-value operands
1557 else
John Kessenich32cfd492016-02-02 12:37:46 -07001558 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001559
John Kessenichead86222018-03-28 18:01:20 -06001560 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001561 TranslateNoContractionDecoration(node->getType().getQualifier()),
1562 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001563
1564 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001565 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001566 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001567
1568 // if not, then possibly an operation
1569 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001570 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001571
1572 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001573 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001574 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001575 builder.addDecoration(result, decorations.nonUniform);
1576 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001577
John Kessenich140f3df2015-06-26 16:58:36 -06001578 builder.clearAccessChain();
1579 builder.setAccessChainRValue(result);
1580
1581 return false; // done with this node
1582 }
1583
1584 // it must be a special case, check...
1585 switch (node->getOp()) {
1586 case glslang::EOpPostIncrement:
1587 case glslang::EOpPostDecrement:
1588 case glslang::EOpPreIncrement:
1589 case glslang::EOpPreDecrement:
1590 {
1591 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001592 spv::Id one = 0;
1593 if (node->getBasicType() == glslang::EbtFloat)
1594 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001595 else if (node->getBasicType() == glslang::EbtDouble)
1596 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001597 else if (node->getBasicType() == glslang::EbtFloat16)
1598 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001599 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1600 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001601 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1602 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001603 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1604 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001605 else
1606 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001607 glslang::TOperator op;
1608 if (node->getOp() == glslang::EOpPreIncrement ||
1609 node->getOp() == glslang::EOpPostIncrement)
1610 op = glslang::EOpAdd;
1611 else
1612 op = glslang::EOpSub;
1613
John Kessenichead86222018-03-28 18:01:20 -06001614 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001615 convertGlslangToSpvType(node->getType()), operand, one,
1616 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001617 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001618
1619 // The result of operation is always stored, but conditionally the
1620 // consumed result. The consumed result is always an r-value.
1621 builder.accessChainStore(result);
1622 builder.clearAccessChain();
1623 if (node->getOp() == glslang::EOpPreIncrement ||
1624 node->getOp() == glslang::EOpPreDecrement)
1625 builder.setAccessChainRValue(result);
1626 else
1627 builder.setAccessChainRValue(operand);
1628 }
1629
1630 return false;
1631
1632 case glslang::EOpEmitStreamVertex:
1633 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1634 return false;
1635 case glslang::EOpEndStreamPrimitive:
1636 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1637 return false;
1638
1639 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001640 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001641 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001642 }
John Kessenich140f3df2015-06-26 16:58:36 -06001643}
1644
1645bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1646{
qining27e04a02016-04-14 16:40:20 -04001647 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1648 if (node->getType().getQualifier().isSpecConstant())
1649 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1650
John Kessenichfc51d282015-08-19 13:34:18 -06001651 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001652 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1653 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001654
1655 // try texturing
1656 result = createImageTextureFunctionCall(node);
1657 if (result != spv::NoResult) {
1658 builder.clearAccessChain();
1659 builder.setAccessChainRValue(result);
1660
1661 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001662#ifdef AMD_EXTENSIONS
1663 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1664#else
John Kessenich56bab042015-09-16 10:54:31 -06001665 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001666#endif
Rex Xufc618912015-09-09 16:42:49 +08001667 // "imageStore" is a special case, which has no result
1668 return false;
1669 }
John Kessenichfc51d282015-08-19 13:34:18 -06001670
John Kessenich140f3df2015-06-26 16:58:36 -06001671 glslang::TOperator binOp = glslang::EOpNull;
1672 bool reduceComparison = true;
1673 bool isMatrix = false;
1674 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001675 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001676
1677 assert(node->getOp());
1678
John Kessenichf6640762016-08-01 19:44:00 -06001679 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001680
1681 switch (node->getOp()) {
1682 case glslang::EOpSequence:
1683 {
1684 if (preVisit)
1685 ++sequenceDepth;
1686 else
1687 --sequenceDepth;
1688
1689 if (sequenceDepth == 1) {
1690 // If this is the parent node of all the functions, we want to see them
1691 // early, so all call points have actual SPIR-V functions to reference.
1692 // In all cases, still let the traverser visit the children for us.
1693 makeFunctions(node->getAsAggregate()->getSequence());
1694
John Kessenich6fccb3c2016-09-19 16:01:41 -06001695 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001696 // anything else gets there, so visit out of order, doing them all now.
1697 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1698
John Kessenich6a60c2f2016-12-08 21:01:59 -07001699 // 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 -06001700 // so do them manually.
1701 visitFunctions(node->getAsAggregate()->getSequence());
1702
1703 return false;
1704 }
1705
1706 return true;
1707 }
1708 case glslang::EOpLinkerObjects:
1709 {
1710 if (visit == glslang::EvPreVisit)
1711 linkageOnly = true;
1712 else
1713 linkageOnly = false;
1714
1715 return true;
1716 }
1717 case glslang::EOpComma:
1718 {
1719 // processing from left to right naturally leaves the right-most
1720 // lying around in the access chain
1721 glslang::TIntermSequence& glslangOperands = node->getSequence();
1722 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1723 glslangOperands[i]->traverse(this);
1724
1725 return false;
1726 }
1727 case glslang::EOpFunction:
1728 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001729 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001730 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001731 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001732 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001733 } else {
1734 handleFunctionEntry(node);
1735 }
1736 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001737 if (inEntryPoint)
1738 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001739 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001740 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001741 }
1742
1743 return true;
1744 case glslang::EOpParameters:
1745 // Parameters will have been consumed by EOpFunction processing, but not
1746 // the body, so we still visited the function node's children, making this
1747 // child redundant.
1748 return false;
1749 case glslang::EOpFunctionCall:
1750 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001751 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001752 if (node->isUserDefined())
1753 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001754 // 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 -07001755 if (result) {
1756 builder.clearAccessChain();
1757 builder.setAccessChainRValue(result);
1758 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001759 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001760
1761 return false;
1762 }
1763 case glslang::EOpConstructMat2x2:
1764 case glslang::EOpConstructMat2x3:
1765 case glslang::EOpConstructMat2x4:
1766 case glslang::EOpConstructMat3x2:
1767 case glslang::EOpConstructMat3x3:
1768 case glslang::EOpConstructMat3x4:
1769 case glslang::EOpConstructMat4x2:
1770 case glslang::EOpConstructMat4x3:
1771 case glslang::EOpConstructMat4x4:
1772 case glslang::EOpConstructDMat2x2:
1773 case glslang::EOpConstructDMat2x3:
1774 case glslang::EOpConstructDMat2x4:
1775 case glslang::EOpConstructDMat3x2:
1776 case glslang::EOpConstructDMat3x3:
1777 case glslang::EOpConstructDMat3x4:
1778 case glslang::EOpConstructDMat4x2:
1779 case glslang::EOpConstructDMat4x3:
1780 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001781 case glslang::EOpConstructIMat2x2:
1782 case glslang::EOpConstructIMat2x3:
1783 case glslang::EOpConstructIMat2x4:
1784 case glslang::EOpConstructIMat3x2:
1785 case glslang::EOpConstructIMat3x3:
1786 case glslang::EOpConstructIMat3x4:
1787 case glslang::EOpConstructIMat4x2:
1788 case glslang::EOpConstructIMat4x3:
1789 case glslang::EOpConstructIMat4x4:
1790 case glslang::EOpConstructUMat2x2:
1791 case glslang::EOpConstructUMat2x3:
1792 case glslang::EOpConstructUMat2x4:
1793 case glslang::EOpConstructUMat3x2:
1794 case glslang::EOpConstructUMat3x3:
1795 case glslang::EOpConstructUMat3x4:
1796 case glslang::EOpConstructUMat4x2:
1797 case glslang::EOpConstructUMat4x3:
1798 case glslang::EOpConstructUMat4x4:
1799 case glslang::EOpConstructBMat2x2:
1800 case glslang::EOpConstructBMat2x3:
1801 case glslang::EOpConstructBMat2x4:
1802 case glslang::EOpConstructBMat3x2:
1803 case glslang::EOpConstructBMat3x3:
1804 case glslang::EOpConstructBMat3x4:
1805 case glslang::EOpConstructBMat4x2:
1806 case glslang::EOpConstructBMat4x3:
1807 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001808 case glslang::EOpConstructF16Mat2x2:
1809 case glslang::EOpConstructF16Mat2x3:
1810 case glslang::EOpConstructF16Mat2x4:
1811 case glslang::EOpConstructF16Mat3x2:
1812 case glslang::EOpConstructF16Mat3x3:
1813 case glslang::EOpConstructF16Mat3x4:
1814 case glslang::EOpConstructF16Mat4x2:
1815 case glslang::EOpConstructF16Mat4x3:
1816 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06001817 isMatrix = true;
1818 // fall through
1819 case glslang::EOpConstructFloat:
1820 case glslang::EOpConstructVec2:
1821 case glslang::EOpConstructVec3:
1822 case glslang::EOpConstructVec4:
1823 case glslang::EOpConstructDouble:
1824 case glslang::EOpConstructDVec2:
1825 case glslang::EOpConstructDVec3:
1826 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001827 case glslang::EOpConstructFloat16:
1828 case glslang::EOpConstructF16Vec2:
1829 case glslang::EOpConstructF16Vec3:
1830 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001831 case glslang::EOpConstructBool:
1832 case glslang::EOpConstructBVec2:
1833 case glslang::EOpConstructBVec3:
1834 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07001835 case glslang::EOpConstructInt8:
1836 case glslang::EOpConstructI8Vec2:
1837 case glslang::EOpConstructI8Vec3:
1838 case glslang::EOpConstructI8Vec4:
1839 case glslang::EOpConstructUint8:
1840 case glslang::EOpConstructU8Vec2:
1841 case glslang::EOpConstructU8Vec3:
1842 case glslang::EOpConstructU8Vec4:
1843 case glslang::EOpConstructInt16:
1844 case glslang::EOpConstructI16Vec2:
1845 case glslang::EOpConstructI16Vec3:
1846 case glslang::EOpConstructI16Vec4:
1847 case glslang::EOpConstructUint16:
1848 case glslang::EOpConstructU16Vec2:
1849 case glslang::EOpConstructU16Vec3:
1850 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001851 case glslang::EOpConstructInt:
1852 case glslang::EOpConstructIVec2:
1853 case glslang::EOpConstructIVec3:
1854 case glslang::EOpConstructIVec4:
1855 case glslang::EOpConstructUint:
1856 case glslang::EOpConstructUVec2:
1857 case glslang::EOpConstructUVec3:
1858 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001859 case glslang::EOpConstructInt64:
1860 case glslang::EOpConstructI64Vec2:
1861 case glslang::EOpConstructI64Vec3:
1862 case glslang::EOpConstructI64Vec4:
1863 case glslang::EOpConstructUint64:
1864 case glslang::EOpConstructU64Vec2:
1865 case glslang::EOpConstructU64Vec3:
1866 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001867 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001868 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001869 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001870 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001871 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001872 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001873 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001874 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001875 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001876 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001877 std::vector<spv::Id> constituents;
1878 for (int c = 0; c < (int)arguments.size(); ++c)
1879 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001880 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001881 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001882 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001883 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001884 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001885
1886 builder.clearAccessChain();
1887 builder.setAccessChainRValue(constructed);
1888
1889 return false;
1890 }
1891
1892 // These six are component-wise compares with component-wise results.
1893 // Forward on to createBinaryOperation(), requesting a vector result.
1894 case glslang::EOpLessThan:
1895 case glslang::EOpGreaterThan:
1896 case glslang::EOpLessThanEqual:
1897 case glslang::EOpGreaterThanEqual:
1898 case glslang::EOpVectorEqual:
1899 case glslang::EOpVectorNotEqual:
1900 {
1901 // Map the operation to a binary
1902 binOp = node->getOp();
1903 reduceComparison = false;
1904 switch (node->getOp()) {
1905 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1906 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1907 default: binOp = node->getOp(); break;
1908 }
1909
1910 break;
1911 }
1912 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001913 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001914 binOp = glslang::EOpMul;
1915 break;
1916 case glslang::EOpOuterProduct:
1917 // two vectors multiplied to make a matrix
1918 binOp = glslang::EOpOuterProduct;
1919 break;
1920 case glslang::EOpDot:
1921 {
qining25262b32016-05-06 17:25:16 -04001922 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001923 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001924 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001925 binOp = glslang::EOpMul;
1926 break;
1927 }
1928 case glslang::EOpMod:
1929 // when an aggregate, this is the floating-point mod built-in function,
1930 // which can be emitted by the one in createBinaryOperation()
1931 binOp = glslang::EOpMod;
1932 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001933 case glslang::EOpEmitVertex:
1934 case glslang::EOpEndPrimitive:
1935 case glslang::EOpBarrier:
1936 case glslang::EOpMemoryBarrier:
1937 case glslang::EOpMemoryBarrierAtomicCounter:
1938 case glslang::EOpMemoryBarrierBuffer:
1939 case glslang::EOpMemoryBarrierImage:
1940 case glslang::EOpMemoryBarrierShared:
1941 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07001942 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001943 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07001944 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001945 case glslang::EOpWorkgroupMemoryBarrier:
1946 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07001947 case glslang::EOpSubgroupBarrier:
1948 case glslang::EOpSubgroupMemoryBarrier:
1949 case glslang::EOpSubgroupMemoryBarrierBuffer:
1950 case glslang::EOpSubgroupMemoryBarrierImage:
1951 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06001952 noReturnValue = true;
1953 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1954 break;
1955
John Kessenich426394d2015-07-23 10:22:48 -06001956 case glslang::EOpAtomicAdd:
1957 case glslang::EOpAtomicMin:
1958 case glslang::EOpAtomicMax:
1959 case glslang::EOpAtomicAnd:
1960 case glslang::EOpAtomicOr:
1961 case glslang::EOpAtomicXor:
1962 case glslang::EOpAtomicExchange:
1963 case glslang::EOpAtomicCompSwap:
1964 atomic = true;
1965 break;
1966
John Kessenich0d0c6d32017-07-23 16:08:26 -06001967 case glslang::EOpAtomicCounterAdd:
1968 case glslang::EOpAtomicCounterSubtract:
1969 case glslang::EOpAtomicCounterMin:
1970 case glslang::EOpAtomicCounterMax:
1971 case glslang::EOpAtomicCounterAnd:
1972 case glslang::EOpAtomicCounterOr:
1973 case glslang::EOpAtomicCounterXor:
1974 case glslang::EOpAtomicCounterExchange:
1975 case glslang::EOpAtomicCounterCompSwap:
1976 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1977 builder.addCapability(spv::CapabilityAtomicStorageOps);
1978 atomic = true;
1979 break;
1980
John Kessenich140f3df2015-06-26 16:58:36 -06001981 default:
1982 break;
1983 }
1984
1985 //
1986 // See if it maps to a regular operation.
1987 //
John Kessenich140f3df2015-06-26 16:58:36 -06001988 if (binOp != glslang::EOpNull) {
1989 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1990 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1991 assert(left && right);
1992
1993 builder.clearAccessChain();
1994 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001995 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001996
1997 builder.clearAccessChain();
1998 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001999 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002000
John Kesseniche485c7a2017-05-31 18:50:53 -06002001 builder.setLine(node->getLoc().line);
John Kessenichead86222018-03-28 18:01:20 -06002002 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002003 TranslateNoContractionDecoration(node->getType().getQualifier()),
2004 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002005 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002006 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002007 left->getType().getBasicType(), reduceComparison);
2008
2009 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002010 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002011 builder.clearAccessChain();
2012 builder.setAccessChainRValue(result);
2013
2014 return false;
2015 }
2016
John Kessenich426394d2015-07-23 10:22:48 -06002017 //
2018 // Create the list of operands.
2019 //
John Kessenich140f3df2015-06-26 16:58:36 -06002020 glslang::TIntermSequence& glslangOperands = node->getSequence();
2021 std::vector<spv::Id> operands;
2022 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002023 // special case l-value operands; there are just a few
2024 bool lvalue = false;
2025 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002026 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002027 case glslang::EOpModf:
2028 if (arg == 1)
2029 lvalue = true;
2030 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002031 case glslang::EOpInterpolateAtSample:
2032 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002033#ifdef AMD_EXTENSIONS
2034 case glslang::EOpInterpolateAtVertex:
2035#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002036 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002037 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002038
2039 // Does it need a swizzle inversion? If so, evaluation is inverted;
2040 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002041 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002042 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2043 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2044 }
Rex Xu7a26c172015-12-08 17:12:09 +08002045 break;
Rex Xud4782c12015-09-06 16:30:11 +08002046 case glslang::EOpAtomicAdd:
2047 case glslang::EOpAtomicMin:
2048 case glslang::EOpAtomicMax:
2049 case glslang::EOpAtomicAnd:
2050 case glslang::EOpAtomicOr:
2051 case glslang::EOpAtomicXor:
2052 case glslang::EOpAtomicExchange:
2053 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002054 case glslang::EOpAtomicCounterAdd:
2055 case glslang::EOpAtomicCounterSubtract:
2056 case glslang::EOpAtomicCounterMin:
2057 case glslang::EOpAtomicCounterMax:
2058 case glslang::EOpAtomicCounterAnd:
2059 case glslang::EOpAtomicCounterOr:
2060 case glslang::EOpAtomicCounterXor:
2061 case glslang::EOpAtomicCounterExchange:
2062 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002063 if (arg == 0)
2064 lvalue = true;
2065 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002066 case glslang::EOpAddCarry:
2067 case glslang::EOpSubBorrow:
2068 if (arg == 2)
2069 lvalue = true;
2070 break;
2071 case glslang::EOpUMulExtended:
2072 case glslang::EOpIMulExtended:
2073 if (arg >= 2)
2074 lvalue = true;
2075 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002076 default:
2077 break;
2078 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002079 builder.clearAccessChain();
2080 if (invertedType != spv::NoType && arg == 0)
2081 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2082 else
2083 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002084 if (lvalue)
2085 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002086 else {
2087 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07002088 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002089 }
John Kessenich140f3df2015-06-26 16:58:36 -06002090 }
John Kessenich426394d2015-07-23 10:22:48 -06002091
John Kesseniche485c7a2017-05-31 18:50:53 -06002092 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06002093 if (atomic) {
2094 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002095 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002096 } else {
2097 // Pass through to generic operations.
2098 switch (glslangOperands.size()) {
2099 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002100 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002101 break;
2102 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002103 {
2104 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002105 TranslateNoContractionDecoration(node->getType().getQualifier()),
2106 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002107 result = createUnaryOperation(
2108 node->getOp(), decorations,
2109 resultType(), operands.front(),
2110 glslangOperands[0]->getAsTyped()->getBasicType());
2111 }
John Kessenich426394d2015-07-23 10:22:48 -06002112 break;
2113 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002114 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002115 break;
2116 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002117 if (invertedType)
2118 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002119 }
2120
2121 if (noReturnValue)
2122 return false;
2123
2124 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002125 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002126 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002127 } else {
2128 builder.clearAccessChain();
2129 builder.setAccessChainRValue(result);
2130 return false;
2131 }
2132}
2133
John Kessenich433e9ff2017-01-26 20:31:11 -07002134// This path handles both if-then-else and ?:
2135// The if-then-else has a node type of void, while
2136// ?: has either a void or a non-void node type
2137//
2138// Leaving the result, when not void:
2139// GLSL only has r-values as the result of a :?, but
2140// if we have an l-value, that can be more efficient if it will
2141// become the base of a complex r-value expression, because the
2142// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002143bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2144{
John Kessenich4bee5312018-02-20 21:29:05 -07002145 // See if it simple and safe, or required, to execute both sides.
2146 // Crucially, side effects must be either semantically required or avoided,
2147 // and there are performance trade-offs.
2148 // Return true if required or a good idea (and safe) to execute both sides,
2149 // false otherwise.
2150 const auto bothSidesPolicy = [&]() -> bool {
2151 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002152 if (node->getTrueBlock() == nullptr ||
2153 node->getFalseBlock() == nullptr)
2154 return false;
2155
John Kessenich4bee5312018-02-20 21:29:05 -07002156 // required? (unless we write additional code to look for side effects
2157 // and make performance trade-offs if none are present)
2158 if (!node->getShortCircuit())
2159 return true;
2160
2161 // if not required to execute both, decide based on performance/practicality...
2162
2163 // see if OpSelect can handle it
2164 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2165 node->getBasicType() == glslang::EbtVoid)
2166 return false;
2167
John Kessenich433e9ff2017-01-26 20:31:11 -07002168 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2169 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2170
2171 // return true if a single operand to ? : is okay for OpSelect
2172 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002173 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002174 };
2175
2176 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2177 operandOkay(node->getFalseBlock()->getAsTyped());
2178 };
2179
John Kessenich4bee5312018-02-20 21:29:05 -07002180 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2181 // emit the condition before doing anything with selection
2182 node->getCondition()->traverse(this);
2183 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2184
2185 // Find a way of executing both sides and selecting the right result.
2186 const auto executeBothSides = [&]() -> void {
2187 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002188 node->getTrueBlock()->traverse(this);
2189 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2190 node->getFalseBlock()->traverse(this);
2191 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2192
John Kesseniche485c7a2017-05-31 18:50:53 -06002193 builder.setLine(node->getLoc().line);
2194
John Kessenich4bee5312018-02-20 21:29:05 -07002195 // done if void
2196 if (node->getBasicType() == glslang::EbtVoid)
2197 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002198
John Kessenich4bee5312018-02-20 21:29:05 -07002199 // emit code to select between trueValue and falseValue
2200
2201 // see if OpSelect can handle it
2202 if (node->getType().isScalar() || node->getType().isVector()) {
2203 // Emit OpSelect for this selection.
2204
2205 // smear condition to vector, if necessary (AST is always scalar)
2206 if (builder.isVector(trueValue))
2207 condition = builder.smearScalar(spv::NoPrecision, condition,
2208 builder.makeVectorType(builder.makeBoolType(),
2209 builder.getNumComponents(trueValue)));
2210
2211 // OpSelect
2212 result = builder.createTriOp(spv::OpSelect,
2213 convertGlslangToSpvType(node->getType()), condition,
2214 trueValue, falseValue);
2215
2216 builder.clearAccessChain();
2217 builder.setAccessChainRValue(result);
2218 } else {
2219 // We need control flow to select the result.
2220 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2221 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2222
2223 // Selection control:
2224 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2225
2226 // make an "if" based on the value created by the condition
2227 spv::Builder::If ifBuilder(condition, control, builder);
2228
2229 // emit the "then" statement
2230 builder.createStore(trueValue, result);
2231 ifBuilder.makeBeginElse();
2232 // emit the "else" statement
2233 builder.createStore(falseValue, result);
2234
2235 // finish off the control flow
2236 ifBuilder.makeEndIf();
2237
2238 builder.clearAccessChain();
2239 builder.setAccessChainLValue(result);
2240 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002241 };
2242
John Kessenich4bee5312018-02-20 21:29:05 -07002243 // Execute the one side needed, as per the condition
2244 const auto executeOneSide = [&]() {
2245 // Always emit control flow.
2246 if (node->getBasicType() != glslang::EbtVoid)
2247 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002248
John Kessenich4bee5312018-02-20 21:29:05 -07002249 // Selection control:
2250 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2251
2252 // make an "if" based on the value created by the condition
2253 spv::Builder::If ifBuilder(condition, control, builder);
2254
2255 // emit the "then" statement
2256 if (node->getTrueBlock() != nullptr) {
2257 node->getTrueBlock()->traverse(this);
2258 if (result != spv::NoResult)
2259 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2260 }
2261
2262 if (node->getFalseBlock() != nullptr) {
2263 ifBuilder.makeBeginElse();
2264 // emit the "else" statement
2265 node->getFalseBlock()->traverse(this);
2266 if (result != spv::NoResult)
2267 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2268 }
2269
2270 // finish off the control flow
2271 ifBuilder.makeEndIf();
2272
2273 if (result != spv::NoResult) {
2274 builder.clearAccessChain();
2275 builder.setAccessChainLValue(result);
2276 }
2277 };
2278
2279 // Try for OpSelect (or a requirement to execute both sides)
2280 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002281 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2282 if (node->getType().getQualifier().isSpecConstant())
2283 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002284 executeBothSides();
2285 } else
2286 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002287
2288 return false;
2289}
2290
2291bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2292{
2293 // emit and get the condition before doing anything with switch
2294 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002295 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002296
Rex Xu57e65922017-07-04 23:23:40 +08002297 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002298 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002299
John Kessenich140f3df2015-06-26 16:58:36 -06002300 // browse the children to sort out code segments
2301 int defaultSegment = -1;
2302 std::vector<TIntermNode*> codeSegments;
2303 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2304 std::vector<int> caseValues;
2305 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2306 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2307 TIntermNode* child = *c;
2308 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002309 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002310 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002311 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002312 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2313 } else
2314 codeSegments.push_back(child);
2315 }
2316
qining25262b32016-05-06 17:25:16 -04002317 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002318 // statements between the last case and the end of the switch statement
2319 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2320 (int)codeSegments.size() == defaultSegment)
2321 codeSegments.push_back(nullptr);
2322
2323 // make the switch statement
2324 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002325 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002326
2327 // emit all the code in the segments
2328 breakForLoop.push(false);
2329 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2330 builder.nextSwitchSegment(segmentBlocks, s);
2331 if (codeSegments[s])
2332 codeSegments[s]->traverse(this);
2333 else
2334 builder.addSwitchBreak();
2335 }
2336 breakForLoop.pop();
2337
2338 builder.endSwitch(segmentBlocks);
2339
2340 return false;
2341}
2342
2343void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2344{
2345 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002346 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002347
2348 builder.clearAccessChain();
2349 builder.setAccessChainRValue(constant);
2350}
2351
2352bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2353{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002354 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002355 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002356
2357 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002358 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2359 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002360
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002361 // Spec requires back edges to target header blocks, and every header block
2362 // must dominate its merge block. Make a header block first to ensure these
2363 // conditions are met. By definition, it will contain OpLoopMerge, followed
2364 // by a block-ending branch. But we don't want to put any other body/test
2365 // instructions in it, since the body/test may have arbitrary instructions,
2366 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002367 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002368 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002369 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002370 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002371 spv::Block& test = builder.makeNewBlock();
2372 builder.createBranch(&test);
2373
2374 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002375 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002376 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002377 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2378
2379 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002380 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002381 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002382 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002383 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002384 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002385
2386 builder.setBuildPoint(&blocks.continue_target);
2387 if (node->getTerminal())
2388 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002389 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002390 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002391 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002392 builder.createBranch(&blocks.body);
2393
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002394 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002395 builder.setBuildPoint(&blocks.body);
2396 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002397 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002398 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002399 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002400
2401 builder.setBuildPoint(&blocks.continue_target);
2402 if (node->getTerminal())
2403 node->getTerminal()->traverse(this);
2404 if (node->getTest()) {
2405 node->getTest()->traverse(this);
2406 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002407 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002408 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002409 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002410 // TODO: unless there was a break/return/discard instruction
2411 // somewhere in the body, this is an infinite loop, so we should
2412 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002413 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002414 }
John Kessenich140f3df2015-06-26 16:58:36 -06002415 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002416 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002417 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002418 return false;
2419}
2420
2421bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2422{
2423 if (node->getExpression())
2424 node->getExpression()->traverse(this);
2425
John Kesseniche485c7a2017-05-31 18:50:53 -06002426 builder.setLine(node->getLoc().line);
2427
John Kessenich140f3df2015-06-26 16:58:36 -06002428 switch (node->getFlowOp()) {
2429 case glslang::EOpKill:
2430 builder.makeDiscard();
2431 break;
2432 case glslang::EOpBreak:
2433 if (breakForLoop.top())
2434 builder.createLoopExit();
2435 else
2436 builder.addSwitchBreak();
2437 break;
2438 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002439 builder.createLoopContinue();
2440 break;
2441 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002442 if (node->getExpression()) {
2443 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2444 spv::Id returnId = accessChainLoad(glslangReturnType);
2445 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2446 builder.clearAccessChain();
2447 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2448 builder.setAccessChainLValue(copyId);
2449 multiTypeStore(glslangReturnType, returnId);
2450 returnId = builder.createLoad(copyId);
2451 }
2452 builder.makeReturn(false, returnId);
2453 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002454 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002455
2456 builder.clearAccessChain();
2457 break;
2458
2459 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002460 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002461 break;
2462 }
2463
2464 return false;
2465}
2466
2467spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2468{
qining25262b32016-05-06 17:25:16 -04002469 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002470 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002471 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002472 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002473 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002474 }
2475
2476 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002477 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002478 spv::Id spvType = convertGlslangToSpvType(node->getType());
2479
Rex Xucabbb782017-03-24 13:41:14 +08002480 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2481 node->getType().containsBasicType(glslang::EbtInt16) ||
2482 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002483 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002484 switch (storageClass) {
2485 case spv::StorageClassInput:
2486 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002487 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002488 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002489 break;
2490 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07002491 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002492 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06002493 break;
2494 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07002495 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002496 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2497 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06002498 else
2499 builder.addCapability(spv::CapabilityStorageUniform16);
2500 break;
2501 case spv::StorageClassStorageBuffer:
2502 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
2503 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2504 break;
2505 default:
2506 break;
Rex Xuf89ad982017-04-07 23:22:33 +08002507 }
2508 }
Rex Xuf89ad982017-04-07 23:22:33 +08002509
John Kessenich140f3df2015-06-26 16:58:36 -06002510 const char* name = node->getName().c_str();
2511 if (glslang::IsAnonymous(name))
2512 name = "";
2513
2514 return builder.createVariable(storageClass, spvType, name);
2515}
2516
2517// Return type Id of the sampled type.
2518spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2519{
2520 switch (sampler.type) {
2521 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08002522#ifdef AMD_EXTENSIONS
2523 case glslang::EbtFloat16:
2524 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
2525 builder.addCapability(spv::CapabilityFloat16ImageAMD);
2526 return builder.makeFloatType(16);
2527#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002528 case glslang::EbtInt: return builder.makeIntType(32);
2529 case glslang::EbtUint: return builder.makeUintType(32);
2530 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002531 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002532 return builder.makeFloatType(32);
2533 }
2534}
2535
John Kessenich8c8505c2016-07-26 12:50:38 -06002536// If node is a swizzle operation, return the type that should be used if
2537// the swizzle base is first consumed by another operation, before the swizzle
2538// is applied.
2539spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2540{
John Kessenichecba76f2017-01-06 00:34:48 -07002541 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002542 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2543 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2544 else
2545 return spv::NoType;
2546}
2547
2548// When inverting a swizzle with a parent op, this function
2549// will apply the swizzle operation to a completed parent operation.
2550spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2551{
2552 std::vector<unsigned> swizzle;
2553 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2554 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2555}
2556
John Kessenich8c8505c2016-07-26 12:50:38 -06002557// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2558void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2559{
2560 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2561 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2562 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2563}
2564
John Kessenich3ac051e2015-12-20 11:29:16 -07002565// Convert from a glslang type to an SPV type, by calling into a
2566// recursive version of this function. This establishes the inherited
2567// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002568spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2569{
John Kessenichead86222018-03-28 18:01:20 -06002570 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false);
John Kessenich31ed4832015-09-09 17:51:38 -06002571}
2572
2573// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002574// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002575// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06002576spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
2577 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier, bool lastBufferBlockMember)
John Kessenich31ed4832015-09-09 17:51:38 -06002578{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002579 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002580
2581 switch (type.getBasicType()) {
2582 case glslang::EbtVoid:
2583 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002584 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002585 break;
2586 case glslang::EbtFloat:
2587 spvType = builder.makeFloatType(32);
2588 break;
2589 case glslang::EbtDouble:
2590 spvType = builder.makeFloatType(64);
2591 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002592 case glslang::EbtFloat16:
John Kessenich66011cb2018-03-06 16:12:04 -07002593 builder.addCapability(spv::CapabilityFloat16);
2594#if AMD_EXTENSIONS
2595 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2596 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
2597#endif
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002598 spvType = builder.makeFloatType(16);
2599 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002600 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002601 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2602 // a 32-bit int where non-0 means true.
2603 if (explicitLayout != glslang::ElpNone)
2604 spvType = builder.makeUintType(32);
2605 else
2606 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002607 break;
John Kessenich66011cb2018-03-06 16:12:04 -07002608 case glslang::EbtInt8:
2609 builder.addCapability(spv::CapabilityInt8);
2610 spvType = builder.makeIntType(8);
2611 break;
2612 case glslang::EbtUint8:
2613 builder.addCapability(spv::CapabilityInt8);
2614 spvType = builder.makeUintType(8);
2615 break;
2616 case glslang::EbtInt16:
2617 builder.addCapability(spv::CapabilityInt16);
2618#ifdef AMD_EXTENSIONS
2619 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2620 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2621#endif
2622 spvType = builder.makeIntType(16);
2623 break;
2624 case glslang::EbtUint16:
2625 builder.addCapability(spv::CapabilityInt16);
2626#ifdef AMD_EXTENSIONS
2627 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2628 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2629#endif
2630 spvType = builder.makeUintType(16);
2631 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002632 case glslang::EbtInt:
2633 spvType = builder.makeIntType(32);
2634 break;
2635 case glslang::EbtUint:
2636 spvType = builder.makeUintType(32);
2637 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002638 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002639 spvType = builder.makeIntType(64);
2640 break;
2641 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002642 spvType = builder.makeUintType(64);
2643 break;
John Kessenich426394d2015-07-23 10:22:48 -06002644 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002645 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002646 spvType = builder.makeUintType(32);
2647 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002648 case glslang::EbtSampler:
2649 {
2650 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002651 if (sampler.sampler) {
2652 // pure sampler
2653 spvType = builder.makeSamplerType();
2654 } else {
2655 // an image is present, make its type
2656 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2657 sampler.image ? 2 : 1, TranslateImageFormat(type));
2658 if (sampler.combined) {
2659 // already has both image and sampler, make the combined type
2660 spvType = builder.makeSampledImageType(spvType);
2661 }
John Kessenich55e7d112015-11-15 21:33:39 -07002662 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002663 }
John Kessenich140f3df2015-06-26 16:58:36 -06002664 break;
2665 case glslang::EbtStruct:
2666 case glslang::EbtBlock:
2667 {
2668 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002669 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002670
2671 // Try to share structs for different layouts, but not yet for other
2672 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002673 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002674 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002675 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002676 break;
2677
2678 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002679 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002680 memberRemapper[glslangMembers].resize(glslangMembers->size());
2681 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002682 }
2683 break;
2684 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002685 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002686 break;
2687 }
2688
2689 if (type.isMatrix())
2690 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2691 else {
2692 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2693 if (type.getVectorSize() > 1)
2694 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2695 }
2696
2697 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002698 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2699
John Kessenichc9a80832015-09-12 12:17:44 -06002700 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002701 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002702 // We need to decorate array strides for types needing explicit layout, except blocks.
2703 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002704 // Use a dummy glslang type for querying internal strides of
2705 // arrays of arrays, but using just a one-dimensional array.
2706 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06002707 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
2708 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07002709
2710 // Will compute the higher-order strides here, rather than making a whole
2711 // pile of types and doing repetitive recursion on their contents.
2712 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2713 }
John Kessenichf8842e52016-01-04 19:22:56 -07002714
2715 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002716 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002717 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002718 if (stride > 0)
2719 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002720 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002721 }
2722 } else {
2723 // single-dimensional array, and don't yet have stride
2724
John Kessenichf8842e52016-01-04 19:22:56 -07002725 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002726 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2727 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002728 }
John Kessenich31ed4832015-09-09 17:51:38 -06002729
John Kessenichead86222018-03-28 18:01:20 -06002730 // Do the outer dimension, which might not be known for a runtime-sized array.
2731 // (Unsized arrays that survive through linking will be runtime-sized arrays)
2732 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07002733 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06002734 else {
2735 if (!lastBufferBlockMember) {
2736 builder.addExtension("SPV_EXT_descriptor_indexing");
2737 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
2738 }
John Kessenichead86222018-03-28 18:01:20 -06002739 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06002740 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002741 if (stride > 0)
2742 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002743 }
2744
2745 return spvType;
2746}
2747
John Kessenich0e737842017-03-24 18:38:16 -06002748// TODO: this functionality should exist at a higher level, in creating the AST
2749//
2750// Identify interface members that don't have their required extension turned on.
2751//
2752bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2753{
2754 auto& extensions = glslangIntermediate->getRequestedExtensions();
2755
Rex Xubcf291a2017-03-29 23:01:36 +08002756 if (member.getFieldName() == "gl_ViewportMask" &&
2757 extensions.find("GL_NV_viewport_array2") == extensions.end())
2758 return true;
2759 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2760 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2761 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002762 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2763 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2764 return true;
2765 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2766 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2767 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002768 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2769 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2770 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002771
2772 return false;
2773};
2774
John Kessenich6090df02016-06-30 21:18:02 -06002775// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2776// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2777// Mutually recursive with convertGlslangToSpvType().
2778spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2779 const glslang::TTypeList* glslangMembers,
2780 glslang::TLayoutPacking explicitLayout,
2781 const glslang::TQualifier& qualifier)
2782{
2783 // Create a vector of struct types for SPIR-V to consume
2784 std::vector<spv::Id> spvMembers;
2785 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 -06002786 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2787 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2788 if (glslangMember.hiddenMember()) {
2789 ++memberDelta;
2790 if (type.getBasicType() == glslang::EbtBlock)
2791 memberRemapper[glslangMembers][i] = -1;
2792 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002793 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002794 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002795 if (filterMember(glslangMember))
2796 continue;
2797 }
John Kessenich6090df02016-06-30 21:18:02 -06002798 // modify just this child's view of the qualifier
2799 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2800 InheritQualifiers(memberQualifier, qualifier);
2801
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002802 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002803 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002804 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002805
2806 // recurse
John Kessenichead86222018-03-28 18:01:20 -06002807 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
2808 i == (int)glslangMembers->size() - 1;
2809 spvMembers.push_back(
2810 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember));
John Kessenich6090df02016-06-30 21:18:02 -06002811 }
2812 }
2813
2814 // Make the SPIR-V type
2815 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002816 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002817 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2818
2819 // Decorate it
2820 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2821
2822 return spvType;
2823}
2824
2825void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2826 const glslang::TTypeList* glslangMembers,
2827 glslang::TLayoutPacking explicitLayout,
2828 const glslang::TQualifier& qualifier,
2829 spv::Id spvType)
2830{
2831 // Name and decorate the non-hidden members
2832 int offset = -1;
2833 int locationOffset = 0; // for use within the members of this struct
2834 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2835 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2836 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002837 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002838 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002839 if (filterMember(glslangMember))
2840 continue;
2841 }
John Kessenich6090df02016-06-30 21:18:02 -06002842
2843 // modify just this child's view of the qualifier
2844 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2845 InheritQualifiers(memberQualifier, qualifier);
2846
2847 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07002848 if (member < 0)
2849 continue;
2850
2851 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2852 builder.addMemberDecoration(spvType, member,
2853 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2854 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2855 // Add interpolation and auxiliary storage decorations only to
2856 // top-level members of Input and Output storage classes
2857 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2858 type.getQualifier().storage == glslang::EvqVaryingOut) {
2859 if (type.getBasicType() == glslang::EbtBlock ||
2860 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
2861 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2862 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002863 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002864 }
2865 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002866
John Kessenich5d610ee2018-03-07 18:05:55 -07002867 if (type.getBasicType() == glslang::EbtBlock &&
2868 qualifier.storage == glslang::EvqBuffer) {
2869 // Add memory decorations only to top-level members of shader storage block
2870 std::vector<spv::Decoration> memory;
2871 TranslateMemoryDecoration(memberQualifier, memory);
2872 for (unsigned int i = 0; i < memory.size(); ++i)
2873 builder.addMemberDecoration(spvType, member, memory[i]);
2874 }
John Kessenich6090df02016-06-30 21:18:02 -06002875
John Kessenich5d610ee2018-03-07 18:05:55 -07002876 // Location assignment was already completed correctly by the front end,
2877 // just track whether a member needs to be decorated.
2878 // Ignore member locations if the container is an array, as that's
2879 // ill-specified and decisions have been made to not allow this.
2880 if (! type.isArray() && memberQualifier.hasLocation())
2881 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002882
John Kessenich5d610ee2018-03-07 18:05:55 -07002883 if (qualifier.hasLocation()) // track for upcoming inheritance
2884 locationOffset += glslangIntermediate->computeTypeLocationSize(
2885 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06002886
John Kessenich5d610ee2018-03-07 18:05:55 -07002887 // component, XFB, others
2888 if (glslangMember.getQualifier().hasComponent())
2889 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
2890 glslangMember.getQualifier().layoutComponent);
2891 if (glslangMember.getQualifier().hasXfbOffset())
2892 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
2893 glslangMember.getQualifier().layoutXfbOffset);
2894 else if (explicitLayout != glslang::ElpNone) {
2895 // figure out what to do with offset, which is accumulating
2896 int nextOffset;
2897 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2898 if (offset >= 0)
2899 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2900 offset = nextOffset;
2901 }
John Kessenich6090df02016-06-30 21:18:02 -06002902
John Kessenich5d610ee2018-03-07 18:05:55 -07002903 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2904 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
2905 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06002906
John Kessenich5d610ee2018-03-07 18:05:55 -07002907 // built-in variable decorations
2908 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
2909 if (builtIn != spv::BuiltInMax)
2910 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002911
John Kessenich5611c6d2018-04-05 11:25:02 -06002912 // nonuniform
2913 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
2914
John Kessenichead86222018-03-28 18:01:20 -06002915 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
2916 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
2917 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
2918 memberQualifier.semanticName);
2919 }
2920
chaoc771d89f2017-01-13 01:10:53 -08002921#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07002922 if (builtIn == spv::BuiltInLayer) {
2923 // SPV_NV_viewport_array2 extension
2924 if (glslangMember.getQualifier().layoutViewportRelative){
2925 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2926 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2927 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08002928 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002929 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2930 builder.addMemberDecoration(spvType, member,
2931 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
2932 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2933 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2934 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08002935 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002936 }
2937 if (glslangMember.getQualifier().layoutPassthrough) {
2938 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2939 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2940 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2941 }
chaoc771d89f2017-01-13 01:10:53 -08002942#endif
John Kessenich6090df02016-06-30 21:18:02 -06002943 }
2944
2945 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07002946 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2947 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002948 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2949 builder.addCapability(spv::CapabilityGeometryStreams);
2950 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2951 }
John Kessenich6090df02016-06-30 21:18:02 -06002952}
2953
John Kessenich6c292d32016-02-15 20:58:50 -07002954// Turn the expression forming the array size into an id.
2955// This is not quite trivial, because of specialization constants.
2956// Sometimes, a raw constant is turned into an Id, and sometimes
2957// a specialization constant expression is.
2958spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2959{
2960 // First, see if this is sized with a node, meaning a specialization constant:
2961 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2962 if (specNode != nullptr) {
2963 builder.clearAccessChain();
2964 specNode->traverse(this);
2965 return accessChainLoad(specNode->getAsTyped()->getType());
2966 }
qining25262b32016-05-06 17:25:16 -04002967
John Kessenich6c292d32016-02-15 20:58:50 -07002968 // Otherwise, need a compile-time (front end) size, get it:
2969 int size = arraySizes.getDimSize(dim);
2970 assert(size > 0);
2971 return builder.makeUintConstant(size);
2972}
2973
John Kessenich103bef92016-02-08 21:38:15 -07002974// Wrap the builder's accessChainLoad to:
2975// - localize handling of RelaxedPrecision
2976// - use the SPIR-V inferred type instead of another conversion of the glslang type
2977// (avoids unnecessary work and possible type punning for structures)
2978// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002979spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2980{
John Kessenich103bef92016-02-08 21:38:15 -07002981 spv::Id nominalTypeId = builder.accessChainGetInferredType();
John Kessenich5611c6d2018-04-05 11:25:02 -06002982 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
2983 TranslateNonUniformDecoration(type.getQualifier()), nominalTypeId);
John Kessenich103bef92016-02-08 21:38:15 -07002984
2985 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002986 if (type.getBasicType() == glslang::EbtBool) {
2987 if (builder.isScalarType(nominalTypeId)) {
2988 // Conversion for bool
2989 spv::Id boolType = builder.makeBoolType();
2990 if (nominalTypeId != boolType)
2991 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2992 } else if (builder.isVectorType(nominalTypeId)) {
2993 // Conversion for bvec
2994 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2995 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2996 if (nominalTypeId != bvecType)
2997 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2998 }
2999 }
John Kessenich103bef92016-02-08 21:38:15 -07003000
3001 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003002}
3003
Rex Xu27253232016-02-23 17:51:09 +08003004// Wrap the builder's accessChainStore to:
3005// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003006//
3007// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003008void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3009{
3010 // Need to convert to abstract types when necessary
3011 if (type.getBasicType() == glslang::EbtBool) {
3012 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3013
3014 if (builder.isScalarType(nominalTypeId)) {
3015 // Conversion for bool
3016 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003017 if (nominalTypeId != boolType) {
3018 // keep these outside arguments, for determinant order-of-evaluation
3019 spv::Id one = builder.makeUintConstant(1);
3020 spv::Id zero = builder.makeUintConstant(0);
3021 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3022 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003023 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003024 } else if (builder.isVectorType(nominalTypeId)) {
3025 // Conversion for bvec
3026 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3027 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003028 if (nominalTypeId != bvecType) {
3029 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003030 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3031 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3032 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003033 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003034 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3035 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003036 }
3037 }
3038
3039 builder.accessChainStore(rvalue);
3040}
3041
John Kessenich4bf71552016-09-02 11:20:21 -06003042// For storing when types match at the glslang level, but not might match at the
3043// SPIR-V level.
3044//
3045// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003046// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003047// as in a member-decorated way.
3048//
3049// NOTE: This function can handle any store request; if it's not special it
3050// simplifies to a simple OpStore.
3051//
3052// Implicitly uses the existing builder.accessChain as the storage target.
3053void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3054{
John Kessenichb3e24e42016-09-11 12:33:43 -06003055 // we only do the complex path here if it's an aggregate
3056 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003057 accessChainStore(type, rValue);
3058 return;
3059 }
3060
John Kessenichb3e24e42016-09-11 12:33:43 -06003061 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003062 spv::Id rType = builder.getTypeId(rValue);
3063 spv::Id lValue = builder.accessChainGetLValue();
3064 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3065 if (lType == rType) {
3066 accessChainStore(type, rValue);
3067 return;
3068 }
3069
John Kessenichb3e24e42016-09-11 12:33:43 -06003070 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003071 // where the two types were the same type in GLSL. This requires member
3072 // by member copy, recursively.
3073
John Kessenichb3e24e42016-09-11 12:33:43 -06003074 // If an array, copy element by element.
3075 if (type.isArray()) {
3076 glslang::TType glslangElementType(type, 0);
3077 spv::Id elementRType = builder.getContainedTypeId(rType);
3078 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3079 // get the source member
3080 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003081
John Kessenichb3e24e42016-09-11 12:33:43 -06003082 // set up the target storage
3083 builder.clearAccessChain();
3084 builder.setAccessChainLValue(lValue);
3085 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06003086
John Kessenichb3e24e42016-09-11 12:33:43 -06003087 // store the member
3088 multiTypeStore(glslangElementType, elementRValue);
3089 }
3090 } else {
3091 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003092
John Kessenichb3e24e42016-09-11 12:33:43 -06003093 // loop over structure members
3094 const glslang::TTypeList& members = *type.getStruct();
3095 for (int m = 0; m < (int)members.size(); ++m) {
3096 const glslang::TType& glslangMemberType = *members[m].type;
3097
3098 // get the source member
3099 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3100 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3101
3102 // set up the target storage
3103 builder.clearAccessChain();
3104 builder.setAccessChainLValue(lValue);
3105 builder.accessChainPush(builder.makeIntConstant(m));
3106
3107 // store the member
3108 multiTypeStore(glslangMemberType, memberRValue);
3109 }
John Kessenich4bf71552016-09-02 11:20:21 -06003110 }
3111}
3112
John Kessenichf85e8062015-12-19 13:57:10 -07003113// Decide whether or not this type should be
3114// decorated with offsets and strides, and if so
3115// whether std140 or std430 rules should be applied.
3116glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003117{
John Kessenichf85e8062015-12-19 13:57:10 -07003118 // has to be a block
3119 if (type.getBasicType() != glslang::EbtBlock)
3120 return glslang::ElpNone;
3121
3122 // has to be a uniform or buffer block
3123 if (type.getQualifier().storage != glslang::EvqUniform &&
3124 type.getQualifier().storage != glslang::EvqBuffer)
3125 return glslang::ElpNone;
3126
3127 // return the layout to use
3128 switch (type.getQualifier().layoutPacking) {
3129 case glslang::ElpStd140:
3130 case glslang::ElpStd430:
3131 return type.getQualifier().layoutPacking;
3132 default:
3133 return glslang::ElpNone;
3134 }
John Kessenich31ed4832015-09-09 17:51:38 -06003135}
3136
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003137// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003138int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003139{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003140 int size;
John Kessenich49987892015-12-29 17:11:44 -07003141 int stride;
3142 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003143
3144 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003145}
3146
John Kessenich49987892015-12-29 17:11:44 -07003147// 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 -07003148// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003149int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003150{
John Kessenich49987892015-12-29 17:11:44 -07003151 glslang::TType elementType;
3152 elementType.shallowCopy(matrixType);
3153 elementType.clearArraySizes();
3154
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003155 int size;
John Kessenich49987892015-12-29 17:11:44 -07003156 int stride;
3157 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
3158
3159 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003160}
3161
John Kessenich5e4b1242015-08-06 22:53:06 -06003162// Given a member type of a struct, realign the current offset for it, and compute
3163// the next (not yet aligned) offset for the next member, which will get aligned
3164// on the next call.
3165// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3166// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3167// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003168void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003169 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003170{
3171 // this will get a positive value when deemed necessary
3172 nextOffset = -1;
3173
John Kessenich5e4b1242015-08-06 22:53:06 -06003174 // override anything in currentOffset with user-set offset
3175 if (memberType.getQualifier().hasOffset())
3176 currentOffset = memberType.getQualifier().layoutOffset;
3177
3178 // It could be that current linker usage in glslang updated all the layoutOffset,
3179 // in which case the following code does not matter. But, that's not quite right
3180 // once cross-compilation unit GLSL validation is done, as the original user
3181 // settings are needed in layoutOffset, and then the following will come into play.
3182
John Kessenichf85e8062015-12-19 13:57:10 -07003183 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003184 if (! memberType.getQualifier().hasOffset())
3185 currentOffset = -1;
3186
3187 return;
3188 }
3189
John Kessenichf85e8062015-12-19 13:57:10 -07003190 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003191 if (currentOffset < 0)
3192 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003193
John Kessenich5e4b1242015-08-06 22:53:06 -06003194 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3195 // but possibly not yet correctly aligned.
3196
3197 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003198 int dummyStride;
3199 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003200
3201 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003202 // TODO: make this consistent in early phases of code:
3203 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3204 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3205 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06003206 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003207 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003208 int dummySize;
3209 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3210 if (componentAlignment <= 4)
3211 memberAlignment = componentAlignment;
3212 }
3213
3214 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003215 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003216
3217 // Bump up to vec4 if there is a bad straddle
3218 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
3219 glslang::RoundToPow2(currentOffset, 16);
3220
John Kessenich5e4b1242015-08-06 22:53:06 -06003221 nextOffset = currentOffset + memberSize;
3222}
3223
David Netoa901ffe2016-06-08 14:11:40 +01003224void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003225{
David Netoa901ffe2016-06-08 14:11:40 +01003226 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3227 switch (glslangBuiltIn)
3228 {
3229 case glslang::EbvClipDistance:
3230 case glslang::EbvCullDistance:
3231 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003232#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003233 case glslang::EbvViewportMaskNV:
3234 case glslang::EbvSecondaryPositionNV:
3235 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003236 case glslang::EbvPositionPerViewNV:
3237 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08003238#endif
David Netoa901ffe2016-06-08 14:11:40 +01003239 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3240 // Alternately, we could just call this for any glslang built-in, since the
3241 // capability already guards against duplicates.
3242 TranslateBuiltInDecoration(glslangBuiltIn, false);
3243 break;
3244 default:
3245 // Capabilities were already generated when the struct was declared.
3246 break;
3247 }
John Kessenichebb50532016-05-16 19:22:05 -06003248}
3249
John Kessenich6fccb3c2016-09-19 16:01:41 -06003250bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003251{
John Kessenicheee9d532016-09-19 18:09:30 -06003252 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003253}
3254
John Kessenichd41993d2017-09-10 15:21:05 -06003255// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003256// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3257// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003258bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003259{
John Kessenich6a14f782017-12-04 02:48:10 -07003260 assert(qualifier == glslang::EvqIn ||
3261 qualifier == glslang::EvqOut ||
3262 qualifier == glslang::EvqInOut ||
3263 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003264 return qualifier != glslang::EvqConstReadOnly;
3265}
3266
3267// Is parameter pass-by-original?
3268bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3269 bool implicitThisParam)
3270{
3271 if (implicitThisParam) // implicit this
3272 return true;
3273 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003274 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003275 return paramType.containsOpaque() || // sampler, etc.
3276 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3277}
3278
John Kessenich140f3df2015-06-26 16:58:36 -06003279// Make all the functions, skeletally, without actually visiting their bodies.
3280void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3281{
John Kessenichfad62972017-07-18 02:35:46 -06003282 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
3283 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3284 if (paramPrecision != spv::NoPrecision)
3285 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06003286 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06003287 };
3288
John Kessenich140f3df2015-06-26 16:58:36 -06003289 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3290 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003291 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003292 continue;
3293
3294 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003295 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003296 //
qining25262b32016-05-06 17:25:16 -04003297 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003298 // function. What it is an address of varies:
3299 //
John Kessenich4bf71552016-09-02 11:20:21 -06003300 // - "in" parameters not marked as "const" can be written to without modifying the calling
3301 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003302 //
3303 // - "const in" parameters can just be the r-value, as no writes need occur.
3304 //
John Kessenich4bf71552016-09-02 11:20:21 -06003305 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3306 // 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 -06003307
3308 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003309 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003310 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3311
John Kessenichfad62972017-07-18 02:35:46 -06003312 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3313 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003314
John Kessenichfad62972017-07-18 02:35:46 -06003315 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003316 for (int p = 0; p < (int)parameters.size(); ++p) {
3317 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3318 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003319 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003320 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003321 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003322 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3323 else
John Kessenich4bf71552016-09-02 11:20:21 -06003324 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003325 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003326 paramTypes.push_back(typeId);
3327 }
3328
3329 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003330 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3331 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003332 glslFunction->getName().c_str(), paramTypes,
3333 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003334 if (implicitThis)
3335 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003336
3337 // Track function to emit/call later
3338 functionMap[glslFunction->getName().c_str()] = function;
3339
3340 // Set the parameter id's
3341 for (int p = 0; p < (int)parameters.size(); ++p) {
3342 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3343 // give a name too
3344 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3345 }
3346 }
3347}
3348
3349// Process all the initializers, while skipping the functions and link objects
3350void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3351{
3352 builder.setBuildPoint(shaderEntry->getLastBlock());
3353 for (int i = 0; i < (int)initializers.size(); ++i) {
3354 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3355 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3356
3357 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003358 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003359 initializer->traverse(this);
3360 }
3361 }
3362}
3363
3364// Process all the functions, while skipping initializers.
3365void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3366{
3367 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3368 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003369 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003370 node->traverse(this);
3371 }
3372}
3373
3374void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3375{
qining25262b32016-05-06 17:25:16 -04003376 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003377 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003378 currentFunction = functionMap[node->getName().c_str()];
3379 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003380 builder.setBuildPoint(functionBlock);
3381}
3382
Rex Xu04db3f52015-09-16 11:44:02 +08003383void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003384{
Rex Xufc618912015-09-09 16:42:49 +08003385 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003386
3387 glslang::TSampler sampler = {};
3388 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003389#ifdef AMD_EXTENSIONS
3390 bool f16ShadowCompare = false;
3391#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003392 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003393 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3394 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003395#ifdef AMD_EXTENSIONS
3396 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3397#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003398 }
3399
John Kessenich140f3df2015-06-26 16:58:36 -06003400 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3401 builder.clearAccessChain();
3402 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003403
3404 // Special case l-value operands
3405 bool lvalue = false;
3406 switch (node.getOp()) {
3407 case glslang::EOpImageAtomicAdd:
3408 case glslang::EOpImageAtomicMin:
3409 case glslang::EOpImageAtomicMax:
3410 case glslang::EOpImageAtomicAnd:
3411 case glslang::EOpImageAtomicOr:
3412 case glslang::EOpImageAtomicXor:
3413 case glslang::EOpImageAtomicExchange:
3414 case glslang::EOpImageAtomicCompSwap:
3415 if (i == 0)
3416 lvalue = true;
3417 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003418 case glslang::EOpSparseImageLoad:
3419 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3420 lvalue = true;
3421 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003422#ifdef AMD_EXTENSIONS
3423 case glslang::EOpSparseTexture:
3424 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3425 lvalue = true;
3426 break;
3427 case glslang::EOpSparseTextureClamp:
3428 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3429 lvalue = true;
3430 break;
3431 case glslang::EOpSparseTextureLod:
3432 case glslang::EOpSparseTextureOffset:
3433 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
3434 lvalue = true;
3435 break;
3436#else
Rex Xu48edadf2015-12-31 16:11:41 +08003437 case glslang::EOpSparseTexture:
3438 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3439 lvalue = true;
3440 break;
3441 case glslang::EOpSparseTextureClamp:
3442 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3443 lvalue = true;
3444 break;
3445 case glslang::EOpSparseTextureLod:
3446 case glslang::EOpSparseTextureOffset:
3447 if (i == 3)
3448 lvalue = true;
3449 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003450#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003451 case glslang::EOpSparseTextureFetch:
3452 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3453 lvalue = true;
3454 break;
3455 case glslang::EOpSparseTextureFetchOffset:
3456 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3457 lvalue = true;
3458 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003459#ifdef AMD_EXTENSIONS
3460 case glslang::EOpSparseTextureLodOffset:
3461 case glslang::EOpSparseTextureGrad:
3462 case glslang::EOpSparseTextureOffsetClamp:
3463 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
3464 lvalue = true;
3465 break;
3466 case glslang::EOpSparseTextureGradOffset:
3467 case glslang::EOpSparseTextureGradClamp:
3468 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
3469 lvalue = true;
3470 break;
3471 case glslang::EOpSparseTextureGradOffsetClamp:
3472 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
3473 lvalue = true;
3474 break;
3475#else
Rex Xu48edadf2015-12-31 16:11:41 +08003476 case glslang::EOpSparseTextureLodOffset:
3477 case glslang::EOpSparseTextureGrad:
3478 case glslang::EOpSparseTextureOffsetClamp:
3479 if (i == 4)
3480 lvalue = true;
3481 break;
3482 case glslang::EOpSparseTextureGradOffset:
3483 case glslang::EOpSparseTextureGradClamp:
3484 if (i == 5)
3485 lvalue = true;
3486 break;
3487 case glslang::EOpSparseTextureGradOffsetClamp:
3488 if (i == 6)
3489 lvalue = true;
3490 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003491#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08003492 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003493 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3494 lvalue = true;
3495 break;
3496 case glslang::EOpSparseTextureGatherOffset:
3497 case glslang::EOpSparseTextureGatherOffsets:
3498 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3499 lvalue = true;
3500 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003501#ifdef AMD_EXTENSIONS
3502 case glslang::EOpSparseTextureGatherLod:
3503 if (i == 3)
3504 lvalue = true;
3505 break;
3506 case glslang::EOpSparseTextureGatherLodOffset:
3507 case glslang::EOpSparseTextureGatherLodOffsets:
3508 if (i == 4)
3509 lvalue = true;
3510 break;
Rex Xu129799a2017-07-05 17:23:28 +08003511 case glslang::EOpSparseImageLoadLod:
3512 if (i == 3)
3513 lvalue = true;
3514 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003515#endif
Rex Xufc618912015-09-09 16:42:49 +08003516 default:
3517 break;
3518 }
3519
Rex Xu6b86d492015-09-16 17:48:22 +08003520 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003521 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003522 else
John Kessenich32cfd492016-02-02 12:37:46 -07003523 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003524 }
3525}
3526
John Kessenichfc51d282015-08-19 13:34:18 -06003527void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003528{
John Kessenichfc51d282015-08-19 13:34:18 -06003529 builder.clearAccessChain();
3530 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003531 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003532}
John Kessenich140f3df2015-06-26 16:58:36 -06003533
John Kessenichfc51d282015-08-19 13:34:18 -06003534spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3535{
John Kesseniche485c7a2017-05-31 18:50:53 -06003536 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003537 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003538
3539 builder.setLine(node->getLoc().line);
3540
John Kessenichfc51d282015-08-19 13:34:18 -06003541 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003542 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3543 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08003544#ifdef AMD_EXTENSIONS
3545 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
3546 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
3547 : false;
3548#endif
3549
John Kessenichfc51d282015-08-19 13:34:18 -06003550 std::vector<spv::Id> arguments;
3551 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003552 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003553 else
3554 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003555 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003556
3557 spv::Builder::TextureParameters params = { };
3558 params.sampler = arguments[0];
3559
Rex Xu04db3f52015-09-16 11:44:02 +08003560 glslang::TCrackedTextureOp cracked;
3561 node->crackTexture(sampler, cracked);
3562
amhagan05506bb2017-06-13 16:53:02 -04003563 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003564
John Kessenichfc51d282015-08-19 13:34:18 -06003565 // Check for queries
3566 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003567 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3568 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003569 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003570
John Kessenichfc51d282015-08-19 13:34:18 -06003571 switch (node->getOp()) {
3572 case glslang::EOpImageQuerySize:
3573 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003574 if (arguments.size() > 1) {
3575 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003576 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003577 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003578 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003579 case glslang::EOpImageQuerySamples:
3580 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003581 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003582 case glslang::EOpTextureQueryLod:
3583 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003584 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003585 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003586 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003587 case glslang::EOpSparseTexelsResident:
3588 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003589 default:
3590 assert(0);
3591 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003592 }
John Kessenich140f3df2015-06-26 16:58:36 -06003593 }
3594
LoopDawg4425f242018-02-18 11:40:01 -07003595 int components = node->getType().getVectorSize();
3596
3597 if (node->getOp() == glslang::EOpTextureFetch) {
3598 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3599 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3600 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3601 // here around e.g. which ones return scalars or other types.
3602 components = 4;
3603 }
3604
3605 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3606
3607 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3608
Rex Xufc618912015-09-09 16:42:49 +08003609 // Check for image functions other than queries
3610 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003611 std::vector<spv::Id> operands;
3612 auto opIt = arguments.begin();
3613 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003614
3615 // Handle subpass operations
3616 // TODO: GLSL should change to have the "MS" only on the type rather than the
3617 // built-in function.
3618 if (cracked.subpass) {
3619 // add on the (0,0) coordinate
3620 spv::Id zero = builder.makeIntConstant(0);
3621 std::vector<spv::Id> comps;
3622 comps.push_back(zero);
3623 comps.push_back(zero);
3624 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3625 if (sampler.ms) {
3626 operands.push_back(spv::ImageOperandsSampleMask);
3627 operands.push_back(*(opIt++));
3628 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003629 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3630 builder.setPrecision(result, precision);
3631 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003632 }
3633
John Kessenich56bab042015-09-16 10:54:31 -06003634 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003635#ifdef AMD_EXTENSIONS
3636 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3637#else
John Kessenich56bab042015-09-16 10:54:31 -06003638 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003639#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003640 if (sampler.ms) {
3641 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003642 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003643#ifdef AMD_EXTENSIONS
3644 } else if (cracked.lod) {
3645 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3646 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3647
3648 operands.push_back(spv::ImageOperandsLodMask);
3649 operands.push_back(*opIt);
3650#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003651 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003652 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3653 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003654
St0fFa1184dd2018-04-09 21:08:14 +02003655 std::vector<spv::Id> result( 1, builder.createOp(spv::OpImageRead, resultType(), operands) );
LoopDawg4425f242018-02-18 11:40:01 -07003656 builder.setPrecision(result[0], precision);
3657
3658 // If needed, add a conversion constructor to the proper size.
3659 if (components != node->getType().getVectorSize())
3660 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3661
3662 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08003663#ifdef AMD_EXTENSIONS
3664 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3665#else
John Kessenich56bab042015-09-16 10:54:31 -06003666 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003667#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003668 if (sampler.ms) {
3669 operands.push_back(*(opIt + 1));
3670 operands.push_back(spv::ImageOperandsSampleMask);
3671 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003672#ifdef AMD_EXTENSIONS
3673 } else if (cracked.lod) {
3674 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3675 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3676
3677 operands.push_back(*(opIt + 1));
3678 operands.push_back(spv::ImageOperandsLodMask);
3679 operands.push_back(*opIt);
3680#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003681 } else
3682 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003683 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003684 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3685 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003686 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003687#ifdef AMD_EXTENSIONS
3688 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3689#else
Rex Xu5eafa472016-02-19 22:24:03 +08003690 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003691#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003692 builder.addCapability(spv::CapabilitySparseResidency);
3693 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3694 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3695
3696 if (sampler.ms) {
3697 operands.push_back(spv::ImageOperandsSampleMask);
3698 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003699#ifdef AMD_EXTENSIONS
3700 } else if (cracked.lod) {
3701 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3702 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3703
3704 operands.push_back(spv::ImageOperandsLodMask);
3705 operands.push_back(*opIt++);
3706#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003707 }
3708
3709 // Create the return type that was a special structure
3710 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003711 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003712 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3713 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3714
3715 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3716
3717 // Decode the return type
3718 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3719 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003720 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003721 // Process image atomic operations
3722
3723 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3724 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003725 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003726
John Kessenich8c8505c2016-07-26 12:50:38 -06003727 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003728 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003729
3730 std::vector<spv::Id> operands;
3731 operands.push_back(pointer);
3732 for (; opIt != arguments.end(); ++opIt)
3733 operands.push_back(*opIt);
3734
John Kessenich8c8505c2016-07-26 12:50:38 -06003735 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003736 }
3737 }
3738
amhagan05506bb2017-06-13 16:53:02 -04003739#ifdef AMD_EXTENSIONS
3740 // Check for fragment mask functions other than queries
3741 if (cracked.fragMask) {
3742 assert(sampler.ms);
3743
3744 auto opIt = arguments.begin();
3745 std::vector<spv::Id> operands;
3746
3747 // Extract the image if necessary
3748 if (builder.isSampledImage(params.sampler))
3749 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3750
3751 operands.push_back(params.sampler);
3752 ++opIt;
3753
3754 if (sampler.isSubpass()) {
3755 // add on the (0,0) coordinate
3756 spv::Id zero = builder.makeIntConstant(0);
3757 std::vector<spv::Id> comps;
3758 comps.push_back(zero);
3759 comps.push_back(zero);
3760 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3761 }
3762
3763 for (; opIt != arguments.end(); ++opIt)
3764 operands.push_back(*opIt);
3765
3766 spv::Op fragMaskOp = spv::OpNop;
3767 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3768 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3769 else if (node->getOp() == glslang::EOpFragmentFetch)
3770 fragMaskOp = spv::OpFragmentFetchAMD;
3771
3772 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3773 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3774 return builder.createOp(fragMaskOp, resultType(), operands);
3775 }
3776#endif
3777
Rex Xufc618912015-09-09 16:42:49 +08003778 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003779 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003780 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3781
John Kessenichfc51d282015-08-19 13:34:18 -06003782 // check for bias argument
3783 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003784#ifdef AMD_EXTENSIONS
3785 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3786#else
Rex Xu71519fe2015-11-11 15:35:47 +08003787 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003788#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003789 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003790#ifdef AMD_EXTENSIONS
3791 if (cracked.gather)
3792 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08003793
3794 if (f16ShadowCompare)
3795 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003796#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003797 if (cracked.offset)
3798 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003799#ifdef AMD_EXTENSIONS
3800 else if (cracked.offsets)
3801 ++nonBiasArgCount;
3802#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003803 if (cracked.grad)
3804 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003805 if (cracked.lodClamp)
3806 ++nonBiasArgCount;
3807 if (sparse)
3808 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003809
3810 if ((int)arguments.size() > nonBiasArgCount)
3811 bias = true;
3812 }
3813
John Kessenicha5c33d62016-06-02 23:45:21 -06003814 // See if the sampler param should really be just the SPV image part
3815 if (cracked.fetch) {
3816 // a fetch needs to have the image extracted first
3817 if (builder.isSampledImage(params.sampler))
3818 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3819 }
3820
Rex Xu225e0fc2016-11-17 17:47:59 +08003821#ifdef AMD_EXTENSIONS
3822 if (cracked.gather) {
3823 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3824 if (bias || cracked.lod ||
3825 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3826 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003827 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003828 }
3829 }
3830#endif
3831
John Kessenichfc51d282015-08-19 13:34:18 -06003832 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003833
John Kessenichfc51d282015-08-19 13:34:18 -06003834 params.coords = arguments[1];
3835 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003836 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003837
3838 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08003839#ifdef AMD_EXTENSIONS
3840 if (cubeCompare || f16ShadowCompare) {
3841#else
Rex Xu48edadf2015-12-31 16:11:41 +08003842 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08003843#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003844 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003845 ++extraArgs;
3846 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003847 params.Dref = arguments[2];
3848 ++extraArgs;
3849 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003850 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003851 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003852 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003853 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003854 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003855 dRefComp = builder.getNumComponents(params.coords) - 1;
3856 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003857 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3858 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003859
3860 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003861 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003862 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003863 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003864 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3865 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3866 noImplicitLod = true;
3867 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003868
3869 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003870 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003871 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003872 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003873 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003874
3875 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003876 if (cracked.grad) {
3877 params.gradX = arguments[2 + extraArgs];
3878 params.gradY = arguments[3 + extraArgs];
3879 extraArgs += 2;
3880 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003881
3882 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003883 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003884 params.offset = arguments[2 + extraArgs];
3885 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003886 } else if (cracked.offsets) {
3887 params.offsets = arguments[2 + extraArgs];
3888 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003889 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003890
3891 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003892 if (cracked.lodClamp) {
3893 params.lodClamp = arguments[2 + extraArgs];
3894 ++extraArgs;
3895 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003896
3897 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003898 if (sparse) {
3899 params.texelOut = arguments[2 + extraArgs];
3900 ++extraArgs;
3901 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003902
John Kessenich76d4dfc2016-06-16 12:43:23 -06003903 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003904 if (cracked.gather && ! sampler.shadow) {
3905 // default component is 0, if missing, otherwise an argument
3906 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003907 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003908 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003909 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003910 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003911 }
3912
3913 // bias
3914 if (bias) {
3915 params.bias = arguments[2 + extraArgs];
3916 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003917 }
John Kessenichfc51d282015-08-19 13:34:18 -06003918
John Kessenich65336482016-06-16 14:06:26 -06003919 // projective component (might not to move)
3920 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3921 // are divided by the last component of P."
3922 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3923 // unused components will appear after all used components."
3924 if (cracked.proj) {
3925 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3926 int projTargetComp;
3927 switch (sampler.dim) {
3928 case glslang::Esd1D: projTargetComp = 1; break;
3929 case glslang::Esd2D: projTargetComp = 2; break;
3930 case glslang::EsdRect: projTargetComp = 2; break;
3931 default: projTargetComp = projSourceComp; break;
3932 }
3933 // copy the projective coordinate if we have to
3934 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003935 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003936 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3937 projSourceComp);
3938 params.coords = builder.createCompositeInsert(projComp, params.coords,
3939 builder.getTypeId(params.coords), projTargetComp);
3940 }
3941 }
3942
St0fFa1184dd2018-04-09 21:08:14 +02003943 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07003944 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02003945 );
LoopDawg4425f242018-02-18 11:40:01 -07003946
3947 if (components != node->getType().getVectorSize())
3948 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3949
3950 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06003951}
3952
3953spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3954{
3955 // Grab the function's pointer from the previously created function
3956 spv::Function* function = functionMap[node->getName().c_str()];
3957 if (! function)
3958 return 0;
3959
3960 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3961 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3962
3963 // See comments in makeFunctions() for details about the semantics for parameter passing.
3964 //
3965 // These imply we need a four step process:
3966 // 1. Evaluate the arguments
3967 // 2. Allocate and make copies of in, out, and inout arguments
3968 // 3. Make the call
3969 // 4. Copy back the results
3970
John Kessenichd3ed90b2018-05-04 11:43:03 -06003971 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06003972 std::vector<spv::Builder::AccessChain> lValues;
3973 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003974 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003975 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06003976 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003977 // build l-value
3978 builder.clearAccessChain();
3979 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06003980 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06003981 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07003982 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003983 // save l-value
3984 lValues.push_back(builder.getAccessChain());
3985 } else {
3986 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003987 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003988 }
3989 }
3990
3991 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3992 // copy the original into that space.
3993 //
3994 // Also, build up the list of actual arguments to pass in for the call
3995 int lValueCount = 0;
3996 int rValueCount = 0;
3997 std::vector<spv::Id> spvArgs;
3998 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
3999 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004000 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004001 builder.setAccessChain(lValues[lValueCount]);
4002 arg = builder.accessChainGetLValue();
4003 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004004 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004005 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004006 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004007 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4008 // need to copy the input into output space
4009 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004010 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004011 builder.clearAccessChain();
4012 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004013 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004014 }
4015 ++lValueCount;
4016 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004017 // process r-value, which involves a copy for a type mismatch
4018 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4019 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4020 builder.clearAccessChain();
4021 builder.setAccessChainLValue(argCopy);
4022 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4023 arg = builder.createLoad(argCopy);
4024 } else
4025 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004026 ++rValueCount;
4027 }
4028 spvArgs.push_back(arg);
4029 }
4030
4031 // 3. Make the call.
4032 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004033 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004034
4035 // 4. Copy back out an "out" arguments.
4036 lValueCount = 0;
4037 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004038 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004039 ++lValueCount;
4040 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004041 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4042 spv::Id copy = builder.createLoad(spvArgs[a]);
4043 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004044 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004045 }
4046 ++lValueCount;
4047 }
4048 }
4049
4050 return result;
4051}
4052
4053// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004054spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004055 spv::Id typeId, spv::Id left, spv::Id right,
4056 glslang::TBasicType typeProxy, bool reduceComparison)
4057{
John Kessenich66011cb2018-03-06 16:12:04 -07004058 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4059 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004060 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004061
4062 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004063 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004064 bool comparison = false;
4065
4066 switch (op) {
4067 case glslang::EOpAdd:
4068 case glslang::EOpAddAssign:
4069 if (isFloat)
4070 binOp = spv::OpFAdd;
4071 else
4072 binOp = spv::OpIAdd;
4073 break;
4074 case glslang::EOpSub:
4075 case glslang::EOpSubAssign:
4076 if (isFloat)
4077 binOp = spv::OpFSub;
4078 else
4079 binOp = spv::OpISub;
4080 break;
4081 case glslang::EOpMul:
4082 case glslang::EOpMulAssign:
4083 if (isFloat)
4084 binOp = spv::OpFMul;
4085 else
4086 binOp = spv::OpIMul;
4087 break;
4088 case glslang::EOpVectorTimesScalar:
4089 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004090 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004091 if (builder.isVector(right))
4092 std::swap(left, right);
4093 assert(builder.isScalar(right));
4094 needMatchingVectors = false;
4095 binOp = spv::OpVectorTimesScalar;
4096 } else
4097 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004098 break;
4099 case glslang::EOpVectorTimesMatrix:
4100 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004101 binOp = spv::OpVectorTimesMatrix;
4102 break;
4103 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004104 binOp = spv::OpMatrixTimesVector;
4105 break;
4106 case glslang::EOpMatrixTimesScalar:
4107 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004108 binOp = spv::OpMatrixTimesScalar;
4109 break;
4110 case glslang::EOpMatrixTimesMatrix:
4111 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004112 binOp = spv::OpMatrixTimesMatrix;
4113 break;
4114 case glslang::EOpOuterProduct:
4115 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004116 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004117 break;
4118
4119 case glslang::EOpDiv:
4120 case glslang::EOpDivAssign:
4121 if (isFloat)
4122 binOp = spv::OpFDiv;
4123 else if (isUnsigned)
4124 binOp = spv::OpUDiv;
4125 else
4126 binOp = spv::OpSDiv;
4127 break;
4128 case glslang::EOpMod:
4129 case glslang::EOpModAssign:
4130 if (isFloat)
4131 binOp = spv::OpFMod;
4132 else if (isUnsigned)
4133 binOp = spv::OpUMod;
4134 else
4135 binOp = spv::OpSMod;
4136 break;
4137 case glslang::EOpRightShift:
4138 case glslang::EOpRightShiftAssign:
4139 if (isUnsigned)
4140 binOp = spv::OpShiftRightLogical;
4141 else
4142 binOp = spv::OpShiftRightArithmetic;
4143 break;
4144 case glslang::EOpLeftShift:
4145 case glslang::EOpLeftShiftAssign:
4146 binOp = spv::OpShiftLeftLogical;
4147 break;
4148 case glslang::EOpAnd:
4149 case glslang::EOpAndAssign:
4150 binOp = spv::OpBitwiseAnd;
4151 break;
4152 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004153 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004154 binOp = spv::OpLogicalAnd;
4155 break;
4156 case glslang::EOpInclusiveOr:
4157 case glslang::EOpInclusiveOrAssign:
4158 binOp = spv::OpBitwiseOr;
4159 break;
4160 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004161 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004162 binOp = spv::OpLogicalOr;
4163 break;
4164 case glslang::EOpExclusiveOr:
4165 case glslang::EOpExclusiveOrAssign:
4166 binOp = spv::OpBitwiseXor;
4167 break;
4168 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004169 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004170 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004171 break;
4172
4173 case glslang::EOpLessThan:
4174 case glslang::EOpGreaterThan:
4175 case glslang::EOpLessThanEqual:
4176 case glslang::EOpGreaterThanEqual:
4177 case glslang::EOpEqual:
4178 case glslang::EOpNotEqual:
4179 case glslang::EOpVectorEqual:
4180 case glslang::EOpVectorNotEqual:
4181 comparison = true;
4182 break;
4183 default:
4184 break;
4185 }
4186
John Kessenich7c1aa102015-10-15 13:29:11 -06004187 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004188 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004189 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07004190 if (builder.isMatrix(left) || builder.isMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004191 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004192
4193 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004194 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004195 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004196
qining25262b32016-05-06 17:25:16 -04004197 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004198 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004199 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004200 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004201 }
4202
4203 if (! comparison)
4204 return 0;
4205
John Kessenich7c1aa102015-10-15 13:29:11 -06004206 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004207
John Kessenich4583b612016-08-07 19:14:22 -06004208 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004209 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4210 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004211 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004212 return result;
4213 }
John Kessenich140f3df2015-06-26 16:58:36 -06004214
4215 switch (op) {
4216 case glslang::EOpLessThan:
4217 if (isFloat)
4218 binOp = spv::OpFOrdLessThan;
4219 else if (isUnsigned)
4220 binOp = spv::OpULessThan;
4221 else
4222 binOp = spv::OpSLessThan;
4223 break;
4224 case glslang::EOpGreaterThan:
4225 if (isFloat)
4226 binOp = spv::OpFOrdGreaterThan;
4227 else if (isUnsigned)
4228 binOp = spv::OpUGreaterThan;
4229 else
4230 binOp = spv::OpSGreaterThan;
4231 break;
4232 case glslang::EOpLessThanEqual:
4233 if (isFloat)
4234 binOp = spv::OpFOrdLessThanEqual;
4235 else if (isUnsigned)
4236 binOp = spv::OpULessThanEqual;
4237 else
4238 binOp = spv::OpSLessThanEqual;
4239 break;
4240 case glslang::EOpGreaterThanEqual:
4241 if (isFloat)
4242 binOp = spv::OpFOrdGreaterThanEqual;
4243 else if (isUnsigned)
4244 binOp = spv::OpUGreaterThanEqual;
4245 else
4246 binOp = spv::OpSGreaterThanEqual;
4247 break;
4248 case glslang::EOpEqual:
4249 case glslang::EOpVectorEqual:
4250 if (isFloat)
4251 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004252 else if (isBool)
4253 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004254 else
4255 binOp = spv::OpIEqual;
4256 break;
4257 case glslang::EOpNotEqual:
4258 case glslang::EOpVectorNotEqual:
4259 if (isFloat)
4260 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004261 else if (isBool)
4262 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004263 else
4264 binOp = spv::OpINotEqual;
4265 break;
4266 default:
4267 break;
4268 }
4269
qining25262b32016-05-06 17:25:16 -04004270 if (binOp != spv::OpNop) {
4271 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004272 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004273 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004274 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004275 }
John Kessenich140f3df2015-06-26 16:58:36 -06004276
4277 return 0;
4278}
4279
John Kessenich04bb8a02015-12-12 12:28:14 -07004280//
4281// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
4282// These can be any of:
4283//
4284// matrix * scalar
4285// scalar * matrix
4286// matrix * matrix linear algebraic
4287// matrix * vector
4288// vector * matrix
4289// matrix * matrix componentwise
4290// matrix op matrix op in {+, -, /}
4291// matrix op scalar op in {+, -, /}
4292// scalar op matrix op in {+, -, /}
4293//
John Kessenichead86222018-03-28 18:01:20 -06004294spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4295 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07004296{
4297 bool firstClass = true;
4298
4299 // First, handle first-class matrix operations (* and matrix/scalar)
4300 switch (op) {
4301 case spv::OpFDiv:
4302 if (builder.isMatrix(left) && builder.isScalar(right)) {
4303 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01004304 spv::Id resultType = builder.getTypeId(right);
4305 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07004306 op = spv::OpMatrixTimesScalar;
4307 } else
4308 firstClass = false;
4309 break;
4310 case spv::OpMatrixTimesScalar:
4311 if (builder.isMatrix(right))
4312 std::swap(left, right);
4313 assert(builder.isScalar(right));
4314 break;
4315 case spv::OpVectorTimesMatrix:
4316 assert(builder.isVector(left));
4317 assert(builder.isMatrix(right));
4318 break;
4319 case spv::OpMatrixTimesVector:
4320 assert(builder.isMatrix(left));
4321 assert(builder.isVector(right));
4322 break;
4323 case spv::OpMatrixTimesMatrix:
4324 assert(builder.isMatrix(left));
4325 assert(builder.isMatrix(right));
4326 break;
4327 default:
4328 firstClass = false;
4329 break;
4330 }
4331
qining25262b32016-05-06 17:25:16 -04004332 if (firstClass) {
4333 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004334 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004335 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004336 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004337 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004338
LoopDawg592860c2016-06-09 08:57:35 -06004339 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004340 // The result type of all of them is the same type as the (a) matrix operand.
4341 // The algorithm is to:
4342 // - break the matrix(es) into vectors
4343 // - smear any scalar to a vector
4344 // - do vector operations
4345 // - make a matrix out the vector results
4346 switch (op) {
4347 case spv::OpFAdd:
4348 case spv::OpFSub:
4349 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004350 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004351 case spv::OpFMul:
4352 {
4353 // one time set up...
4354 bool leftMat = builder.isMatrix(left);
4355 bool rightMat = builder.isMatrix(right);
4356 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4357 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4358 spv::Id scalarType = builder.getScalarTypeId(typeId);
4359 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4360 std::vector<spv::Id> results;
4361 spv::Id smearVec = spv::NoResult;
4362 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06004363 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004364 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06004365 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004366
4367 // do each vector op
4368 for (unsigned int c = 0; c < numCols; ++c) {
4369 std::vector<unsigned int> indexes;
4370 indexes.push_back(c);
4371 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4372 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004373 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06004374 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004375 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004376 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004377 }
4378
4379 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004380 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004381 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004382 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07004383 }
4384 default:
4385 assert(0);
4386 return spv::NoResult;
4387 }
4388}
4389
John Kessenichead86222018-03-28 18:01:20 -06004390spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
4391 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004392{
4393 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004394 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004395 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07004396 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4397 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004398
4399 switch (op) {
4400 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004401 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004402 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004403 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06004404 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004405 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004406 unaryOp = spv::OpSNegate;
4407 break;
4408
4409 case glslang::EOpLogicalNot:
4410 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004411 unaryOp = spv::OpLogicalNot;
4412 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004413 case glslang::EOpBitwiseNot:
4414 unaryOp = spv::OpNot;
4415 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004416
John Kessenich140f3df2015-06-26 16:58:36 -06004417 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004418 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004419 break;
4420 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004421 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004422 break;
4423 case glslang::EOpTranspose:
4424 unaryOp = spv::OpTranspose;
4425 break;
4426
4427 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004428 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004429 break;
4430 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004431 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004432 break;
4433 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004434 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004435 break;
4436 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004437 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004438 break;
4439 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004440 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004441 break;
4442 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004443 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004444 break;
4445 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004446 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004447 break;
4448 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004449 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004450 break;
4451
4452 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004453 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004454 break;
4455 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004456 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004457 break;
4458 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004459 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004460 break;
4461 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004462 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004463 break;
4464 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004465 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004466 break;
4467 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004468 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004469 break;
4470
4471 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004472 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004473 break;
4474 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004475 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004476 break;
4477
4478 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004479 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004480 break;
4481 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004482 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004483 break;
4484 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004485 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004486 break;
4487 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004488 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004489 break;
4490 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004491 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004492 break;
4493 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004494 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004495 break;
4496
4497 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004498 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004499 break;
4500 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004501 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004502 break;
4503 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004504 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004505 break;
4506 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004507 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004508 break;
4509 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004510 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004511 break;
4512 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004513 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004514 break;
4515
4516 case glslang::EOpIsNan:
4517 unaryOp = spv::OpIsNan;
4518 break;
4519 case glslang::EOpIsInf:
4520 unaryOp = spv::OpIsInf;
4521 break;
LoopDawg592860c2016-06-09 08:57:35 -06004522 case glslang::EOpIsFinite:
4523 unaryOp = spv::OpIsFinite;
4524 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004525
Rex Xucbc426e2015-12-15 16:03:10 +08004526 case glslang::EOpFloatBitsToInt:
4527 case glslang::EOpFloatBitsToUint:
4528 case glslang::EOpIntBitsToFloat:
4529 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004530 case glslang::EOpDoubleBitsToInt64:
4531 case glslang::EOpDoubleBitsToUint64:
4532 case glslang::EOpInt64BitsToDouble:
4533 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004534 case glslang::EOpFloat16BitsToInt16:
4535 case glslang::EOpFloat16BitsToUint16:
4536 case glslang::EOpInt16BitsToFloat16:
4537 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08004538 unaryOp = spv::OpBitcast;
4539 break;
4540
John Kessenich140f3df2015-06-26 16:58:36 -06004541 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004542 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004543 break;
4544 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004545 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004546 break;
4547 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004548 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004549 break;
4550 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004551 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004552 break;
4553 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004554 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004555 break;
4556 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004557 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004558 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004559 case glslang::EOpPackSnorm4x8:
4560 libCall = spv::GLSLstd450PackSnorm4x8;
4561 break;
4562 case glslang::EOpUnpackSnorm4x8:
4563 libCall = spv::GLSLstd450UnpackSnorm4x8;
4564 break;
4565 case glslang::EOpPackUnorm4x8:
4566 libCall = spv::GLSLstd450PackUnorm4x8;
4567 break;
4568 case glslang::EOpUnpackUnorm4x8:
4569 libCall = spv::GLSLstd450UnpackUnorm4x8;
4570 break;
4571 case glslang::EOpPackDouble2x32:
4572 libCall = spv::GLSLstd450PackDouble2x32;
4573 break;
4574 case glslang::EOpUnpackDouble2x32:
4575 libCall = spv::GLSLstd450UnpackDouble2x32;
4576 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004577
Rex Xu8ff43de2016-04-22 16:51:45 +08004578 case glslang::EOpPackInt2x32:
4579 case glslang::EOpUnpackInt2x32:
4580 case glslang::EOpPackUint2x32:
4581 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07004582 case glslang::EOpPack16:
4583 case glslang::EOpPack32:
4584 case glslang::EOpPack64:
4585 case glslang::EOpUnpack32:
4586 case glslang::EOpUnpack16:
4587 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08004588 case glslang::EOpPackInt2x16:
4589 case glslang::EOpUnpackInt2x16:
4590 case glslang::EOpPackUint2x16:
4591 case glslang::EOpUnpackUint2x16:
4592 case glslang::EOpPackInt4x16:
4593 case glslang::EOpUnpackInt4x16:
4594 case glslang::EOpPackUint4x16:
4595 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004596 case glslang::EOpPackFloat2x16:
4597 case glslang::EOpUnpackFloat2x16:
4598 unaryOp = spv::OpBitcast;
4599 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004600
John Kessenich140f3df2015-06-26 16:58:36 -06004601 case glslang::EOpDPdx:
4602 unaryOp = spv::OpDPdx;
4603 break;
4604 case glslang::EOpDPdy:
4605 unaryOp = spv::OpDPdy;
4606 break;
4607 case glslang::EOpFwidth:
4608 unaryOp = spv::OpFwidth;
4609 break;
4610 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004611 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004612 unaryOp = spv::OpDPdxFine;
4613 break;
4614 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004615 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004616 unaryOp = spv::OpDPdyFine;
4617 break;
4618 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004619 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004620 unaryOp = spv::OpFwidthFine;
4621 break;
4622 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004623 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004624 unaryOp = spv::OpDPdxCoarse;
4625 break;
4626 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004627 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004628 unaryOp = spv::OpDPdyCoarse;
4629 break;
4630 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004631 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004632 unaryOp = spv::OpFwidthCoarse;
4633 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004634 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08004635#ifdef AMD_EXTENSIONS
4636 if (typeProxy == glslang::EbtFloat16)
4637 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
4638#endif
John Kessenich92187592016-02-01 13:45:25 -07004639 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004640 libCall = spv::GLSLstd450InterpolateAtCentroid;
4641 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004642 case glslang::EOpAny:
4643 unaryOp = spv::OpAny;
4644 break;
4645 case glslang::EOpAll:
4646 unaryOp = spv::OpAll;
4647 break;
4648
4649 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004650 if (isFloat)
4651 libCall = spv::GLSLstd450FAbs;
4652 else
4653 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004654 break;
4655 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004656 if (isFloat)
4657 libCall = spv::GLSLstd450FSign;
4658 else
4659 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004660 break;
4661
John Kessenichfc51d282015-08-19 13:34:18 -06004662 case glslang::EOpAtomicCounterIncrement:
4663 case glslang::EOpAtomicCounterDecrement:
4664 case glslang::EOpAtomicCounter:
4665 {
4666 // Handle all of the atomics in one place, in createAtomicOperation()
4667 std::vector<spv::Id> operands;
4668 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06004669 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004670 }
4671
John Kessenichfc51d282015-08-19 13:34:18 -06004672 case glslang::EOpBitFieldReverse:
4673 unaryOp = spv::OpBitReverse;
4674 break;
4675 case glslang::EOpBitCount:
4676 unaryOp = spv::OpBitCount;
4677 break;
4678 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004679 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004680 break;
4681 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004682 if (isUnsigned)
4683 libCall = spv::GLSLstd450FindUMsb;
4684 else
4685 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004686 break;
4687
Rex Xu574ab042016-04-14 16:53:07 +08004688 case glslang::EOpBallot:
4689 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004690 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004691 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004692 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004693#ifdef AMD_EXTENSIONS
4694 case glslang::EOpMinInvocations:
4695 case glslang::EOpMaxInvocations:
4696 case glslang::EOpAddInvocations:
4697 case glslang::EOpMinInvocationsNonUniform:
4698 case glslang::EOpMaxInvocationsNonUniform:
4699 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004700 case glslang::EOpMinInvocationsInclusiveScan:
4701 case glslang::EOpMaxInvocationsInclusiveScan:
4702 case glslang::EOpAddInvocationsInclusiveScan:
4703 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4704 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4705 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4706 case glslang::EOpMinInvocationsExclusiveScan:
4707 case glslang::EOpMaxInvocationsExclusiveScan:
4708 case glslang::EOpAddInvocationsExclusiveScan:
4709 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4710 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4711 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004712#endif
Rex Xu51596642016-09-21 18:56:12 +08004713 {
4714 std::vector<spv::Id> operands;
4715 operands.push_back(operand);
4716 return createInvocationsOperation(op, typeId, operands, typeProxy);
4717 }
John Kessenich66011cb2018-03-06 16:12:04 -07004718 case glslang::EOpSubgroupAll:
4719 case glslang::EOpSubgroupAny:
4720 case glslang::EOpSubgroupAllEqual:
4721 case glslang::EOpSubgroupBroadcastFirst:
4722 case glslang::EOpSubgroupBallot:
4723 case glslang::EOpSubgroupInverseBallot:
4724 case glslang::EOpSubgroupBallotBitCount:
4725 case glslang::EOpSubgroupBallotInclusiveBitCount:
4726 case glslang::EOpSubgroupBallotExclusiveBitCount:
4727 case glslang::EOpSubgroupBallotFindLSB:
4728 case glslang::EOpSubgroupBallotFindMSB:
4729 case glslang::EOpSubgroupAdd:
4730 case glslang::EOpSubgroupMul:
4731 case glslang::EOpSubgroupMin:
4732 case glslang::EOpSubgroupMax:
4733 case glslang::EOpSubgroupAnd:
4734 case glslang::EOpSubgroupOr:
4735 case glslang::EOpSubgroupXor:
4736 case glslang::EOpSubgroupInclusiveAdd:
4737 case glslang::EOpSubgroupInclusiveMul:
4738 case glslang::EOpSubgroupInclusiveMin:
4739 case glslang::EOpSubgroupInclusiveMax:
4740 case glslang::EOpSubgroupInclusiveAnd:
4741 case glslang::EOpSubgroupInclusiveOr:
4742 case glslang::EOpSubgroupInclusiveXor:
4743 case glslang::EOpSubgroupExclusiveAdd:
4744 case glslang::EOpSubgroupExclusiveMul:
4745 case glslang::EOpSubgroupExclusiveMin:
4746 case glslang::EOpSubgroupExclusiveMax:
4747 case glslang::EOpSubgroupExclusiveAnd:
4748 case glslang::EOpSubgroupExclusiveOr:
4749 case glslang::EOpSubgroupExclusiveXor:
4750 case glslang::EOpSubgroupQuadSwapHorizontal:
4751 case glslang::EOpSubgroupQuadSwapVertical:
4752 case glslang::EOpSubgroupQuadSwapDiagonal: {
4753 std::vector<spv::Id> operands;
4754 operands.push_back(operand);
4755 return createSubgroupOperation(op, typeId, operands, typeProxy);
4756 }
Rex Xu9d93a232016-05-05 12:30:44 +08004757#ifdef AMD_EXTENSIONS
4758 case glslang::EOpMbcnt:
4759 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4760 libCall = spv::MbcntAMD;
4761 break;
4762
4763 case glslang::EOpCubeFaceIndex:
4764 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4765 libCall = spv::CubeFaceIndexAMD;
4766 break;
4767
4768 case glslang::EOpCubeFaceCoord:
4769 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4770 libCall = spv::CubeFaceCoordAMD;
4771 break;
4772#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05004773#ifdef NV_EXTENSIONS
4774 case glslang::EOpSubgroupPartition:
4775 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
4776 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
4777 unaryOp = spv::OpGroupNonUniformPartitionNV;
4778 break;
4779#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004780 default:
4781 return 0;
4782 }
4783
4784 spv::Id id;
4785 if (libCall >= 0) {
4786 std::vector<spv::Id> args;
4787 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004788 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004789 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004790 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004791 }
John Kessenich140f3df2015-06-26 16:58:36 -06004792
John Kessenichead86222018-03-28 18:01:20 -06004793 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004794 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004795 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004796}
4797
John Kessenich7a53f762016-01-20 11:19:27 -07004798// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06004799spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4800 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07004801{
4802 // Handle unary operations vector by vector.
4803 // The result type is the same type as the original type.
4804 // The algorithm is to:
4805 // - break the matrix into vectors
4806 // - apply the operation to each vector
4807 // - make a matrix out the vector results
4808
4809 // get the types sorted out
4810 int numCols = builder.getNumColumns(operand);
4811 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004812 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4813 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004814 std::vector<spv::Id> results;
4815
4816 // do each vector op
4817 for (int c = 0; c < numCols; ++c) {
4818 std::vector<unsigned int> indexes;
4819 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004820 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4821 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06004822 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004823 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004824 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004825 }
4826
4827 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004828 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004829 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004830 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07004831}
4832
John Kessenichad7645f2018-06-04 19:11:25 -06004833// For converting integers where both the bitwidth and the signedness could
4834// change, but only do the width change here. The caller is still responsible
4835// for the signedness conversion.
4836spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07004837{
John Kessenichad7645f2018-06-04 19:11:25 -06004838 // Get the result type width, based on the type to convert to.
4839 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07004840 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06004841 case glslang::EOpConvInt16ToUint8:
4842 case glslang::EOpConvIntToUint8:
4843 case glslang::EOpConvInt64ToUint8:
4844 case glslang::EOpConvUint16ToInt8:
4845 case glslang::EOpConvUintToInt8:
4846 case glslang::EOpConvUint64ToInt8:
4847 width = 8;
4848 break;
John Kessenich66011cb2018-03-06 16:12:04 -07004849 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06004850 case glslang::EOpConvIntToUint16:
4851 case glslang::EOpConvInt64ToUint16:
4852 case glslang::EOpConvUint8ToInt16:
4853 case glslang::EOpConvUintToInt16:
4854 case glslang::EOpConvUint64ToInt16:
4855 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07004856 break;
4857 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06004858 case glslang::EOpConvInt16ToUint:
4859 case glslang::EOpConvInt64ToUint:
4860 case glslang::EOpConvUint8ToInt:
4861 case glslang::EOpConvUint16ToInt:
4862 case glslang::EOpConvUint64ToInt:
4863 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07004864 break;
4865 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07004866 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07004867 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07004868 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07004869 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07004870 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06004871 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07004872 break;
4873
4874 default:
4875 assert(false && "Default missing");
4876 break;
4877 }
4878
John Kessenichad7645f2018-06-04 19:11:25 -06004879 // Get the conversion operation and result type,
4880 // based on the target width, but the source type.
4881 spv::Id type = spv::NoType;
4882 spv::Op convOp = spv::OpNop;
4883 switch(op) {
4884 case glslang::EOpConvInt8ToUint16:
4885 case glslang::EOpConvInt8ToUint:
4886 case glslang::EOpConvInt8ToUint64:
4887 case glslang::EOpConvInt16ToUint8:
4888 case glslang::EOpConvInt16ToUint:
4889 case glslang::EOpConvInt16ToUint64:
4890 case glslang::EOpConvIntToUint8:
4891 case glslang::EOpConvIntToUint16:
4892 case glslang::EOpConvIntToUint64:
4893 case glslang::EOpConvInt64ToUint8:
4894 case glslang::EOpConvInt64ToUint16:
4895 case glslang::EOpConvInt64ToUint:
4896 convOp = spv::OpSConvert;
4897 type = builder.makeIntType(width);
4898 break;
4899 default:
4900 convOp = spv::OpUConvert;
4901 type = builder.makeUintType(width);
4902 break;
4903 }
4904
John Kessenich66011cb2018-03-06 16:12:04 -07004905 if (vectorSize > 0)
4906 type = builder.makeVectorType(type, vectorSize);
4907
John Kessenichad7645f2018-06-04 19:11:25 -06004908 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07004909}
4910
John Kessenichead86222018-03-28 18:01:20 -06004911spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
4912 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004913{
4914 spv::Op convOp = spv::OpNop;
4915 spv::Id zero = 0;
4916 spv::Id one = 0;
4917
4918 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4919
4920 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07004921 case glslang::EOpConvInt8ToBool:
4922 case glslang::EOpConvUint8ToBool:
4923 zero = builder.makeUint8Constant(0);
4924 zero = makeSmearedConstant(zero, vectorSize);
4925 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08004926 case glslang::EOpConvInt16ToBool:
4927 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07004928 zero = builder.makeUint16Constant(0);
4929 zero = makeSmearedConstant(zero, vectorSize);
4930 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4931 case glslang::EOpConvIntToBool:
4932 case glslang::EOpConvUintToBool:
4933 zero = builder.makeUintConstant(0);
4934 zero = makeSmearedConstant(zero, vectorSize);
4935 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4936 case glslang::EOpConvInt64ToBool:
4937 case glslang::EOpConvUint64ToBool:
4938 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004939 zero = makeSmearedConstant(zero, vectorSize);
4940 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4941
4942 case glslang::EOpConvFloatToBool:
4943 zero = builder.makeFloatConstant(0.0F);
4944 zero = makeSmearedConstant(zero, vectorSize);
4945 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4946
4947 case glslang::EOpConvDoubleToBool:
4948 zero = builder.makeDoubleConstant(0.0);
4949 zero = makeSmearedConstant(zero, vectorSize);
4950 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4951
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004952 case glslang::EOpConvFloat16ToBool:
4953 zero = builder.makeFloat16Constant(0.0F);
4954 zero = makeSmearedConstant(zero, vectorSize);
4955 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004956
John Kessenich140f3df2015-06-26 16:58:36 -06004957 case glslang::EOpConvBoolToFloat:
4958 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004959 zero = builder.makeFloatConstant(0.0F);
4960 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004961 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004962
John Kessenich140f3df2015-06-26 16:58:36 -06004963 case glslang::EOpConvBoolToDouble:
4964 convOp = spv::OpSelect;
4965 zero = builder.makeDoubleConstant(0.0);
4966 one = builder.makeDoubleConstant(1.0);
4967 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004968
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004969 case glslang::EOpConvBoolToFloat16:
4970 convOp = spv::OpSelect;
4971 zero = builder.makeFloat16Constant(0.0F);
4972 one = builder.makeFloat16Constant(1.0F);
4973 break;
John Kessenich66011cb2018-03-06 16:12:04 -07004974
4975 case glslang::EOpConvBoolToInt8:
4976 zero = builder.makeInt8Constant(0);
4977 one = builder.makeInt8Constant(1);
4978 convOp = spv::OpSelect;
4979 break;
4980
4981 case glslang::EOpConvBoolToUint8:
4982 zero = builder.makeUint8Constant(0);
4983 one = builder.makeUint8Constant(1);
4984 convOp = spv::OpSelect;
4985 break;
4986
4987 case glslang::EOpConvBoolToInt16:
4988 zero = builder.makeInt16Constant(0);
4989 one = builder.makeInt16Constant(1);
4990 convOp = spv::OpSelect;
4991 break;
4992
4993 case glslang::EOpConvBoolToUint16:
4994 zero = builder.makeUint16Constant(0);
4995 one = builder.makeUint16Constant(1);
4996 convOp = spv::OpSelect;
4997 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004998
John Kessenich140f3df2015-06-26 16:58:36 -06004999 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005000 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005001 if (op == glslang::EOpConvBoolToInt64)
5002 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005003 else
5004 zero = builder.makeIntConstant(0);
5005
5006 if (op == glslang::EOpConvBoolToInt64)
5007 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005008 else
5009 one = builder.makeIntConstant(1);
5010
John Kessenich140f3df2015-06-26 16:58:36 -06005011 convOp = spv::OpSelect;
5012 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005013
John Kessenich140f3df2015-06-26 16:58:36 -06005014 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005015 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005016 if (op == glslang::EOpConvBoolToUint64)
5017 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005018 else
5019 zero = builder.makeUintConstant(0);
5020
5021 if (op == glslang::EOpConvBoolToUint64)
5022 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005023 else
5024 one = builder.makeUintConstant(1);
5025
John Kessenich140f3df2015-06-26 16:58:36 -06005026 convOp = spv::OpSelect;
5027 break;
5028
John Kessenich66011cb2018-03-06 16:12:04 -07005029 case glslang::EOpConvInt8ToFloat16:
5030 case glslang::EOpConvInt8ToFloat:
5031 case glslang::EOpConvInt8ToDouble:
5032 case glslang::EOpConvInt16ToFloat16:
5033 case glslang::EOpConvInt16ToFloat:
5034 case glslang::EOpConvInt16ToDouble:
5035 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005036 case glslang::EOpConvIntToFloat:
5037 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005038 case glslang::EOpConvInt64ToFloat:
5039 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005040 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005041 convOp = spv::OpConvertSToF;
5042 break;
5043
John Kessenich66011cb2018-03-06 16:12:04 -07005044 case glslang::EOpConvUint8ToFloat16:
5045 case glslang::EOpConvUint8ToFloat:
5046 case glslang::EOpConvUint8ToDouble:
5047 case glslang::EOpConvUint16ToFloat16:
5048 case glslang::EOpConvUint16ToFloat:
5049 case glslang::EOpConvUint16ToDouble:
5050 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005051 case glslang::EOpConvUintToFloat:
5052 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005053 case glslang::EOpConvUint64ToFloat:
5054 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005055 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005056 convOp = spv::OpConvertUToF;
5057 break;
5058
5059 case glslang::EOpConvDoubleToFloat:
5060 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005061 case glslang::EOpConvDoubleToFloat16:
5062 case glslang::EOpConvFloat16ToDouble:
5063 case glslang::EOpConvFloatToFloat16:
5064 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005065 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005066 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005067 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005068 break;
5069
John Kessenich66011cb2018-03-06 16:12:04 -07005070 case glslang::EOpConvFloat16ToInt8:
5071 case glslang::EOpConvFloatToInt8:
5072 case glslang::EOpConvDoubleToInt8:
5073 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005074 case glslang::EOpConvFloatToInt16:
5075 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005076 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005077 case glslang::EOpConvFloatToInt:
5078 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005079 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005080 case glslang::EOpConvFloatToInt64:
5081 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005082 convOp = spv::OpConvertFToS;
5083 break;
5084
John Kessenich66011cb2018-03-06 16:12:04 -07005085 case glslang::EOpConvUint8ToInt8:
5086 case glslang::EOpConvInt8ToUint8:
5087 case glslang::EOpConvUint16ToInt16:
5088 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005089 case glslang::EOpConvUintToInt:
5090 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005091 case glslang::EOpConvUint64ToInt64:
5092 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005093 if (builder.isInSpecConstCodeGenMode()) {
5094 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005095 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5096 zero = builder.makeUint8Constant(0);
5097 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005098 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005099 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5100 zero = builder.makeUint64Constant(0);
5101 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005102 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005103 }
qining189b2032016-04-12 23:16:20 -04005104 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005105 // Use OpIAdd, instead of OpBitcast to do the conversion when
5106 // generating for OpSpecConstantOp instruction.
5107 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5108 }
5109 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005110 convOp = spv::OpBitcast;
5111 break;
5112
John Kessenich66011cb2018-03-06 16:12:04 -07005113 case glslang::EOpConvFloat16ToUint8:
5114 case glslang::EOpConvFloatToUint8:
5115 case glslang::EOpConvDoubleToUint8:
5116 case glslang::EOpConvFloat16ToUint16:
5117 case glslang::EOpConvFloatToUint16:
5118 case glslang::EOpConvDoubleToUint16:
5119 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005120 case glslang::EOpConvFloatToUint:
5121 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005122 case glslang::EOpConvFloatToUint64:
5123 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005124 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005125 convOp = spv::OpConvertFToU;
5126 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005127
John Kessenich66011cb2018-03-06 16:12:04 -07005128 case glslang::EOpConvInt8ToInt16:
5129 case glslang::EOpConvInt8ToInt:
5130 case glslang::EOpConvInt8ToInt64:
5131 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005132 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005133 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005134 case glslang::EOpConvIntToInt8:
5135 case glslang::EOpConvIntToInt16:
5136 case glslang::EOpConvIntToInt64:
5137 case glslang::EOpConvInt64ToInt8:
5138 case glslang::EOpConvInt64ToInt16:
5139 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005140 convOp = spv::OpSConvert;
5141 break;
5142
John Kessenich66011cb2018-03-06 16:12:04 -07005143 case glslang::EOpConvUint8ToUint16:
5144 case glslang::EOpConvUint8ToUint:
5145 case glslang::EOpConvUint8ToUint64:
5146 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005147 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005148 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005149 case glslang::EOpConvUintToUint8:
5150 case glslang::EOpConvUintToUint16:
5151 case glslang::EOpConvUintToUint64:
5152 case glslang::EOpConvUint64ToUint8:
5153 case glslang::EOpConvUint64ToUint16:
5154 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005155 convOp = spv::OpUConvert;
5156 break;
5157
John Kessenich66011cb2018-03-06 16:12:04 -07005158 case glslang::EOpConvInt8ToUint16:
5159 case glslang::EOpConvInt8ToUint:
5160 case glslang::EOpConvInt8ToUint64:
5161 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005162 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005163 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005164 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005165 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005166 case glslang::EOpConvIntToUint64:
5167 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005168 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005169 case glslang::EOpConvInt64ToUint:
5170 case glslang::EOpConvUint8ToInt16:
5171 case glslang::EOpConvUint8ToInt:
5172 case glslang::EOpConvUint8ToInt64:
5173 case glslang::EOpConvUint16ToInt8:
5174 case glslang::EOpConvUint16ToInt:
5175 case glslang::EOpConvUint16ToInt64:
5176 case glslang::EOpConvUintToInt8:
5177 case glslang::EOpConvUintToInt16:
5178 case glslang::EOpConvUintToInt64:
5179 case glslang::EOpConvUint64ToInt8:
5180 case glslang::EOpConvUint64ToInt16:
5181 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005182 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005183 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005184
5185 if (builder.isInSpecConstCodeGenMode()) {
5186 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005187 switch(op) {
5188 case glslang::EOpConvInt16ToUint8:
5189 case glslang::EOpConvIntToUint8:
5190 case glslang::EOpConvInt64ToUint8:
5191 case glslang::EOpConvUint16ToInt8:
5192 case glslang::EOpConvUintToInt8:
5193 case glslang::EOpConvUint64ToInt8:
5194 zero = builder.makeUint8Constant(0);
5195 break;
5196 case glslang::EOpConvInt8ToUint16:
5197 case glslang::EOpConvIntToUint16:
5198 case glslang::EOpConvInt64ToUint16:
5199 case glslang::EOpConvUint8ToInt16:
5200 case glslang::EOpConvUintToInt16:
5201 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005202 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005203 break;
5204 case glslang::EOpConvInt8ToUint:
5205 case glslang::EOpConvInt16ToUint:
5206 case glslang::EOpConvInt64ToUint:
5207 case glslang::EOpConvUint8ToInt:
5208 case glslang::EOpConvUint16ToInt:
5209 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005210 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005211 break;
5212 case glslang::EOpConvInt8ToUint64:
5213 case glslang::EOpConvInt16ToUint64:
5214 case glslang::EOpConvIntToUint64:
5215 case glslang::EOpConvUint8ToInt64:
5216 case glslang::EOpConvUint16ToInt64:
5217 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005218 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005219 break;
5220 default:
5221 assert(false && "Default missing");
5222 break;
5223 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005224 zero = makeSmearedConstant(zero, vectorSize);
5225 // Use OpIAdd, instead of OpBitcast to do the conversion when
5226 // generating for OpSpecConstantOp instruction.
5227 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5228 }
5229 // For normal run-time conversion instruction, use OpBitcast.
5230 convOp = spv::OpBitcast;
5231 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005232 default:
5233 break;
5234 }
5235
5236 spv::Id result = 0;
5237 if (convOp == spv::OpNop)
5238 return result;
5239
5240 if (convOp == spv::OpSelect) {
5241 zero = makeSmearedConstant(zero, vectorSize);
5242 one = makeSmearedConstant(one, vectorSize);
5243 result = builder.createTriOp(convOp, destType, operand, one, zero);
5244 } else
5245 result = builder.createUnaryOp(convOp, destType, operand);
5246
John Kessenichead86222018-03-28 18:01:20 -06005247 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005248 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005249 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06005250}
5251
5252spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
5253{
5254 if (vectorSize == 0)
5255 return constant;
5256
5257 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
5258 std::vector<spv::Id> components;
5259 for (int c = 0; c < vectorSize; ++c)
5260 components.push_back(constant);
5261 return builder.makeCompositeConstant(vectorTypeId, components);
5262}
5263
John Kessenich426394d2015-07-23 10:22:48 -06005264// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07005265spv::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 -06005266{
5267 spv::Op opCode = spv::OpNop;
5268
5269 switch (op) {
5270 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08005271 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005272 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06005273 opCode = spv::OpAtomicIAdd;
5274 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06005275 case glslang::EOpAtomicCounterSubtract:
5276 opCode = spv::OpAtomicISub;
5277 break;
John Kessenich426394d2015-07-23 10:22:48 -06005278 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08005279 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005280 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08005281 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06005282 break;
5283 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08005284 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005285 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08005286 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06005287 break;
5288 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08005289 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005290 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06005291 opCode = spv::OpAtomicAnd;
5292 break;
5293 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08005294 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005295 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06005296 opCode = spv::OpAtomicOr;
5297 break;
5298 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08005299 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005300 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06005301 opCode = spv::OpAtomicXor;
5302 break;
5303 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08005304 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005305 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06005306 opCode = spv::OpAtomicExchange;
5307 break;
5308 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08005309 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005310 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06005311 opCode = spv::OpAtomicCompareExchange;
5312 break;
5313 case glslang::EOpAtomicCounterIncrement:
5314 opCode = spv::OpAtomicIIncrement;
5315 break;
5316 case glslang::EOpAtomicCounterDecrement:
5317 opCode = spv::OpAtomicIDecrement;
5318 break;
5319 case glslang::EOpAtomicCounter:
5320 opCode = spv::OpAtomicLoad;
5321 break;
5322 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005323 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06005324 break;
5325 }
5326
Rex Xue8fe8b02017-09-26 15:42:56 +08005327 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
5328 builder.addCapability(spv::CapabilityInt64Atomics);
5329
John Kessenich426394d2015-07-23 10:22:48 -06005330 // Sort out the operands
5331 // - mapping from glslang -> SPV
5332 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06005333 // - compare-exchange swaps the value and comparator
5334 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06005335 // - EOpAtomicCounterDecrement needs a post decrement
John Kessenich426394d2015-07-23 10:22:48 -06005336 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
5337 auto opIt = operands.begin(); // walk the glslang operands
5338 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08005339 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
5340 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
5341 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08005342 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
5343 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08005344 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06005345 spvAtomicOperands.push_back(*(opIt + 1));
5346 spvAtomicOperands.push_back(*opIt);
5347 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08005348 }
John Kessenich426394d2015-07-23 10:22:48 -06005349
John Kessenich3e60a6f2015-09-14 22:45:16 -06005350 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06005351 for (; opIt != operands.end(); ++opIt)
5352 spvAtomicOperands.push_back(*opIt);
5353
John Kessenich48d6e792017-10-06 21:21:48 -06005354 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
5355
5356 // GLSL and HLSL atomic-counter decrement return post-decrement value,
5357 // while SPIR-V returns pre-decrement value. Translate between these semantics.
5358 if (op == glslang::EOpAtomicCounterDecrement)
5359 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
5360
5361 return resultId;
John Kessenich426394d2015-07-23 10:22:48 -06005362}
5363
John Kessenich91cef522016-05-05 16:45:40 -06005364// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08005365spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06005366{
John Kessenich66011cb2018-03-06 16:12:04 -07005367 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5368 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08005369
Rex Xu51596642016-09-21 18:56:12 +08005370 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08005371 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08005372 spv::GroupOperation groupOperation = spv::GroupOperationMax;
5373
chaocf200da82016-12-20 12:44:35 -08005374 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
5375 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08005376 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
5377 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005378 } else if (op == glslang::EOpAnyInvocation ||
5379 op == glslang::EOpAllInvocations ||
5380 op == glslang::EOpAllInvocationsEqual) {
5381 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
5382 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08005383 } else {
5384 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04005385#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08005386 if (op == glslang::EOpMinInvocationsNonUniform ||
5387 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08005388 op == glslang::EOpAddInvocationsNonUniform ||
5389 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5390 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5391 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
5392 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
5393 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
5394 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08005395 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04005396#endif
Rex Xu51596642016-09-21 18:56:12 +08005397
5398 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08005399#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08005400 switch (op) {
5401 case glslang::EOpMinInvocations:
5402 case glslang::EOpMaxInvocations:
5403 case glslang::EOpAddInvocations:
5404 case glslang::EOpMinInvocationsNonUniform:
5405 case glslang::EOpMaxInvocationsNonUniform:
5406 case glslang::EOpAddInvocationsNonUniform:
5407 groupOperation = spv::GroupOperationReduce;
5408 spvGroupOperands.push_back(groupOperation);
5409 break;
5410 case glslang::EOpMinInvocationsInclusiveScan:
5411 case glslang::EOpMaxInvocationsInclusiveScan:
5412 case glslang::EOpAddInvocationsInclusiveScan:
5413 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5414 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5415 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5416 groupOperation = spv::GroupOperationInclusiveScan;
5417 spvGroupOperands.push_back(groupOperation);
5418 break;
5419 case glslang::EOpMinInvocationsExclusiveScan:
5420 case glslang::EOpMaxInvocationsExclusiveScan:
5421 case glslang::EOpAddInvocationsExclusiveScan:
5422 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5423 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5424 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5425 groupOperation = spv::GroupOperationExclusiveScan;
5426 spvGroupOperands.push_back(groupOperation);
5427 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07005428 default:
5429 break;
Rex Xu430ef402016-10-14 17:22:23 +08005430 }
Rex Xu9d93a232016-05-05 12:30:44 +08005431#endif
Rex Xu51596642016-09-21 18:56:12 +08005432 }
5433
5434 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
5435 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06005436
5437 switch (op) {
5438 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005439 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08005440 break;
John Kessenich91cef522016-05-05 16:45:40 -06005441 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005442 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08005443 break;
John Kessenich91cef522016-05-05 16:45:40 -06005444 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005445 opCode = spv::OpSubgroupAllEqualKHR;
5446 break;
Rex Xu51596642016-09-21 18:56:12 +08005447 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08005448 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08005449 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005450 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005451 break;
5452 case glslang::EOpReadFirstInvocation:
5453 opCode = spv::OpSubgroupFirstInvocationKHR;
5454 break;
5455 case glslang::EOpBallot:
5456 {
5457 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
5458 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
5459 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
5460 //
5461 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
5462 //
5463 spv::Id uintType = builder.makeUintType(32);
5464 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
5465 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
5466
5467 std::vector<spv::Id> components;
5468 components.push_back(builder.createCompositeExtract(result, uintType, 0));
5469 components.push_back(builder.createCompositeExtract(result, uintType, 1));
5470
5471 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
5472 return builder.createUnaryOp(spv::OpBitcast, typeId,
5473 builder.createCompositeConstruct(uvec2Type, components));
5474 }
5475
Rex Xu9d93a232016-05-05 12:30:44 +08005476#ifdef AMD_EXTENSIONS
5477 case glslang::EOpMinInvocations:
5478 case glslang::EOpMaxInvocations:
5479 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08005480 case glslang::EOpMinInvocationsInclusiveScan:
5481 case glslang::EOpMaxInvocationsInclusiveScan:
5482 case glslang::EOpAddInvocationsInclusiveScan:
5483 case glslang::EOpMinInvocationsExclusiveScan:
5484 case glslang::EOpMaxInvocationsExclusiveScan:
5485 case glslang::EOpAddInvocationsExclusiveScan:
5486 if (op == glslang::EOpMinInvocations ||
5487 op == glslang::EOpMinInvocationsInclusiveScan ||
5488 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005489 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005490 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005491 else {
5492 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005493 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005494 else
Rex Xu51596642016-09-21 18:56:12 +08005495 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005496 }
Rex Xu430ef402016-10-14 17:22:23 +08005497 } else if (op == glslang::EOpMaxInvocations ||
5498 op == glslang::EOpMaxInvocationsInclusiveScan ||
5499 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005500 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005501 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005502 else {
5503 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005504 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005505 else
Rex Xu51596642016-09-21 18:56:12 +08005506 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005507 }
5508 } else {
5509 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005510 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005511 else
Rex Xu51596642016-09-21 18:56:12 +08005512 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005513 }
5514
Rex Xu2bbbe062016-08-23 15:41:05 +08005515 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005516 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005517
5518 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005519 case glslang::EOpMinInvocationsNonUniform:
5520 case glslang::EOpMaxInvocationsNonUniform:
5521 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005522 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5523 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5524 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5525 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5526 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5527 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5528 if (op == glslang::EOpMinInvocationsNonUniform ||
5529 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5530 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005531 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005532 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005533 else {
5534 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005535 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005536 else
Rex Xu51596642016-09-21 18:56:12 +08005537 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005538 }
5539 }
Rex Xu430ef402016-10-14 17:22:23 +08005540 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5541 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5542 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005543 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005544 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005545 else {
5546 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005547 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005548 else
Rex Xu51596642016-09-21 18:56:12 +08005549 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005550 }
5551 }
5552 else {
5553 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005554 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005555 else
Rex Xu51596642016-09-21 18:56:12 +08005556 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005557 }
5558
Rex Xu2bbbe062016-08-23 15:41:05 +08005559 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005560 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005561
5562 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005563#endif
John Kessenich91cef522016-05-05 16:45:40 -06005564 default:
5565 logger->missingFunctionality("invocation operation");
5566 return spv::NoResult;
5567 }
Rex Xu51596642016-09-21 18:56:12 +08005568
5569 assert(opCode != spv::OpNop);
5570 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005571}
5572
Rex Xu2bbbe062016-08-23 15:41:05 +08005573// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005574spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005575{
Rex Xub7072052016-09-26 15:53:40 +08005576#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005577 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5578 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005579 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005580 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005581 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5582 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5583 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005584#else
5585 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5586 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005587 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5588 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005589#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005590
5591 // Handle group invocation operations scalar by scalar.
5592 // The result type is the same type as the original type.
5593 // The algorithm is to:
5594 // - break the vector into scalars
5595 // - apply the operation to each scalar
5596 // - make a vector out the scalar results
5597
5598 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005599 int numComponents = builder.getNumComponents(operands[0]);
5600 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005601 std::vector<spv::Id> results;
5602
5603 // do each scalar op
5604 for (int comp = 0; comp < numComponents; ++comp) {
5605 std::vector<unsigned int> indexes;
5606 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005607 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005608 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005609 if (op == spv::OpSubgroupReadInvocationKHR) {
5610 spvGroupOperands.push_back(scalar);
5611 spvGroupOperands.push_back(operands[1]);
5612 } else if (op == spv::OpGroupBroadcast) {
5613 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005614 spvGroupOperands.push_back(scalar);
5615 spvGroupOperands.push_back(operands[1]);
5616 } else {
chaocf200da82016-12-20 12:44:35 -08005617 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005618 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005619 spvGroupOperands.push_back(scalar);
5620 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005621
Rex Xub7072052016-09-26 15:53:40 +08005622 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005623 }
5624
5625 // put the pieces together
5626 return builder.createCompositeConstruct(typeId, results);
5627}
Rex Xu2bbbe062016-08-23 15:41:05 +08005628
John Kessenich66011cb2018-03-06 16:12:04 -07005629// Create subgroup invocation operations.
5630spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
5631{
5632 // Add the required capabilities.
5633 switch (op) {
5634 case glslang::EOpSubgroupElect:
5635 builder.addCapability(spv::CapabilityGroupNonUniform);
5636 break;
5637 case glslang::EOpSubgroupAll:
5638 case glslang::EOpSubgroupAny:
5639 case glslang::EOpSubgroupAllEqual:
5640 builder.addCapability(spv::CapabilityGroupNonUniform);
5641 builder.addCapability(spv::CapabilityGroupNonUniformVote);
5642 break;
5643 case glslang::EOpSubgroupBroadcast:
5644 case glslang::EOpSubgroupBroadcastFirst:
5645 case glslang::EOpSubgroupBallot:
5646 case glslang::EOpSubgroupInverseBallot:
5647 case glslang::EOpSubgroupBallotBitExtract:
5648 case glslang::EOpSubgroupBallotBitCount:
5649 case glslang::EOpSubgroupBallotInclusiveBitCount:
5650 case glslang::EOpSubgroupBallotExclusiveBitCount:
5651 case glslang::EOpSubgroupBallotFindLSB:
5652 case glslang::EOpSubgroupBallotFindMSB:
5653 builder.addCapability(spv::CapabilityGroupNonUniform);
5654 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
5655 break;
5656 case glslang::EOpSubgroupShuffle:
5657 case glslang::EOpSubgroupShuffleXor:
5658 builder.addCapability(spv::CapabilityGroupNonUniform);
5659 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
5660 break;
5661 case glslang::EOpSubgroupShuffleUp:
5662 case glslang::EOpSubgroupShuffleDown:
5663 builder.addCapability(spv::CapabilityGroupNonUniform);
5664 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
5665 break;
5666 case glslang::EOpSubgroupAdd:
5667 case glslang::EOpSubgroupMul:
5668 case glslang::EOpSubgroupMin:
5669 case glslang::EOpSubgroupMax:
5670 case glslang::EOpSubgroupAnd:
5671 case glslang::EOpSubgroupOr:
5672 case glslang::EOpSubgroupXor:
5673 case glslang::EOpSubgroupInclusiveAdd:
5674 case glslang::EOpSubgroupInclusiveMul:
5675 case glslang::EOpSubgroupInclusiveMin:
5676 case glslang::EOpSubgroupInclusiveMax:
5677 case glslang::EOpSubgroupInclusiveAnd:
5678 case glslang::EOpSubgroupInclusiveOr:
5679 case glslang::EOpSubgroupInclusiveXor:
5680 case glslang::EOpSubgroupExclusiveAdd:
5681 case glslang::EOpSubgroupExclusiveMul:
5682 case glslang::EOpSubgroupExclusiveMin:
5683 case glslang::EOpSubgroupExclusiveMax:
5684 case glslang::EOpSubgroupExclusiveAnd:
5685 case glslang::EOpSubgroupExclusiveOr:
5686 case glslang::EOpSubgroupExclusiveXor:
5687 builder.addCapability(spv::CapabilityGroupNonUniform);
5688 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
5689 break;
5690 case glslang::EOpSubgroupClusteredAdd:
5691 case glslang::EOpSubgroupClusteredMul:
5692 case glslang::EOpSubgroupClusteredMin:
5693 case glslang::EOpSubgroupClusteredMax:
5694 case glslang::EOpSubgroupClusteredAnd:
5695 case glslang::EOpSubgroupClusteredOr:
5696 case glslang::EOpSubgroupClusteredXor:
5697 builder.addCapability(spv::CapabilityGroupNonUniform);
5698 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
5699 break;
5700 case glslang::EOpSubgroupQuadBroadcast:
5701 case glslang::EOpSubgroupQuadSwapHorizontal:
5702 case glslang::EOpSubgroupQuadSwapVertical:
5703 case glslang::EOpSubgroupQuadSwapDiagonal:
5704 builder.addCapability(spv::CapabilityGroupNonUniform);
5705 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
5706 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005707#ifdef NV_EXTENSIONS
5708 case glslang::EOpSubgroupPartitionedAdd:
5709 case glslang::EOpSubgroupPartitionedMul:
5710 case glslang::EOpSubgroupPartitionedMin:
5711 case glslang::EOpSubgroupPartitionedMax:
5712 case glslang::EOpSubgroupPartitionedAnd:
5713 case glslang::EOpSubgroupPartitionedOr:
5714 case glslang::EOpSubgroupPartitionedXor:
5715 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5716 case glslang::EOpSubgroupPartitionedInclusiveMul:
5717 case glslang::EOpSubgroupPartitionedInclusiveMin:
5718 case glslang::EOpSubgroupPartitionedInclusiveMax:
5719 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5720 case glslang::EOpSubgroupPartitionedInclusiveOr:
5721 case glslang::EOpSubgroupPartitionedInclusiveXor:
5722 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5723 case glslang::EOpSubgroupPartitionedExclusiveMul:
5724 case glslang::EOpSubgroupPartitionedExclusiveMin:
5725 case glslang::EOpSubgroupPartitionedExclusiveMax:
5726 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5727 case glslang::EOpSubgroupPartitionedExclusiveOr:
5728 case glslang::EOpSubgroupPartitionedExclusiveXor:
5729 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
5730 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
5731 break;
5732#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005733 default: assert(0 && "Unhandled subgroup operation!");
5734 }
5735
5736 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
5737 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
5738 const bool isBool = typeProxy == glslang::EbtBool;
5739
5740 spv::Op opCode = spv::OpNop;
5741
5742 // Figure out which opcode to use.
5743 switch (op) {
5744 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
5745 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
5746 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
5747 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
5748 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
5749 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
5750 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
5751 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
5752 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
5753 case glslang::EOpSubgroupBallotBitCount:
5754 case glslang::EOpSubgroupBallotInclusiveBitCount:
5755 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
5756 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
5757 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
5758 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
5759 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
5760 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
5761 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
5762 case glslang::EOpSubgroupAdd:
5763 case glslang::EOpSubgroupInclusiveAdd:
5764 case glslang::EOpSubgroupExclusiveAdd:
5765 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005766#ifdef NV_EXTENSIONS
5767 case glslang::EOpSubgroupPartitionedAdd:
5768 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5769 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5770#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005771 if (isFloat) {
5772 opCode = spv::OpGroupNonUniformFAdd;
5773 } else {
5774 opCode = spv::OpGroupNonUniformIAdd;
5775 }
5776 break;
5777 case glslang::EOpSubgroupMul:
5778 case glslang::EOpSubgroupInclusiveMul:
5779 case glslang::EOpSubgroupExclusiveMul:
5780 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005781#ifdef NV_EXTENSIONS
5782 case glslang::EOpSubgroupPartitionedMul:
5783 case glslang::EOpSubgroupPartitionedInclusiveMul:
5784 case glslang::EOpSubgroupPartitionedExclusiveMul:
5785#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005786 if (isFloat) {
5787 opCode = spv::OpGroupNonUniformFMul;
5788 } else {
5789 opCode = spv::OpGroupNonUniformIMul;
5790 }
5791 break;
5792 case glslang::EOpSubgroupMin:
5793 case glslang::EOpSubgroupInclusiveMin:
5794 case glslang::EOpSubgroupExclusiveMin:
5795 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005796#ifdef NV_EXTENSIONS
5797 case glslang::EOpSubgroupPartitionedMin:
5798 case glslang::EOpSubgroupPartitionedInclusiveMin:
5799 case glslang::EOpSubgroupPartitionedExclusiveMin:
5800#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005801 if (isFloat) {
5802 opCode = spv::OpGroupNonUniformFMin;
5803 } else if (isUnsigned) {
5804 opCode = spv::OpGroupNonUniformUMin;
5805 } else {
5806 opCode = spv::OpGroupNonUniformSMin;
5807 }
5808 break;
5809 case glslang::EOpSubgroupMax:
5810 case glslang::EOpSubgroupInclusiveMax:
5811 case glslang::EOpSubgroupExclusiveMax:
5812 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005813#ifdef NV_EXTENSIONS
5814 case glslang::EOpSubgroupPartitionedMax:
5815 case glslang::EOpSubgroupPartitionedInclusiveMax:
5816 case glslang::EOpSubgroupPartitionedExclusiveMax:
5817#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005818 if (isFloat) {
5819 opCode = spv::OpGroupNonUniformFMax;
5820 } else if (isUnsigned) {
5821 opCode = spv::OpGroupNonUniformUMax;
5822 } else {
5823 opCode = spv::OpGroupNonUniformSMax;
5824 }
5825 break;
5826 case glslang::EOpSubgroupAnd:
5827 case glslang::EOpSubgroupInclusiveAnd:
5828 case glslang::EOpSubgroupExclusiveAnd:
5829 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005830#ifdef NV_EXTENSIONS
5831 case glslang::EOpSubgroupPartitionedAnd:
5832 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5833 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5834#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005835 if (isBool) {
5836 opCode = spv::OpGroupNonUniformLogicalAnd;
5837 } else {
5838 opCode = spv::OpGroupNonUniformBitwiseAnd;
5839 }
5840 break;
5841 case glslang::EOpSubgroupOr:
5842 case glslang::EOpSubgroupInclusiveOr:
5843 case glslang::EOpSubgroupExclusiveOr:
5844 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005845#ifdef NV_EXTENSIONS
5846 case glslang::EOpSubgroupPartitionedOr:
5847 case glslang::EOpSubgroupPartitionedInclusiveOr:
5848 case glslang::EOpSubgroupPartitionedExclusiveOr:
5849#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005850 if (isBool) {
5851 opCode = spv::OpGroupNonUniformLogicalOr;
5852 } else {
5853 opCode = spv::OpGroupNonUniformBitwiseOr;
5854 }
5855 break;
5856 case glslang::EOpSubgroupXor:
5857 case glslang::EOpSubgroupInclusiveXor:
5858 case glslang::EOpSubgroupExclusiveXor:
5859 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005860#ifdef NV_EXTENSIONS
5861 case glslang::EOpSubgroupPartitionedXor:
5862 case glslang::EOpSubgroupPartitionedInclusiveXor:
5863 case glslang::EOpSubgroupPartitionedExclusiveXor:
5864#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005865 if (isBool) {
5866 opCode = spv::OpGroupNonUniformLogicalXor;
5867 } else {
5868 opCode = spv::OpGroupNonUniformBitwiseXor;
5869 }
5870 break;
5871 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
5872 case glslang::EOpSubgroupQuadSwapHorizontal:
5873 case glslang::EOpSubgroupQuadSwapVertical:
5874 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
5875 default: assert(0 && "Unhandled subgroup operation!");
5876 }
5877
5878 std::vector<spv::Id> spvGroupOperands;
5879
5880 // Every operation begins with the Execution Scope operand.
5881 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
5882
5883 // Next, for all operations that use a Group Operation, push that as an operand.
5884 switch (op) {
5885 default: break;
5886 case glslang::EOpSubgroupBallotBitCount:
5887 case glslang::EOpSubgroupAdd:
5888 case glslang::EOpSubgroupMul:
5889 case glslang::EOpSubgroupMin:
5890 case glslang::EOpSubgroupMax:
5891 case glslang::EOpSubgroupAnd:
5892 case glslang::EOpSubgroupOr:
5893 case glslang::EOpSubgroupXor:
5894 spvGroupOperands.push_back(spv::GroupOperationReduce);
5895 break;
5896 case glslang::EOpSubgroupBallotInclusiveBitCount:
5897 case glslang::EOpSubgroupInclusiveAdd:
5898 case glslang::EOpSubgroupInclusiveMul:
5899 case glslang::EOpSubgroupInclusiveMin:
5900 case glslang::EOpSubgroupInclusiveMax:
5901 case glslang::EOpSubgroupInclusiveAnd:
5902 case glslang::EOpSubgroupInclusiveOr:
5903 case glslang::EOpSubgroupInclusiveXor:
5904 spvGroupOperands.push_back(spv::GroupOperationInclusiveScan);
5905 break;
5906 case glslang::EOpSubgroupBallotExclusiveBitCount:
5907 case glslang::EOpSubgroupExclusiveAdd:
5908 case glslang::EOpSubgroupExclusiveMul:
5909 case glslang::EOpSubgroupExclusiveMin:
5910 case glslang::EOpSubgroupExclusiveMax:
5911 case glslang::EOpSubgroupExclusiveAnd:
5912 case glslang::EOpSubgroupExclusiveOr:
5913 case glslang::EOpSubgroupExclusiveXor:
5914 spvGroupOperands.push_back(spv::GroupOperationExclusiveScan);
5915 break;
5916 case glslang::EOpSubgroupClusteredAdd:
5917 case glslang::EOpSubgroupClusteredMul:
5918 case glslang::EOpSubgroupClusteredMin:
5919 case glslang::EOpSubgroupClusteredMax:
5920 case glslang::EOpSubgroupClusteredAnd:
5921 case glslang::EOpSubgroupClusteredOr:
5922 case glslang::EOpSubgroupClusteredXor:
5923 spvGroupOperands.push_back(spv::GroupOperationClusteredReduce);
5924 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005925#ifdef NV_EXTENSIONS
5926 case glslang::EOpSubgroupPartitionedAdd:
5927 case glslang::EOpSubgroupPartitionedMul:
5928 case glslang::EOpSubgroupPartitionedMin:
5929 case glslang::EOpSubgroupPartitionedMax:
5930 case glslang::EOpSubgroupPartitionedAnd:
5931 case glslang::EOpSubgroupPartitionedOr:
5932 case glslang::EOpSubgroupPartitionedXor:
5933 spvGroupOperands.push_back(spv::GroupOperationPartitionedReduceNV);
5934 break;
5935 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5936 case glslang::EOpSubgroupPartitionedInclusiveMul:
5937 case glslang::EOpSubgroupPartitionedInclusiveMin:
5938 case glslang::EOpSubgroupPartitionedInclusiveMax:
5939 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5940 case glslang::EOpSubgroupPartitionedInclusiveOr:
5941 case glslang::EOpSubgroupPartitionedInclusiveXor:
5942 spvGroupOperands.push_back(spv::GroupOperationPartitionedInclusiveScanNV);
5943 break;
5944 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5945 case glslang::EOpSubgroupPartitionedExclusiveMul:
5946 case glslang::EOpSubgroupPartitionedExclusiveMin:
5947 case glslang::EOpSubgroupPartitionedExclusiveMax:
5948 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5949 case glslang::EOpSubgroupPartitionedExclusiveOr:
5950 case glslang::EOpSubgroupPartitionedExclusiveXor:
5951 spvGroupOperands.push_back(spv::GroupOperationPartitionedExclusiveScanNV);
5952 break;
5953#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005954 }
5955
5956 // Push back the operands next.
5957 for (auto opIt : operands) {
5958 spvGroupOperands.push_back(opIt);
5959 }
5960
5961 // Some opcodes have additional operands.
5962 switch (op) {
5963 default: break;
5964 case glslang::EOpSubgroupQuadSwapHorizontal: spvGroupOperands.push_back(builder.makeUintConstant(0)); break;
5965 case glslang::EOpSubgroupQuadSwapVertical: spvGroupOperands.push_back(builder.makeUintConstant(1)); break;
5966 case glslang::EOpSubgroupQuadSwapDiagonal: spvGroupOperands.push_back(builder.makeUintConstant(2)); break;
5967 }
5968
5969 return builder.createOp(opCode, typeId, spvGroupOperands);
5970}
5971
John Kessenich5e4b1242015-08-06 22:53:06 -06005972spv::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 -06005973{
John Kessenich66011cb2018-03-06 16:12:04 -07005974 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5975 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06005976
John Kessenich140f3df2015-06-26 16:58:36 -06005977 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005978 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005979 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005980 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005981 spv::Id typeId0 = 0;
5982 if (consumedOperands > 0)
5983 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005984 spv::Id typeId1 = 0;
5985 if (consumedOperands > 1)
5986 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005987 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005988
5989 switch (op) {
5990 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005991 if (isFloat)
5992 libCall = spv::GLSLstd450FMin;
5993 else if (isUnsigned)
5994 libCall = spv::GLSLstd450UMin;
5995 else
5996 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005997 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005998 break;
5999 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006000 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006001 break;
6002 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006003 if (isFloat)
6004 libCall = spv::GLSLstd450FMax;
6005 else if (isUnsigned)
6006 libCall = spv::GLSLstd450UMax;
6007 else
6008 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006009 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006010 break;
6011 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006012 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006013 break;
6014 case glslang::EOpDot:
6015 opCode = spv::OpDot;
6016 break;
6017 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006018 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006019 break;
6020
6021 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006022 if (isFloat)
6023 libCall = spv::GLSLstd450FClamp;
6024 else if (isUnsigned)
6025 libCall = spv::GLSLstd450UClamp;
6026 else
6027 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006028 builder.promoteScalar(precision, operands.front(), operands[1]);
6029 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006030 break;
6031 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006032 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6033 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006034 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006035 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006036 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006037 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006038 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006039 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006040 break;
6041 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006042 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006043 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006044 break;
6045 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006046 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006047 builder.promoteScalar(precision, operands[0], operands[2]);
6048 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006049 break;
6050
6051 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006052 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006053 break;
6054 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006055 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006056 break;
6057 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006058 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006059 break;
6060 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006061 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006062 break;
6063 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006064 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006065 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006066 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006067#ifdef AMD_EXTENSIONS
6068 if (typeProxy == glslang::EbtFloat16)
6069 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6070#endif
John Kessenich92187592016-02-01 13:45:25 -07006071 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08006072 libCall = spv::GLSLstd450InterpolateAtSample;
6073 break;
6074 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006075#ifdef AMD_EXTENSIONS
6076 if (typeProxy == glslang::EbtFloat16)
6077 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6078#endif
John Kessenich92187592016-02-01 13:45:25 -07006079 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08006080 libCall = spv::GLSLstd450InterpolateAtOffset;
6081 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006082 case glslang::EOpAddCarry:
6083 opCode = spv::OpIAddCarry;
6084 typeId = builder.makeStructResultType(typeId0, typeId0);
6085 consumedOperands = 2;
6086 break;
6087 case glslang::EOpSubBorrow:
6088 opCode = spv::OpISubBorrow;
6089 typeId = builder.makeStructResultType(typeId0, typeId0);
6090 consumedOperands = 2;
6091 break;
6092 case glslang::EOpUMulExtended:
6093 opCode = spv::OpUMulExtended;
6094 typeId = builder.makeStructResultType(typeId0, typeId0);
6095 consumedOperands = 2;
6096 break;
6097 case glslang::EOpIMulExtended:
6098 opCode = spv::OpSMulExtended;
6099 typeId = builder.makeStructResultType(typeId0, typeId0);
6100 consumedOperands = 2;
6101 break;
6102 case glslang::EOpBitfieldExtract:
6103 if (isUnsigned)
6104 opCode = spv::OpBitFieldUExtract;
6105 else
6106 opCode = spv::OpBitFieldSExtract;
6107 break;
6108 case glslang::EOpBitfieldInsert:
6109 opCode = spv::OpBitFieldInsert;
6110 break;
6111
6112 case glslang::EOpFma:
6113 libCall = spv::GLSLstd450Fma;
6114 break;
6115 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006116 {
6117 libCall = spv::GLSLstd450FrexpStruct;
6118 assert(builder.isPointerType(typeId1));
6119 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006120 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006121#ifdef AMD_EXTENSIONS
6122 if (width == 16)
6123 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6124 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
6125#endif
Rex Xu470026f2017-03-29 17:12:40 +08006126 if (builder.getNumComponents(operands[0]) == 1)
6127 frexpIntType = builder.makeIntegerType(width, true);
6128 else
6129 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6130 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6131 consumedOperands = 1;
6132 }
John Kessenich55e7d112015-11-15 21:33:39 -07006133 break;
6134 case glslang::EOpLdexp:
6135 libCall = spv::GLSLstd450Ldexp;
6136 break;
6137
Rex Xu574ab042016-04-14 16:53:07 +08006138 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08006139 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08006140
John Kessenich66011cb2018-03-06 16:12:04 -07006141 case glslang::EOpSubgroupBroadcast:
6142 case glslang::EOpSubgroupBallotBitExtract:
6143 case glslang::EOpSubgroupShuffle:
6144 case glslang::EOpSubgroupShuffleXor:
6145 case glslang::EOpSubgroupShuffleUp:
6146 case glslang::EOpSubgroupShuffleDown:
6147 case glslang::EOpSubgroupClusteredAdd:
6148 case glslang::EOpSubgroupClusteredMul:
6149 case glslang::EOpSubgroupClusteredMin:
6150 case glslang::EOpSubgroupClusteredMax:
6151 case glslang::EOpSubgroupClusteredAnd:
6152 case glslang::EOpSubgroupClusteredOr:
6153 case glslang::EOpSubgroupClusteredXor:
6154 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006155#ifdef NV_EXTENSIONS
6156 case glslang::EOpSubgroupPartitionedAdd:
6157 case glslang::EOpSubgroupPartitionedMul:
6158 case glslang::EOpSubgroupPartitionedMin:
6159 case glslang::EOpSubgroupPartitionedMax:
6160 case glslang::EOpSubgroupPartitionedAnd:
6161 case glslang::EOpSubgroupPartitionedOr:
6162 case glslang::EOpSubgroupPartitionedXor:
6163 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6164 case glslang::EOpSubgroupPartitionedInclusiveMul:
6165 case glslang::EOpSubgroupPartitionedInclusiveMin:
6166 case glslang::EOpSubgroupPartitionedInclusiveMax:
6167 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6168 case glslang::EOpSubgroupPartitionedInclusiveOr:
6169 case glslang::EOpSubgroupPartitionedInclusiveXor:
6170 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6171 case glslang::EOpSubgroupPartitionedExclusiveMul:
6172 case glslang::EOpSubgroupPartitionedExclusiveMin:
6173 case glslang::EOpSubgroupPartitionedExclusiveMax:
6174 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6175 case glslang::EOpSubgroupPartitionedExclusiveOr:
6176 case glslang::EOpSubgroupPartitionedExclusiveXor:
6177#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006178 return createSubgroupOperation(op, typeId, operands, typeProxy);
6179
Rex Xu9d93a232016-05-05 12:30:44 +08006180#ifdef AMD_EXTENSIONS
6181 case glslang::EOpSwizzleInvocations:
6182 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6183 libCall = spv::SwizzleInvocationsAMD;
6184 break;
6185 case glslang::EOpSwizzleInvocationsMasked:
6186 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6187 libCall = spv::SwizzleInvocationsMaskedAMD;
6188 break;
6189 case glslang::EOpWriteInvocation:
6190 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6191 libCall = spv::WriteInvocationAMD;
6192 break;
6193
6194 case glslang::EOpMin3:
6195 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6196 if (isFloat)
6197 libCall = spv::FMin3AMD;
6198 else {
6199 if (isUnsigned)
6200 libCall = spv::UMin3AMD;
6201 else
6202 libCall = spv::SMin3AMD;
6203 }
6204 break;
6205 case glslang::EOpMax3:
6206 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6207 if (isFloat)
6208 libCall = spv::FMax3AMD;
6209 else {
6210 if (isUnsigned)
6211 libCall = spv::UMax3AMD;
6212 else
6213 libCall = spv::SMax3AMD;
6214 }
6215 break;
6216 case glslang::EOpMid3:
6217 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6218 if (isFloat)
6219 libCall = spv::FMid3AMD;
6220 else {
6221 if (isUnsigned)
6222 libCall = spv::UMid3AMD;
6223 else
6224 libCall = spv::SMid3AMD;
6225 }
6226 break;
6227
6228 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006229 if (typeProxy == glslang::EbtFloat16)
6230 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08006231 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
6232 libCall = spv::InterpolateAtVertexAMD;
6233 break;
6234#endif
6235
John Kessenich140f3df2015-06-26 16:58:36 -06006236 default:
6237 return 0;
6238 }
6239
6240 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07006241 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05006242 // Use an extended instruction from the standard library.
6243 // Construct the call arguments, without modifying the original operands vector.
6244 // We might need the remaining arguments, e.g. in the EOpFrexp case.
6245 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08006246 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07006247 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07006248 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06006249 case 0:
6250 // should all be handled by visitAggregate and createNoArgOperation
6251 assert(0);
6252 return 0;
6253 case 1:
6254 // should all be handled by createUnaryOperation
6255 assert(0);
6256 return 0;
6257 case 2:
6258 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
6259 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006260 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006261 // anything 3 or over doesn't have l-value operands, so all should be consumed
6262 assert(consumedOperands == operands.size());
6263 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06006264 break;
6265 }
6266 }
6267
John Kessenich55e7d112015-11-15 21:33:39 -07006268 // Decode the return types that were structures
6269 switch (op) {
6270 case glslang::EOpAddCarry:
6271 case glslang::EOpSubBorrow:
6272 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6273 id = builder.createCompositeExtract(id, typeId0, 0);
6274 break;
6275 case glslang::EOpUMulExtended:
6276 case glslang::EOpIMulExtended:
6277 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
6278 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6279 break;
6280 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006281 {
6282 assert(operands.size() == 2);
6283 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
6284 // "exp" is floating-point type (from HLSL intrinsic)
6285 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
6286 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
6287 builder.createStore(member1, operands[1]);
6288 } else
6289 // "exp" is integer type (from GLSL built-in function)
6290 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
6291 id = builder.createCompositeExtract(id, typeId0, 0);
6292 }
John Kessenich55e7d112015-11-15 21:33:39 -07006293 break;
6294 default:
6295 break;
6296 }
6297
John Kessenich32cfd492016-02-02 12:37:46 -07006298 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006299}
6300
Rex Xu9d93a232016-05-05 12:30:44 +08006301// Intrinsics with no arguments (or no return value, and no precision).
6302spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06006303{
6304 // TODO: get the barrier operands correct
6305
6306 switch (op) {
6307 case glslang::EOpEmitVertex:
6308 builder.createNoResultOp(spv::OpEmitVertex);
6309 return 0;
6310 case glslang::EOpEndPrimitive:
6311 builder.createNoResultOp(spv::OpEndPrimitive);
6312 return 0;
6313 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006314 if (glslangIntermediate->getStage() == EShLangTessControl) {
6315 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
6316 // TODO: prefer the following, when available:
6317 // builder.createControlBarrier(spv::ScopePatch, spv::ScopePatch,
6318 // spv::MemorySemanticsPatchMask |
6319 // spv::MemorySemanticsAcquireReleaseMask);
6320 } else {
6321 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6322 spv::MemorySemanticsWorkgroupMemoryMask |
6323 spv::MemorySemanticsAcquireReleaseMask);
6324 }
John Kessenich140f3df2015-06-26 16:58:36 -06006325 return 0;
6326 case glslang::EOpMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006327 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory |
6328 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006329 return 0;
6330 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich82979362017-12-11 04:02:24 -07006331 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask |
6332 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006333 return 0;
6334 case glslang::EOpMemoryBarrierBuffer:
John Kessenich82979362017-12-11 04:02:24 -07006335 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6336 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006337 return 0;
6338 case glslang::EOpMemoryBarrierImage:
John Kessenich82979362017-12-11 04:02:24 -07006339 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask |
6340 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006341 return 0;
6342 case glslang::EOpMemoryBarrierShared:
John Kessenich82979362017-12-11 04:02:24 -07006343 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask |
6344 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006345 return 0;
6346 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006347 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
6348 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006349 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06006350 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006351 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07006352 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07006353 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006354 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07006355 case glslang::EOpDeviceMemoryBarrier:
6356 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6357 spv::MemorySemanticsImageMemoryMask |
6358 spv::MemorySemanticsAcquireReleaseMask);
6359 return 0;
6360 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
6361 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6362 spv::MemorySemanticsImageMemoryMask |
6363 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006364 return 0;
6365 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07006366 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6367 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006368 return 0;
6369 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006370 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6371 spv::MemorySemanticsWorkgroupMemoryMask |
6372 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006373 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07006374 case glslang::EOpSubgroupBarrier:
6375 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6376 spv::MemorySemanticsAcquireReleaseMask);
6377 return spv::NoResult;
6378 case glslang::EOpSubgroupMemoryBarrier:
6379 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6380 spv::MemorySemanticsAcquireReleaseMask);
6381 return spv::NoResult;
6382 case glslang::EOpSubgroupMemoryBarrierBuffer:
6383 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
6384 spv::MemorySemanticsAcquireReleaseMask);
6385 return spv::NoResult;
6386 case glslang::EOpSubgroupMemoryBarrierImage:
6387 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
6388 spv::MemorySemanticsAcquireReleaseMask);
6389 return spv::NoResult;
6390 case glslang::EOpSubgroupMemoryBarrierShared:
6391 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6392 spv::MemorySemanticsAcquireReleaseMask);
6393 return spv::NoResult;
6394 case glslang::EOpSubgroupElect: {
6395 std::vector<spv::Id> operands;
6396 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
6397 }
Rex Xu9d93a232016-05-05 12:30:44 +08006398#ifdef AMD_EXTENSIONS
6399 case glslang::EOpTime:
6400 {
6401 std::vector<spv::Id> args; // Dummy arguments
6402 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
6403 return builder.setPrecision(id, precision);
6404 }
6405#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006406 default:
Lei Zhang17535f72016-05-04 15:55:59 -04006407 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06006408 return 0;
6409 }
6410}
6411
6412spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
6413{
John Kessenich2f273362015-07-18 22:34:27 -06006414 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06006415 spv::Id id;
6416 if (symbolValues.end() != iter) {
6417 id = iter->second;
6418 return id;
6419 }
6420
6421 // it was not found, create it
6422 id = createSpvVariable(symbol);
6423 symbolValues[symbol->getId()] = id;
6424
Rex Xuc884b4a2016-06-29 15:03:44 +08006425 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006426 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
6427 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
6428 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07006429 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07006430 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06006431 if (symbol->getQualifier().hasIndex())
6432 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
6433 if (symbol->getQualifier().hasComponent())
6434 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06006435 // atomic counters use this:
6436 if (symbol->getQualifier().hasOffset())
6437 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006438 }
6439
scygan2c864272016-05-18 18:09:17 +02006440 if (symbol->getQualifier().hasLocation())
6441 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07006442 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07006443 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07006444 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06006445 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07006446 }
John Kessenich140f3df2015-06-26 16:58:36 -06006447 if (symbol->getQualifier().hasSet())
6448 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07006449 else if (IsDescriptorResource(symbol->getType())) {
6450 // default to 0
6451 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
6452 }
John Kessenich140f3df2015-06-26 16:58:36 -06006453 if (symbol->getQualifier().hasBinding())
6454 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07006455 if (symbol->getQualifier().hasAttachment())
6456 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06006457 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07006458 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06006459 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06006460 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07006461 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06006462 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07006463 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
6464 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
6465 builder.addDecoration(id, spv::DecorationXfbStride, stride);
6466 }
6467 if (symbol->getQualifier().hasXfbOffset())
6468 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006469 }
6470
Rex Xu1da878f2016-02-21 20:59:01 +08006471 if (symbol->getType().isImage()) {
6472 std::vector<spv::Decoration> memory;
6473 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
6474 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07006475 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08006476 }
6477
John Kessenich140f3df2015-06-26 16:58:36 -06006478 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06006479 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06006480 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07006481 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06006482
John Kessenich5611c6d2018-04-05 11:25:02 -06006483 // nonuniform
6484 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
6485
John Kessenichecba76f2017-01-06 00:34:48 -07006486#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08006487 if (builtIn == spv::BuiltInSampleMask) {
6488 spv::Decoration decoration;
6489 // GL_NV_sample_mask_override_coverage extension
6490 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08006491 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08006492 else
6493 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07006494 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08006495 if (decoration != spv::DecorationMax) {
6496 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
6497 }
6498 }
chaoc771d89f2017-01-13 01:10:53 -08006499 else if (builtIn == spv::BuiltInLayer) {
6500 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06006501 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006502 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08006503 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
6504 builder.addExtension(spv::E_SPV_NV_viewport_array2);
6505 }
John Kessenichb41bff62017-08-11 13:07:17 -06006506 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006507 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
6508 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08006509 builder.addCapability(spv::CapabilityShaderStereoViewNV);
6510 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
6511 }
6512 }
6513
chaoc6e5acae2016-12-20 13:28:52 -08006514 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006515 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08006516 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08006517 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
6518 }
chaoc0ad6a4e2016-12-19 16:29:34 -08006519#endif
6520
John Kessenich5d610ee2018-03-07 18:05:55 -07006521 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
6522 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
6523 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
6524 symbol->getType().getQualifier().semanticName);
6525 }
6526
John Kessenich140f3df2015-06-26 16:58:36 -06006527 return id;
6528}
6529
John Kessenich55e7d112015-11-15 21:33:39 -07006530// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07006531// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07006532//
6533// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
6534//
6535// Recursively walk the nodes. The nodes form a tree whose leaves are
6536// regular constants, which themselves are trees that createSpvConstant()
6537// recursively walks. So, this function walks the "top" of the tree:
6538// - emit specialization constant-building instructions for specConstant
6539// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04006540spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07006541{
John Kessenich7cc0e282016-03-20 00:46:02 -06006542 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07006543
qining4f4bb812016-04-03 23:55:17 -04006544 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07006545 if (! node.getQualifier().specConstant) {
6546 // hand off to the non-spec-constant path
6547 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
6548 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04006549 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07006550 nextConst, false);
6551 }
6552
6553 // We now know we have a specialization constant to build
6554
John Kessenichd94c0032016-05-30 19:29:40 -06006555 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04006556 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
6557 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
6558 std::vector<spv::Id> dimConstId;
6559 for (int dim = 0; dim < 3; ++dim) {
6560 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
6561 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07006562 if (specConst) {
6563 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
6564 glslangIntermediate->getLocalSizeSpecId(dim));
6565 }
qining4f4bb812016-04-03 23:55:17 -04006566 }
6567 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
6568 }
6569
6570 // An AST node labelled as specialization constant should be a symbol node.
6571 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
6572 if (auto* sn = node.getAsSymbolNode()) {
6573 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04006574 // Traverse the constant constructor sub tree like generating normal run-time instructions.
6575 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
6576 // will set the builder into spec constant op instruction generating mode.
6577 sub_tree->traverse(this);
6578 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04006579 } else if (auto* const_union_array = &sn->getConstArray()){
6580 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01006581 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
6582 builder.addName(id, sn->getName().c_str());
6583 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07006584 }
6585 }
qining4f4bb812016-04-03 23:55:17 -04006586
6587 // Neither a front-end constant node, nor a specialization constant node with constant union array or
6588 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04006589 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04006590 exit(1);
6591 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07006592}
6593
John Kessenich140f3df2015-06-26 16:58:36 -06006594// Use 'consts' as the flattened glslang source of scalar constants to recursively
6595// build the aggregate SPIR-V constant.
6596//
6597// If there are not enough elements present in 'consts', 0 will be substituted;
6598// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
6599//
qining08408382016-03-21 09:51:37 -04006600spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06006601{
6602 // vector of constants for SPIR-V
6603 std::vector<spv::Id> spvConsts;
6604
6605 // Type is used for struct and array constants
6606 spv::Id typeId = convertGlslangToSpvType(glslangType);
6607
6608 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006609 glslang::TType elementType(glslangType, 0);
6610 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04006611 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006612 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006613 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06006614 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04006615 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006616 } else if (glslangType.getStruct()) {
6617 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
6618 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04006619 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06006620 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06006621 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
6622 bool zero = nextConst >= consts.size();
6623 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006624 case glslang::EbtInt8:
6625 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
6626 break;
6627 case glslang::EbtUint8:
6628 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
6629 break;
6630 case glslang::EbtInt16:
6631 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
6632 break;
6633 case glslang::EbtUint16:
6634 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
6635 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006636 case glslang::EbtInt:
6637 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
6638 break;
6639 case glslang::EbtUint:
6640 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
6641 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006642 case glslang::EbtInt64:
6643 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
6644 break;
6645 case glslang::EbtUint64:
6646 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
6647 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006648 case glslang::EbtFloat:
6649 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
6650 break;
6651 case glslang::EbtDouble:
6652 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
6653 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006654 case glslang::EbtFloat16:
6655 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
6656 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006657 case glslang::EbtBool:
6658 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
6659 break;
6660 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006661 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06006662 break;
6663 }
6664 ++nextConst;
6665 }
6666 } else {
6667 // we have a non-aggregate (scalar) constant
6668 bool zero = nextConst >= consts.size();
6669 spv::Id scalar = 0;
6670 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006671 case glslang::EbtInt8:
6672 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
6673 break;
6674 case glslang::EbtUint8:
6675 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
6676 break;
6677 case glslang::EbtInt16:
6678 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
6679 break;
6680 case glslang::EbtUint16:
6681 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
6682 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006683 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07006684 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006685 break;
6686 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07006687 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006688 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006689 case glslang::EbtInt64:
6690 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
6691 break;
6692 case glslang::EbtUint64:
6693 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
6694 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006695 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07006696 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006697 break;
6698 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07006699 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006700 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006701 case glslang::EbtFloat16:
6702 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
6703 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006704 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07006705 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006706 break;
6707 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006708 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06006709 break;
6710 }
6711 ++nextConst;
6712 return scalar;
6713 }
6714
6715 return builder.makeCompositeConstant(typeId, spvConsts);
6716}
6717
John Kessenich7c1aa102015-10-15 13:29:11 -06006718// Return true if the node is a constant or symbol whose reading has no
6719// non-trivial observable cost or effect.
6720bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
6721{
6722 // don't know what this is
6723 if (node == nullptr)
6724 return false;
6725
6726 // a constant is safe
6727 if (node->getAsConstantUnion() != nullptr)
6728 return true;
6729
6730 // not a symbol means non-trivial
6731 if (node->getAsSymbolNode() == nullptr)
6732 return false;
6733
6734 // a symbol, depends on what's being read
6735 switch (node->getType().getQualifier().storage) {
6736 case glslang::EvqTemporary:
6737 case glslang::EvqGlobal:
6738 case glslang::EvqIn:
6739 case glslang::EvqInOut:
6740 case glslang::EvqConst:
6741 case glslang::EvqConstReadOnly:
6742 case glslang::EvqUniform:
6743 return true;
6744 default:
6745 return false;
6746 }
qining25262b32016-05-06 17:25:16 -04006747}
John Kessenich7c1aa102015-10-15 13:29:11 -06006748
6749// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06006750// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06006751// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06006752// Return true if trivial.
6753bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
6754{
6755 if (node == nullptr)
6756 return false;
6757
John Kessenich84cc15f2017-05-24 16:44:47 -06006758 // count non scalars as trivial, as well as anything coming from HLSL
6759 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06006760 return true;
6761
John Kessenich7c1aa102015-10-15 13:29:11 -06006762 // symbols and constants are trivial
6763 if (isTrivialLeaf(node))
6764 return true;
6765
6766 // otherwise, it needs to be a simple operation or one or two leaf nodes
6767
6768 // not a simple operation
6769 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
6770 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
6771 if (binaryNode == nullptr && unaryNode == nullptr)
6772 return false;
6773
6774 // not on leaf nodes
6775 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
6776 return false;
6777
6778 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
6779 return false;
6780 }
6781
6782 switch (node->getAsOperator()->getOp()) {
6783 case glslang::EOpLogicalNot:
6784 case glslang::EOpConvIntToBool:
6785 case glslang::EOpConvUintToBool:
6786 case glslang::EOpConvFloatToBool:
6787 case glslang::EOpConvDoubleToBool:
6788 case glslang::EOpEqual:
6789 case glslang::EOpNotEqual:
6790 case glslang::EOpLessThan:
6791 case glslang::EOpGreaterThan:
6792 case glslang::EOpLessThanEqual:
6793 case glslang::EOpGreaterThanEqual:
6794 case glslang::EOpIndexDirect:
6795 case glslang::EOpIndexDirectStruct:
6796 case glslang::EOpLogicalXor:
6797 case glslang::EOpAny:
6798 case glslang::EOpAll:
6799 return true;
6800 default:
6801 return false;
6802 }
6803}
6804
6805// Emit short-circuiting code, where 'right' is never evaluated unless
6806// the left side is true (for &&) or false (for ||).
6807spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
6808{
6809 spv::Id boolTypeId = builder.makeBoolType();
6810
6811 // emit left operand
6812 builder.clearAccessChain();
6813 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006814 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006815
6816 // Operands to accumulate OpPhi operands
6817 std::vector<spv::Id> phiOperands;
6818 // accumulate left operand's phi information
6819 phiOperands.push_back(leftId);
6820 phiOperands.push_back(builder.getBuildPoint()->getId());
6821
6822 // Make the two kinds of operation symmetric with a "!"
6823 // || => emit "if (! left) result = right"
6824 // && => emit "if ( left) result = right"
6825 //
6826 // TODO: this runtime "not" for || could be avoided by adding functionality
6827 // to 'builder' to have an "else" without an "then"
6828 if (op == glslang::EOpLogicalOr)
6829 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
6830
6831 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08006832 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06006833
6834 // emit right operand as the "then" part of the "if"
6835 builder.clearAccessChain();
6836 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006837 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006838
6839 // accumulate left operand's phi information
6840 phiOperands.push_back(rightId);
6841 phiOperands.push_back(builder.getBuildPoint()->getId());
6842
6843 // finish the "if"
6844 ifBuilder.makeEndIf();
6845
6846 // phi together the two results
6847 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
6848}
6849
Frank Henigman541f7bb2018-01-16 00:18:26 -05006850#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08006851// Return type Id of the imported set of extended instructions corresponds to the name.
6852// Import this set if it has not been imported yet.
6853spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
6854{
6855 if (extBuiltinMap.find(name) != extBuiltinMap.end())
6856 return extBuiltinMap[name];
6857 else {
Rex Xu51596642016-09-21 18:56:12 +08006858 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08006859 spv::Id extBuiltins = builder.import(name);
6860 extBuiltinMap[name] = extBuiltins;
6861 return extBuiltins;
6862 }
6863}
Frank Henigman541f7bb2018-01-16 00:18:26 -05006864#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006865
John Kessenich140f3df2015-06-26 16:58:36 -06006866}; // end anonymous namespace
6867
6868namespace glslang {
6869
John Kessenich68d78fd2015-07-12 19:28:10 -06006870void GetSpirvVersion(std::string& version)
6871{
John Kessenich9e55f632015-07-15 10:03:39 -06006872 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06006873 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07006874 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06006875 version = buf;
6876}
6877
John Kessenicha372a3e2017-11-02 22:32:14 -06006878// For low-order part of the generator's magic number. Bump up
6879// when there is a change in the style (e.g., if SSA form changes,
6880// or a different instruction sequence to do something gets used).
6881int GetSpirvGeneratorVersion()
6882{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07006883 // return 1; // start
6884 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07006885 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07006886 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07006887 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06006888 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
6889 // versions 4 and 6 each generate OpArrayLength as it has long been done
6890 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
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());
GregFb0c42b22018-05-31 16:17:18 -06006991 optimizer.RegisterPass(CreateSimplificationPass());
GregFeecb8742018-03-26 12:11:55 -06006992 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFb0c42b22018-05-31 16:17:18 -06006993 optimizer.RegisterPass(CreateVectorDCEPass());
GregF8a4848f2018-02-07 16:04:42 -07006994 optimizer.RegisterPass(CreateDeadInsertElimPass());
GregFcd1f1692017-09-21 18:40:22 -06006995 optimizer.RegisterPass(CreateAggressiveDCEPass());
6996 optimizer.RegisterPass(CreateDeadBranchElimPass());
6997 optimizer.RegisterPass(CreateBlockMergePass());
6998 optimizer.RegisterPass(CreateLocalMultiStoreElimPass());
GregFb0c42b22018-05-31 16:17:18 -06006999 optimizer.RegisterPass(CreateIfConversionPass());
7000 optimizer.RegisterPass(CreateSimplificationPass());
GregFeecb8742018-03-26 12:11:55 -06007001 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFb0c42b22018-05-31 16:17:18 -06007002 optimizer.RegisterPass(CreateVectorDCEPass());
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());
GregFb0c42b22018-05-31 16:17:18 -06007010 optimizer.RegisterPass(CreateCFGCleanupPass());
GregFcd1f1692017-09-21 18:40:22 -06007011
7012 if (!optimizer.Run(spirv.data(), spirv.size(), &spirv))
7013 return;
GregFcd1f1692017-09-21 18:40:22 -06007014 }
7015#endif
7016
John Kessenich140f3df2015-06-26 16:58:36 -06007017 glslang::GetThreadPoolAllocator().pop();
7018}
7019
7020}; // end namespace glslang