blob: 50821b8d8a2bc2e9b199304bb99d8cec970a491e [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
GregFcd1f1692017-09-21 18:40:22 -060057#ifdef ENABLE_OPT
58 #include "spirv-tools/optimizer.hpp"
59 #include "message.h"
60 #include "SPVRemapper.h"
61#endif
62
63#ifdef ENABLE_OPT
64using namespace spvtools;
65#endif
66
John Kessenich140f3df2015-06-26 16:58:36 -060067// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020068#include "../glslang/MachineIndependent/localintermediate.h"
69#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060070#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050071#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060072
John Kessenich140f3df2015-06-26 16:58:36 -060073#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050074#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040075#include <list>
76#include <map>
77#include <stack>
78#include <string>
79#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060080
81namespace {
82
qining4c912612016-04-01 10:35:16 -040083namespace {
84class SpecConstantOpModeGuard {
85public:
86 SpecConstantOpModeGuard(spv::Builder* builder)
87 : builder_(builder) {
88 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040089 }
90 ~SpecConstantOpModeGuard() {
91 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
92 : builder_->setToNormalCodeGenMode();
93 }
qining40887662016-04-03 22:20:42 -040094 void turnOnSpecConstantOpMode() {
95 builder_->setToSpecConstCodeGenMode();
96 }
qining4c912612016-04-01 10:35:16 -040097
98private:
99 spv::Builder* builder_;
100 bool previous_flag_;
101};
102}
103
John Kessenich140f3df2015-06-26 16:58:36 -0600104//
105// The main holder of information for translating glslang to SPIR-V.
106//
107// Derives from the AST walking base class.
108//
109class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
110public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700111 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
112 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700113 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600114
115 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
116 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
117 void visitConstantUnion(glslang::TIntermConstantUnion*);
118 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
119 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
120 void visitSymbol(glslang::TIntermSymbol* symbol);
121 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
122 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
123 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
124
John Kessenichfca82622016-11-26 13:23:20 -0700125 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700126 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600127
128protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700129 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
130 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
131
Rex Xu17ff3432016-10-14 17:41:45 +0800132 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800133 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100134 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700135 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700136 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
137 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenicha2858d92018-01-31 08:11:18 -0700138 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, unsigned int& dependencyLength) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600139 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich140f3df2015-06-26 16:58:36 -0600140 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
141 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600142 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
143 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
144 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600145 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700146 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600147 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600148 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
149 glslang::TLayoutPacking, const glslang::TQualifier&);
150 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
151 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700152 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700153 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800154 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600155 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700156 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700157 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
158 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700159 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
160 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100161 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600162
John Kessenich6fccb3c2016-09-19 16:01:41 -0600163 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd41993d2017-09-10 15:21:05 -0600164 bool writableParam(glslang::TStorageQualifier);
165 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600166 void makeFunctions(const glslang::TIntermSequence&);
167 void makeGlobalInitializers(const glslang::TIntermSequence&);
168 void visitFunctions(const glslang::TIntermSequence&);
169 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800170 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600171 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
172 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600173 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
174
qining25262b32016-05-06 17:25:16 -0400175 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
176 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
177 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800178 spv::Id createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800179 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -0700180 spv::Id createConversionOperation(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600181 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800182 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 +0800183 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800184 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700185 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600186 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 +0800187 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600188 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
qining08408382016-03-21 09:51:37 -0400189 spv::Id createSpvConstant(const glslang::TIntermTyped&);
190 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600191 bool isTrivialLeaf(const glslang::TIntermTyped* node);
192 bool isTrivial(const glslang::TIntermTyped* node);
193 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500194#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800195 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500196#endif
John Kessenich66011cb2018-03-06 16:12:04 -0700197 void addPre13Extension(const char* ext)
198 {
199 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
200 builder.addExtension(ext);
201 }
John Kessenich140f3df2015-06-26 16:58:36 -0600202
John Kessenich121853f2017-05-31 17:11:16 -0600203 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600204 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600205 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700206 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600207 int sequenceDepth;
208
Lei Zhang17535f72016-05-04 15:55:59 -0400209 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400210
John Kessenich140f3df2015-06-26 16:58:36 -0600211 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
212 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700213 bool inEntryPoint;
214 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700215 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 -0700216 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600217 const glslang::TIntermediate* glslangIntermediate;
218 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800219 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600220
John Kessenich2f273362015-07-18 22:34:27 -0600221 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600222 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600223 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700224 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700225 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
226 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600227 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700228 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
John Kessenich140f3df2015-06-26 16:58:36 -0600229};
230
231//
232// Helper functions for translating glslang representations to SPIR-V enumerants.
233//
234
235// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700236spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600237{
John Kessenich66e2faf2016-03-12 18:34:36 -0700238 switch (source) {
239 case glslang::EShSourceGlsl:
240 switch (profile) {
241 case ENoProfile:
242 case ECoreProfile:
243 case ECompatibilityProfile:
244 return spv::SourceLanguageGLSL;
245 case EEsProfile:
246 return spv::SourceLanguageESSL;
247 default:
248 return spv::SourceLanguageUnknown;
249 }
250 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600251 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600252 default:
253 return spv::SourceLanguageUnknown;
254 }
255}
256
257// Translate glslang language (stage) to SPIR-V execution model.
258spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
259{
260 switch (stage) {
261 case EShLangVertex: return spv::ExecutionModelVertex;
262 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
263 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
264 case EShLangGeometry: return spv::ExecutionModelGeometry;
265 case EShLangFragment: return spv::ExecutionModelFragment;
266 case EShLangCompute: return spv::ExecutionModelGLCompute;
267 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700268 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600269 return spv::ExecutionModelFragment;
270 }
271}
272
John Kessenich140f3df2015-06-26 16:58:36 -0600273// Translate glslang sampler type to SPIR-V dimensionality.
274spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
275{
276 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700277 case glslang::Esd1D: return spv::Dim1D;
278 case glslang::Esd2D: return spv::Dim2D;
279 case glslang::Esd3D: return spv::Dim3D;
280 case glslang::EsdCube: return spv::DimCube;
281 case glslang::EsdRect: return spv::DimRect;
282 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700283 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600284 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700285 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600286 return spv::Dim2D;
287 }
288}
289
John Kessenichf6640762016-08-01 19:44:00 -0600290// Translate glslang precision to SPIR-V precision decorations.
291spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600292{
John Kessenichf6640762016-08-01 19:44:00 -0600293 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700294 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600295 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600296 default:
297 return spv::NoPrecision;
298 }
299}
300
John Kessenichf6640762016-08-01 19:44:00 -0600301// Translate glslang type to SPIR-V precision decorations.
302spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
303{
304 return TranslatePrecisionDecoration(type.getQualifier().precision);
305}
306
John Kessenich140f3df2015-06-26 16:58:36 -0600307// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600308spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600309{
310 if (type.getBasicType() == glslang::EbtBlock) {
311 switch (type.getQualifier().storage) {
312 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600313 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600314 case glslang::EvqVaryingIn: return spv::DecorationBlock;
315 case glslang::EvqVaryingOut: return spv::DecorationBlock;
316 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700317 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600318 break;
319 }
320 }
321
John Kessenich4016e382016-07-15 11:53:56 -0600322 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600323}
324
Rex Xu1da878f2016-02-21 20:59:01 +0800325// Translate glslang type to SPIR-V memory decorations.
326void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
327{
328 if (qualifier.coherent)
329 memory.push_back(spv::DecorationCoherent);
330 if (qualifier.volatil)
331 memory.push_back(spv::DecorationVolatile);
332 if (qualifier.restrict)
333 memory.push_back(spv::DecorationRestrict);
334 if (qualifier.readonly)
335 memory.push_back(spv::DecorationNonWritable);
336 if (qualifier.writeonly)
337 memory.push_back(spv::DecorationNonReadable);
338}
339
John Kessenich140f3df2015-06-26 16:58:36 -0600340// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700341spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600342{
343 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700344 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600345 case glslang::ElmRowMajor:
346 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700347 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600348 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700349 default:
350 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600351 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600352 }
353 } else {
354 switch (type.getBasicType()) {
355 default:
John Kessenich4016e382016-07-15 11:53:56 -0600356 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600357 break;
358 case glslang::EbtBlock:
359 switch (type.getQualifier().storage) {
360 case glslang::EvqUniform:
361 case glslang::EvqBuffer:
362 switch (type.getQualifier().layoutPacking) {
363 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600364 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
365 default:
John Kessenich4016e382016-07-15 11:53:56 -0600366 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600367 }
368 case glslang::EvqVaryingIn:
369 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700370 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600371 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600372 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700373 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600374 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600375 }
376 }
377 }
378}
379
380// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600381// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700382// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800383spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600384{
Rex Xubbceed72016-05-21 09:40:44 +0800385 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700386 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600387 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800388 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700389 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700390 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600391 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800392#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800393 else if (qualifier.explicitInterp) {
394 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800395 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800396 }
Rex Xu9d93a232016-05-05 12:30:44 +0800397#endif
Rex Xubbceed72016-05-21 09:40:44 +0800398 else
John Kessenich4016e382016-07-15 11:53:56 -0600399 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800400}
401
402// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600403// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800404// should be applied.
405spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
406{
407 if (qualifier.patch)
408 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700409 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600410 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700411 else if (qualifier.sample) {
412 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600413 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700414 } else
John Kessenich4016e382016-07-15 11:53:56 -0600415 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600416}
417
John Kessenich92187592016-02-01 13:45:25 -0700418// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700419spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600420{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700421 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600422 return spv::DecorationInvariant;
423 else
John Kessenich4016e382016-07-15 11:53:56 -0600424 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600425}
426
qining9220dbb2016-05-04 17:34:38 -0400427// If glslang type is noContraction, return SPIR-V NoContraction decoration.
428spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
429{
430 if (qualifier.noContraction)
431 return spv::DecorationNoContraction;
432 else
John Kessenich4016e382016-07-15 11:53:56 -0600433 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400434}
435
David Netoa901ffe2016-06-08 14:11:40 +0100436// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
437// associated capabilities when required. For some built-in variables, a capability
438// is generated only when using the variable in an executable instruction, but not when
439// just declaring a struct member variable with it. This is true for PointSize,
440// ClipDistance, and CullDistance.
441spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600442{
443 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700444 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600445 // Defer adding the capability until the built-in is actually used.
446 if (! memberDeclaration) {
447 switch (glslangIntermediate->getStage()) {
448 case EShLangGeometry:
449 builder.addCapability(spv::CapabilityGeometryPointSize);
450 break;
451 case EShLangTessControl:
452 case EShLangTessEvaluation:
453 builder.addCapability(spv::CapabilityTessellationPointSize);
454 break;
455 default:
456 break;
457 }
John Kessenich92187592016-02-01 13:45:25 -0700458 }
459 return spv::BuiltInPointSize;
460
John Kessenichebb50532016-05-16 19:22:05 -0600461 // These *Distance capabilities logically belong here, but if the member is declared and
462 // then never used, consumers of SPIR-V prefer the capability not be declared.
463 // They are now generated when used, rather than here when declared.
464 // Potentially, the specification should be more clear what the minimum
465 // use needed is to trigger the capability.
466 //
John Kessenich92187592016-02-01 13:45:25 -0700467 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100468 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800469 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700470 return spv::BuiltInClipDistance;
471
472 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100473 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800474 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700475 return spv::BuiltInCullDistance;
476
477 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600478 builder.addCapability(spv::CapabilityMultiViewport);
479 if (glslangIntermediate->getStage() == EShLangVertex ||
480 glslangIntermediate->getStage() == EShLangTessControl ||
481 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800482
John Kessenichba6a3c22017-09-13 13:22:50 -0600483 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
484 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800485 }
John Kessenich92187592016-02-01 13:45:25 -0700486 return spv::BuiltInViewportIndex;
487
John Kessenich5e801132016-02-15 11:09:46 -0700488 case glslang::EbvSampleId:
489 builder.addCapability(spv::CapabilitySampleRateShading);
490 return spv::BuiltInSampleId;
491
492 case glslang::EbvSamplePosition:
493 builder.addCapability(spv::CapabilitySampleRateShading);
494 return spv::BuiltInSamplePosition;
495
496 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700497 return spv::BuiltInSampleMask;
498
John Kessenich78a45572016-07-08 14:05:15 -0600499 case glslang::EbvLayer:
John Kessenichba6a3c22017-09-13 13:22:50 -0600500 builder.addCapability(spv::CapabilityGeometry);
501 if (glslangIntermediate->getStage() == EShLangVertex ||
502 glslangIntermediate->getStage() == EShLangTessControl ||
503 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800504
John Kessenichba6a3c22017-09-13 13:22:50 -0600505 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
506 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800507 }
John Kessenich78a45572016-07-08 14:05:15 -0600508 return spv::BuiltInLayer;
509
John Kessenich140f3df2015-06-26 16:58:36 -0600510 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600511 case glslang::EbvVertexId: return spv::BuiltInVertexId;
512 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700513 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
514 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800515
John Kessenichda581a22015-10-14 14:10:30 -0600516 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700517 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800518 builder.addCapability(spv::CapabilityDrawParameters);
519 return spv::BuiltInBaseVertex;
520
John Kessenichda581a22015-10-14 14:10:30 -0600521 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700522 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800523 builder.addCapability(spv::CapabilityDrawParameters);
524 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200525
John Kessenichda581a22015-10-14 14:10:30 -0600526 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700527 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800528 builder.addCapability(spv::CapabilityDrawParameters);
529 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200530
531 case glslang::EbvPrimitiveId:
532 if (glslangIntermediate->getStage() == EShLangFragment)
533 builder.addCapability(spv::CapabilityGeometry);
534 return spv::BuiltInPrimitiveId;
535
Rex Xu37cdcee2017-06-29 17:46:34 +0800536 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800537 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
538 builder.addCapability(spv::CapabilityStencilExportEXT);
539 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800540
John Kessenich140f3df2015-06-26 16:58:36 -0600541 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600542 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
543 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
544 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
545 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
546 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
547 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
548 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600549 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
550 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
551 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
552 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
553 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
554 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
555 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
556 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800557
Rex Xu574ab042016-04-14 16:53:07 +0800558 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800559 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800560 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
561 return spv::BuiltInSubgroupSize;
562
Rex Xu574ab042016-04-14 16:53:07 +0800563 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800564 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800565 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
566 return spv::BuiltInSubgroupLocalInvocationId;
567
Rex Xu574ab042016-04-14 16:53:07 +0800568 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800569 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
570 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
571 return spv::BuiltInSubgroupEqMaskKHR;
572
Rex Xu574ab042016-04-14 16:53:07 +0800573 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800574 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
575 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
576 return spv::BuiltInSubgroupGeMaskKHR;
577
Rex Xu574ab042016-04-14 16:53:07 +0800578 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800579 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
580 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
581 return spv::BuiltInSubgroupGtMaskKHR;
582
Rex Xu574ab042016-04-14 16:53:07 +0800583 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800584 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
585 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
586 return spv::BuiltInSubgroupLeMaskKHR;
587
Rex Xu574ab042016-04-14 16:53:07 +0800588 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800589 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
590 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
591 return spv::BuiltInSubgroupLtMaskKHR;
592
John Kessenich66011cb2018-03-06 16:12:04 -0700593 case glslang::EbvNumSubgroups:
594 builder.addCapability(spv::CapabilityGroupNonUniform);
595 return spv::BuiltInNumSubgroups;
596
597 case glslang::EbvSubgroupID:
598 builder.addCapability(spv::CapabilityGroupNonUniform);
599 return spv::BuiltInSubgroupId;
600
601 case glslang::EbvSubgroupSize2:
602 builder.addCapability(spv::CapabilityGroupNonUniform);
603 return spv::BuiltInSubgroupSize;
604
605 case glslang::EbvSubgroupInvocation2:
606 builder.addCapability(spv::CapabilityGroupNonUniform);
607 return spv::BuiltInSubgroupLocalInvocationId;
608
609 case glslang::EbvSubgroupEqMask2:
610 builder.addCapability(spv::CapabilityGroupNonUniform);
611 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
612 return spv::BuiltInSubgroupEqMask;
613
614 case glslang::EbvSubgroupGeMask2:
615 builder.addCapability(spv::CapabilityGroupNonUniform);
616 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
617 return spv::BuiltInSubgroupGeMask;
618
619 case glslang::EbvSubgroupGtMask2:
620 builder.addCapability(spv::CapabilityGroupNonUniform);
621 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
622 return spv::BuiltInSubgroupGtMask;
623
624 case glslang::EbvSubgroupLeMask2:
625 builder.addCapability(spv::CapabilityGroupNonUniform);
626 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
627 return spv::BuiltInSubgroupLeMask;
628
629 case glslang::EbvSubgroupLtMask2:
630 builder.addCapability(spv::CapabilityGroupNonUniform);
631 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
632 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800633#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800634 case glslang::EbvBaryCoordNoPersp:
635 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
636 return spv::BuiltInBaryCoordNoPerspAMD;
637
638 case glslang::EbvBaryCoordNoPerspCentroid:
639 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
640 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
641
642 case glslang::EbvBaryCoordNoPerspSample:
643 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
644 return spv::BuiltInBaryCoordNoPerspSampleAMD;
645
646 case glslang::EbvBaryCoordSmooth:
647 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
648 return spv::BuiltInBaryCoordSmoothAMD;
649
650 case glslang::EbvBaryCoordSmoothCentroid:
651 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
652 return spv::BuiltInBaryCoordSmoothCentroidAMD;
653
654 case glslang::EbvBaryCoordSmoothSample:
655 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
656 return spv::BuiltInBaryCoordSmoothSampleAMD;
657
658 case glslang::EbvBaryCoordPullModel:
659 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
660 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800661#endif
chaoc771d89f2017-01-13 01:10:53 -0800662
John Kessenich6c8aaac2017-02-27 01:20:51 -0700663 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700664 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700665 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700666 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700667
668 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700669 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700670 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700671 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700672
chaoc771d89f2017-01-13 01:10:53 -0800673#ifdef NV_EXTENSIONS
674 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800675 if (!memberDeclaration) {
676 builder.addExtension(spv::E_SPV_NV_viewport_array2);
677 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
678 }
chaoc771d89f2017-01-13 01:10:53 -0800679 return spv::BuiltInViewportMaskNV;
680 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800681 if (!memberDeclaration) {
682 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
683 builder.addCapability(spv::CapabilityShaderStereoViewNV);
684 }
chaoc771d89f2017-01-13 01:10:53 -0800685 return spv::BuiltInSecondaryPositionNV;
686 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800687 if (!memberDeclaration) {
688 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
689 builder.addCapability(spv::CapabilityShaderStereoViewNV);
690 }
chaoc771d89f2017-01-13 01:10:53 -0800691 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800692 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800693 if (!memberDeclaration) {
694 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
695 builder.addCapability(spv::CapabilityPerViewAttributesNV);
696 }
chaocdf3956c2017-02-14 14:52:34 -0800697 return spv::BuiltInPositionPerViewNV;
698 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800699 if (!memberDeclaration) {
700 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
701 builder.addCapability(spv::CapabilityPerViewAttributesNV);
702 }
chaocdf3956c2017-02-14 14:52:34 -0800703 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700704 case glslang::EbvFragFullyCoveredNV:
705 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
706 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
707 return spv::BuiltInFullyCoveredEXT;
chaoc771d89f2017-01-13 01:10:53 -0800708#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800709 default:
710 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600711 }
712}
713
Rex Xufc618912015-09-09 16:42:49 +0800714// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700715spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800716{
717 assert(type.getBasicType() == glslang::EbtSampler);
718
John Kessenich5d0fa972016-02-15 11:57:00 -0700719 // Check for capabilities
720 switch (type.getQualifier().layoutFormat) {
721 case glslang::ElfRg32f:
722 case glslang::ElfRg16f:
723 case glslang::ElfR11fG11fB10f:
724 case glslang::ElfR16f:
725 case glslang::ElfRgba16:
726 case glslang::ElfRgb10A2:
727 case glslang::ElfRg16:
728 case glslang::ElfRg8:
729 case glslang::ElfR16:
730 case glslang::ElfR8:
731 case glslang::ElfRgba16Snorm:
732 case glslang::ElfRg16Snorm:
733 case glslang::ElfRg8Snorm:
734 case glslang::ElfR16Snorm:
735 case glslang::ElfR8Snorm:
736
737 case glslang::ElfRg32i:
738 case glslang::ElfRg16i:
739 case glslang::ElfRg8i:
740 case glslang::ElfR16i:
741 case glslang::ElfR8i:
742
743 case glslang::ElfRgb10a2ui:
744 case glslang::ElfRg32ui:
745 case glslang::ElfRg16ui:
746 case glslang::ElfRg8ui:
747 case glslang::ElfR16ui:
748 case glslang::ElfR8ui:
749 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
750 break;
751
752 default:
753 break;
754 }
755
756 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800757 switch (type.getQualifier().layoutFormat) {
758 case glslang::ElfNone: return spv::ImageFormatUnknown;
759 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
760 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
761 case glslang::ElfR32f: return spv::ImageFormatR32f;
762 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
763 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
764 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
765 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
766 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
767 case glslang::ElfR16f: return spv::ImageFormatR16f;
768 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
769 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
770 case glslang::ElfRg16: return spv::ImageFormatRg16;
771 case glslang::ElfRg8: return spv::ImageFormatRg8;
772 case glslang::ElfR16: return spv::ImageFormatR16;
773 case glslang::ElfR8: return spv::ImageFormatR8;
774 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
775 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
776 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
777 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
778 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
779 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
780 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
781 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
782 case glslang::ElfR32i: return spv::ImageFormatR32i;
783 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
784 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
785 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
786 case glslang::ElfR16i: return spv::ImageFormatR16i;
787 case glslang::ElfR8i: return spv::ImageFormatR8i;
788 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
789 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
790 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
791 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
792 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
793 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
794 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
795 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
796 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
797 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600798 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800799 }
800}
801
John Kesseniche18fd202018-01-30 11:01:39 -0700802spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +0800803{
John Kesseniche18fd202018-01-30 11:01:39 -0700804 if (selectionNode.getFlatten())
805 return spv::SelectionControlFlattenMask;
806 if (selectionNode.getDontFlatten())
807 return spv::SelectionControlDontFlattenMask;
808 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +0800809}
810
John Kesseniche18fd202018-01-30 11:01:39 -0700811spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -0600812{
John Kesseniche18fd202018-01-30 11:01:39 -0700813 if (switchNode.getFlatten())
814 return spv::SelectionControlFlattenMask;
815 if (switchNode.getDontFlatten())
816 return spv::SelectionControlDontFlattenMask;
817 return spv::SelectionControlMaskNone;
818}
819
John Kessenicha2858d92018-01-31 08:11:18 -0700820// return a non-0 dependency if the dependency argument must be set
821spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
822 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -0700823{
824 spv::LoopControlMask control = spv::LoopControlMaskNone;
825
826 if (loopNode.getDontUnroll())
827 control = control | spv::LoopControlDontUnrollMask;
828 if (loopNode.getUnroll())
829 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -0700830 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -0700831 control = control | spv::LoopControlDependencyInfiniteMask;
832 else if (loopNode.getLoopDependency() > 0) {
833 control = control | spv::LoopControlDependencyLengthMask;
834 dependencyLength = loopNode.getLoopDependency();
835 }
John Kesseniche18fd202018-01-30 11:01:39 -0700836
837 return control;
steve-lunargf1709e72017-05-02 20:14:50 -0600838}
839
John Kessenicha5c5fb62017-05-05 05:09:58 -0600840// Translate glslang type to SPIR-V storage class.
841spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
842{
843 if (type.getQualifier().isPipeInput())
844 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600845 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -0600846 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600847
848 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
849 type.getQualifier().storage == glslang::EvqUniform) {
850 if (type.getBasicType() == glslang::EbtAtomicUint)
851 return spv::StorageClassAtomicCounter;
852 if (type.containsOpaque())
853 return spv::StorageClassUniformConstant;
854 }
855
856 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -0700857 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -0600858 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600859 }
860
861 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600862 if (type.getQualifier().layoutPushConstant)
863 return spv::StorageClassPushConstant;
864 if (type.getBasicType() == glslang::EbtBlock)
865 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600866 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600867 }
John Kessenichbed4e4f2017-09-08 02:38:07 -0600868
869 switch (type.getQualifier().storage) {
870 case glslang::EvqShared: return spv::StorageClassWorkgroup;
871 case glslang::EvqGlobal: return spv::StorageClassPrivate;
872 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
873 case glslang::EvqTemporary: return spv::StorageClassFunction;
874 default:
875 assert(0);
876 break;
877 }
878
879 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600880}
881
qining25262b32016-05-06 17:25:16 -0400882// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700883// descriptor set.
884bool IsDescriptorResource(const glslang::TType& type)
885{
John Kessenichf7497e22016-03-08 21:36:22 -0700886 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700887 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700888 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700889
890 // non block...
891 // basically samplerXXX/subpass/sampler/texture are all included
892 // if they are the global-scope-class, not the function parameter
893 // (or local, if they ever exist) class.
894 if (type.getBasicType() == glslang::EbtSampler)
895 return type.getQualifier().isUniformOrBuffer();
896
897 // None of the above.
898 return false;
899}
900
John Kesseniche0b6cad2015-12-24 10:30:13 -0700901void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
902{
903 if (child.layoutMatrix == glslang::ElmNone)
904 child.layoutMatrix = parent.layoutMatrix;
905
906 if (parent.invariant)
907 child.invariant = true;
908 if (parent.nopersp)
909 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800910#ifdef AMD_EXTENSIONS
911 if (parent.explicitInterp)
912 child.explicitInterp = true;
913#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700914 if (parent.flat)
915 child.flat = true;
916 if (parent.centroid)
917 child.centroid = true;
918 if (parent.patch)
919 child.patch = true;
920 if (parent.sample)
921 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800922 if (parent.coherent)
923 child.coherent = true;
924 if (parent.volatil)
925 child.volatil = true;
926 if (parent.restrict)
927 child.restrict = true;
928 if (parent.readonly)
929 child.readonly = true;
930 if (parent.writeonly)
931 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700932}
933
John Kessenichf2b7f332016-09-01 17:05:23 -0600934bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700935{
John Kessenich7b9fa252016-01-21 18:56:57 -0700936 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600937 // - struct members might inherit from a struct declaration
938 // (note that non-block structs don't explicitly inherit,
939 // only implicitly, meaning no decoration involved)
940 // - affect decorations on the struct members
941 // (note smooth does not, and expecting something like volatile
942 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700943 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600944 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700945}
946
John Kessenich140f3df2015-06-26 16:58:36 -0600947//
948// Implement the TGlslangToSpvTraverser class.
949//
950
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700951TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -0600952 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
953 : TIntermTraverser(true, false, true),
954 options(options),
955 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600956 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700957 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700958 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600959 glslangIntermediate(glslangIntermediate)
960{
961 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
962
963 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -0600964 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
965 glslangIntermediate->getVersion());
966
John Kessenich121853f2017-05-31 17:11:16 -0600967 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -0600968 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -0600969 builder.setSourceFile(glslangIntermediate->getSourceFile());
970
971 // Set the source shader's text. If for SPV version 1.0, include
972 // a preamble in comments stating the OpModuleProcessed instructions.
973 // Otherwise, emit those as actual instructions.
974 std::string text;
975 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
976 for (int p = 0; p < (int)processes.size(); ++p) {
977 if (glslangIntermediate->getSpv().spv < 0x00010100) {
978 text.append("// OpModuleProcessed ");
979 text.append(processes[p]);
980 text.append("\n");
981 } else
982 builder.addModuleProcessed(processes[p]);
983 }
984 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
985 text.append("#line 1\n");
986 text.append(glslangIntermediate->getSourceText());
987 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -0600988 }
John Kessenich140f3df2015-06-26 16:58:36 -0600989 stdBuiltins = builder.import("GLSL.std.450");
990 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600991 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
992 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600993
994 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600995 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
996 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600997 builder.addSourceExtension(it->c_str());
998
999 // Add the top-level modes for this shader.
1000
John Kessenich92187592016-02-01 13:45:25 -07001001 if (glslangIntermediate->getXfbMode()) {
1002 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001003 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001004 }
John Kessenich140f3df2015-06-26 16:58:36 -06001005
1006 unsigned int mode;
1007 switch (glslangIntermediate->getStage()) {
1008 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001009 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001010 break;
1011
steve-lunarge7412492017-03-23 11:56:07 -06001012 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001013 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001014 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001015
steve-lunarge7412492017-03-23 11:56:07 -06001016 glslang::TLayoutGeometry primitive;
1017
1018 if (glslangIntermediate->getStage() == EShLangTessControl) {
1019 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1020 primitive = glslangIntermediate->getOutputPrimitive();
1021 } else {
1022 primitive = glslangIntermediate->getInputPrimitive();
1023 }
1024
1025 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001026 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1027 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1028 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001029 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001030 }
John Kessenich4016e382016-07-15 11:53:56 -06001031 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001032 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1033
John Kesseniche6903322015-10-13 16:29:02 -06001034 switch (glslangIntermediate->getVertexSpacing()) {
1035 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1036 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1037 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001038 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001039 }
John Kessenich4016e382016-07-15 11:53:56 -06001040 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001041 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1042
1043 switch (glslangIntermediate->getVertexOrder()) {
1044 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1045 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001046 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001047 }
John Kessenich4016e382016-07-15 11:53:56 -06001048 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001049 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1050
1051 if (glslangIntermediate->getPointMode())
1052 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001053 break;
1054
1055 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001056 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001057 switch (glslangIntermediate->getInputPrimitive()) {
1058 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1059 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1060 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001061 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001062 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001063 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001064 }
John Kessenich4016e382016-07-15 11:53:56 -06001065 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001066 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001067
John Kessenich140f3df2015-06-26 16:58:36 -06001068 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1069
1070 switch (glslangIntermediate->getOutputPrimitive()) {
1071 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1072 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1073 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001074 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001075 }
John Kessenich4016e382016-07-15 11:53:56 -06001076 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001077 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1078 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1079 break;
1080
1081 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001082 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001083 if (glslangIntermediate->getPixelCenterInteger())
1084 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001085
John Kessenich140f3df2015-06-26 16:58:36 -06001086 if (glslangIntermediate->getOriginUpperLeft())
1087 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001088 else
1089 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001090
1091 if (glslangIntermediate->getEarlyFragmentTests())
1092 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1093
chaocc1204522017-06-30 17:14:30 -07001094 if (glslangIntermediate->getPostDepthCoverage()) {
1095 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1096 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1097 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1098 }
1099
John Kesseniche6903322015-10-13 16:29:02 -06001100 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001101 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1102 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001103 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001104 }
John Kessenich4016e382016-07-15 11:53:56 -06001105 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001106 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1107
1108 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1109 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001110 break;
1111
1112 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001113 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001114 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1115 glslangIntermediate->getLocalSize(1),
1116 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001117 break;
1118
1119 default:
1120 break;
1121 }
John Kessenich140f3df2015-06-26 16:58:36 -06001122}
1123
John Kessenichfca82622016-11-26 13:23:20 -07001124// Finish creating SPV, after the traversal is complete.
1125void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001126{
John Kessenich517fe7a2016-11-26 13:31:47 -07001127 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001128 builder.setBuildPoint(shaderEntry->getLastBlock());
1129 builder.leaveFunction();
1130 }
1131
John Kessenich7ba63412015-12-20 17:37:07 -07001132 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001133 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1134 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001135
qiningda397332016-03-09 19:54:03 -05001136 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001137}
1138
John Kessenichfca82622016-11-26 13:23:20 -07001139// Write the SPV into 'out'.
1140void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001141{
John Kessenichfca82622016-11-26 13:23:20 -07001142 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001143}
1144
1145//
1146// Implement the traversal functions.
1147//
1148// Return true from interior nodes to have the external traversal
1149// continue on to children. Return false if children were
1150// already processed.
1151//
1152
1153//
qining25262b32016-05-06 17:25:16 -04001154// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001155// - uniform/input reads
1156// - output writes
1157// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1158// - something simple that degenerates into the last bullet
1159//
1160void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1161{
qining75d1d802016-04-06 14:42:01 -04001162 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1163 if (symbol->getType().getQualifier().isSpecConstant())
1164 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1165
John Kessenich140f3df2015-06-26 16:58:36 -06001166 // getSymbolId() will set up all the IO decorations on the first call.
1167 // Formal function parameters were mapped during makeFunctions().
1168 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001169
1170 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1171 if (builder.isPointer(id)) {
1172 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001173 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1174 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1175 iOSet.insert(id);
1176 }
John Kessenich7ba63412015-12-20 17:37:07 -07001177 }
1178
1179 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001180 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001181 // Prepare to generate code for the access
1182
1183 // L-value chains will be computed left to right. We're on the symbol now,
1184 // which is the left-most part of the access chain, so now is "clear" time,
1185 // followed by setting the base.
1186 builder.clearAccessChain();
1187
1188 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001189 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001190 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001191 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001192 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001193 // These are also pure R-values.
1194 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001195 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001196 builder.setAccessChainRValue(id);
1197 else
1198 builder.setAccessChainLValue(id);
1199 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001200
1201 // Process linkage-only nodes for any special additional interface work.
1202 if (linkageOnly) {
1203 if (glslangIntermediate->getHlslFunctionality1()) {
1204 // Map implicit counter buffers to their originating buffers, which should have been
1205 // seen by now, given earlier pruning of unused counters, and preservation of order
1206 // of declaration.
1207 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1208 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1209 // Save possible originating buffers for counter buffers, keyed by
1210 // making the potential counter-buffer name.
1211 std::string keyName = symbol->getName().c_str();
1212 keyName = glslangIntermediate->addCounterBufferName(keyName);
1213 counterOriginator[keyName] = symbol;
1214 } else {
1215 // Handle a counter buffer, by finding the saved originating buffer.
1216 std::string keyName = symbol->getName().c_str();
1217 auto it = counterOriginator.find(keyName);
1218 if (it != counterOriginator.end()) {
1219 id = getSymbolId(it->second);
1220 if (id != spv::NoResult) {
1221 spv::Id counterId = getSymbolId(symbol);
1222 if (counterId != spv::NoResult)
1223 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
1224 }
1225 }
1226 }
1227 }
1228 }
1229 }
John Kessenich140f3df2015-06-26 16:58:36 -06001230}
1231
1232bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1233{
John Kesseniche485c7a2017-05-31 18:50:53 -06001234 builder.setLine(node->getLoc().line);
1235
qining40887662016-04-03 22:20:42 -04001236 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1237 if (node->getType().getQualifier().isSpecConstant())
1238 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1239
John Kessenich140f3df2015-06-26 16:58:36 -06001240 // First, handle special cases
1241 switch (node->getOp()) {
1242 case glslang::EOpAssign:
1243 case glslang::EOpAddAssign:
1244 case glslang::EOpSubAssign:
1245 case glslang::EOpMulAssign:
1246 case glslang::EOpVectorTimesMatrixAssign:
1247 case glslang::EOpVectorTimesScalarAssign:
1248 case glslang::EOpMatrixTimesScalarAssign:
1249 case glslang::EOpMatrixTimesMatrixAssign:
1250 case glslang::EOpDivAssign:
1251 case glslang::EOpModAssign:
1252 case glslang::EOpAndAssign:
1253 case glslang::EOpInclusiveOrAssign:
1254 case glslang::EOpExclusiveOrAssign:
1255 case glslang::EOpLeftShiftAssign:
1256 case glslang::EOpRightShiftAssign:
1257 // A bin-op assign "a += b" means the same thing as "a = a + b"
1258 // where a is evaluated before b. For a simple assignment, GLSL
1259 // says to evaluate the left before the right. So, always, left
1260 // node then right node.
1261 {
1262 // get the left l-value, save it away
1263 builder.clearAccessChain();
1264 node->getLeft()->traverse(this);
1265 spv::Builder::AccessChain lValue = builder.getAccessChain();
1266
1267 // evaluate the right
1268 builder.clearAccessChain();
1269 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001270 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001271
1272 if (node->getOp() != glslang::EOpAssign) {
1273 // the left is also an r-value
1274 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001275 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001276
1277 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001278 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001279 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001280 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1281 node->getType().getBasicType());
1282
1283 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001284 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001285 }
1286
1287 // store the result
1288 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001289 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001290
1291 // assignments are expressions having an rValue after they are evaluated...
1292 builder.clearAccessChain();
1293 builder.setAccessChainRValue(rValue);
1294 }
1295 return false;
1296 case glslang::EOpIndexDirect:
1297 case glslang::EOpIndexDirectStruct:
1298 {
1299 // Get the left part of the access chain.
1300 node->getLeft()->traverse(this);
1301
1302 // Add the next element in the chain
1303
David Netoa901ffe2016-06-08 14:11:40 +01001304 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001305 if (! node->getLeft()->getType().isArray() &&
1306 node->getLeft()->getType().isVector() &&
1307 node->getOp() == glslang::EOpIndexDirect) {
1308 // This is essentially a hard-coded vector swizzle of size 1,
1309 // so short circuit the access-chain stuff with a swizzle.
1310 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001311 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001312 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001313 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001314 int spvIndex = glslangIndex;
1315 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1316 node->getOp() == glslang::EOpIndexDirectStruct)
1317 {
1318 // This may be, e.g., an anonymous block-member selection, which generally need
1319 // index remapping due to hidden members in anonymous blocks.
1320 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1321 assert(remapper.size() > 0);
1322 spvIndex = remapper[glslangIndex];
1323 }
John Kessenichebb50532016-05-16 19:22:05 -06001324
David Netoa901ffe2016-06-08 14:11:40 +01001325 // normal case for indexing array or structure or block
1326 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1327
1328 // Add capabilities here for accessing PointSize and clip/cull distance.
1329 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001330 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001331 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001332 }
1333 }
1334 return false;
1335 case glslang::EOpIndexIndirect:
1336 {
1337 // Structure or array or vector indirection.
1338 // Will use native SPIR-V access-chain for struct and array indirection;
1339 // matrices are arrays of vectors, so will also work for a matrix.
1340 // Will use the access chain's 'component' for variable index into a vector.
1341
1342 // This adapter is building access chains left to right.
1343 // Set up the access chain to the left.
1344 node->getLeft()->traverse(this);
1345
1346 // save it so that computing the right side doesn't trash it
1347 spv::Builder::AccessChain partial = builder.getAccessChain();
1348
1349 // compute the next index in the chain
1350 builder.clearAccessChain();
1351 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001352 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001353
1354 // restore the saved access chain
1355 builder.setAccessChain(partial);
1356
1357 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001358 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001359 else
John Kessenichfa668da2015-09-13 14:46:30 -06001360 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001361 }
1362 return false;
1363 case glslang::EOpVectorSwizzle:
1364 {
1365 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001366 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001367 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001368 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001369 }
1370 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001371 case glslang::EOpMatrixSwizzle:
1372 logger->missingFunctionality("matrix swizzle");
1373 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001374 case glslang::EOpLogicalOr:
1375 case glslang::EOpLogicalAnd:
1376 {
1377
1378 // These may require short circuiting, but can sometimes be done as straight
1379 // binary operations. The right operand must be short circuited if it has
1380 // side effects, and should probably be if it is complex.
1381 if (isTrivial(node->getRight()->getAsTyped()))
1382 break; // handle below as a normal binary operation
1383 // otherwise, we need to do dynamic short circuiting on the right operand
1384 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1385 builder.clearAccessChain();
1386 builder.setAccessChainRValue(result);
1387 }
1388 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001389 default:
1390 break;
1391 }
1392
1393 // Assume generic binary op...
1394
John Kessenich32cfd492016-02-02 12:37:46 -07001395 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001396 builder.clearAccessChain();
1397 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001398 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001399
John Kessenich32cfd492016-02-02 12:37:46 -07001400 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001401 builder.clearAccessChain();
1402 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001403 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001404
John Kessenich32cfd492016-02-02 12:37:46 -07001405 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001406 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001407 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001408 convertGlslangToSpvType(node->getType()), left, right,
1409 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001410
John Kessenich50e57562015-12-21 21:21:11 -07001411 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001412 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001413 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001414 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001415 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001416 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001417 return false;
1418 }
John Kessenich140f3df2015-06-26 16:58:36 -06001419}
1420
1421bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1422{
John Kesseniche485c7a2017-05-31 18:50:53 -06001423 builder.setLine(node->getLoc().line);
1424
qining40887662016-04-03 22:20:42 -04001425 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1426 if (node->getType().getQualifier().isSpecConstant())
1427 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1428
John Kessenichfc51d282015-08-19 13:34:18 -06001429 spv::Id result = spv::NoResult;
1430
1431 // try texturing first
1432 result = createImageTextureFunctionCall(node);
1433 if (result != spv::NoResult) {
1434 builder.clearAccessChain();
1435 builder.setAccessChainRValue(result);
1436
1437 return false; // done with this node
1438 }
1439
1440 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001441
1442 if (node->getOp() == glslang::EOpArrayLength) {
1443 // Quite special; won't want to evaluate the operand.
1444
1445 // Normal .length() would have been constant folded by the front-end.
1446 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001447 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001448 assert(node->getOperand()->getType().isRuntimeSizedArray());
1449 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1450 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001451 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1452 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001453
1454 builder.clearAccessChain();
1455 builder.setAccessChainRValue(length);
1456
1457 return false;
1458 }
1459
John Kessenichfc51d282015-08-19 13:34:18 -06001460 // Start by evaluating the operand
1461
John Kessenich8c8505c2016-07-26 12:50:38 -06001462 // Does it need a swizzle inversion? If so, evaluation is inverted;
1463 // operate first on the swizzle base, then apply the swizzle.
1464 spv::Id invertedType = spv::NoType;
1465 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1466 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1467 invertedType = getInvertedSwizzleType(*node->getOperand());
1468
John Kessenich140f3df2015-06-26 16:58:36 -06001469 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001470 if (invertedType != spv::NoType)
1471 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1472 else
1473 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001474
Rex Xufc618912015-09-09 16:42:49 +08001475 spv::Id operand = spv::NoResult;
1476
1477 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1478 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001479 node->getOp() == glslang::EOpAtomicCounter ||
1480 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001481 operand = builder.accessChainGetLValue(); // Special case l-value operands
1482 else
John Kessenich32cfd492016-02-02 12:37:46 -07001483 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001484
John Kessenichf6640762016-08-01 19:44:00 -06001485 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001486 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001487
1488 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001489 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001490 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001491
1492 // if not, then possibly an operation
1493 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001494 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001495
1496 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001497 if (invertedType)
1498 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1499
John Kessenich140f3df2015-06-26 16:58:36 -06001500 builder.clearAccessChain();
1501 builder.setAccessChainRValue(result);
1502
1503 return false; // done with this node
1504 }
1505
1506 // it must be a special case, check...
1507 switch (node->getOp()) {
1508 case glslang::EOpPostIncrement:
1509 case glslang::EOpPostDecrement:
1510 case glslang::EOpPreIncrement:
1511 case glslang::EOpPreDecrement:
1512 {
1513 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001514 spv::Id one = 0;
1515 if (node->getBasicType() == glslang::EbtFloat)
1516 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001517 else if (node->getBasicType() == glslang::EbtDouble)
1518 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001519 else if (node->getBasicType() == glslang::EbtFloat16)
1520 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001521 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1522 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001523 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1524 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001525 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1526 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001527 else
1528 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001529 glslang::TOperator op;
1530 if (node->getOp() == glslang::EOpPreIncrement ||
1531 node->getOp() == glslang::EOpPostIncrement)
1532 op = glslang::EOpAdd;
1533 else
1534 op = glslang::EOpSub;
1535
John Kessenichf6640762016-08-01 19:44:00 -06001536 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001537 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001538 convertGlslangToSpvType(node->getType()), operand, one,
1539 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001540 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001541
1542 // The result of operation is always stored, but conditionally the
1543 // consumed result. The consumed result is always an r-value.
1544 builder.accessChainStore(result);
1545 builder.clearAccessChain();
1546 if (node->getOp() == glslang::EOpPreIncrement ||
1547 node->getOp() == glslang::EOpPreDecrement)
1548 builder.setAccessChainRValue(result);
1549 else
1550 builder.setAccessChainRValue(operand);
1551 }
1552
1553 return false;
1554
1555 case glslang::EOpEmitStreamVertex:
1556 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1557 return false;
1558 case glslang::EOpEndStreamPrimitive:
1559 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1560 return false;
1561
1562 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001563 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001564 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001565 }
John Kessenich140f3df2015-06-26 16:58:36 -06001566}
1567
1568bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1569{
qining27e04a02016-04-14 16:40:20 -04001570 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1571 if (node->getType().getQualifier().isSpecConstant())
1572 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1573
John Kessenichfc51d282015-08-19 13:34:18 -06001574 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001575 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1576 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001577
1578 // try texturing
1579 result = createImageTextureFunctionCall(node);
1580 if (result != spv::NoResult) {
1581 builder.clearAccessChain();
1582 builder.setAccessChainRValue(result);
1583
1584 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001585#ifdef AMD_EXTENSIONS
1586 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1587#else
John Kessenich56bab042015-09-16 10:54:31 -06001588 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001589#endif
Rex Xufc618912015-09-09 16:42:49 +08001590 // "imageStore" is a special case, which has no result
1591 return false;
1592 }
John Kessenichfc51d282015-08-19 13:34:18 -06001593
John Kessenich140f3df2015-06-26 16:58:36 -06001594 glslang::TOperator binOp = glslang::EOpNull;
1595 bool reduceComparison = true;
1596 bool isMatrix = false;
1597 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001598 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001599
1600 assert(node->getOp());
1601
John Kessenichf6640762016-08-01 19:44:00 -06001602 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001603
1604 switch (node->getOp()) {
1605 case glslang::EOpSequence:
1606 {
1607 if (preVisit)
1608 ++sequenceDepth;
1609 else
1610 --sequenceDepth;
1611
1612 if (sequenceDepth == 1) {
1613 // If this is the parent node of all the functions, we want to see them
1614 // early, so all call points have actual SPIR-V functions to reference.
1615 // In all cases, still let the traverser visit the children for us.
1616 makeFunctions(node->getAsAggregate()->getSequence());
1617
John Kessenich6fccb3c2016-09-19 16:01:41 -06001618 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001619 // anything else gets there, so visit out of order, doing them all now.
1620 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1621
John Kessenich6a60c2f2016-12-08 21:01:59 -07001622 // 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 -06001623 // so do them manually.
1624 visitFunctions(node->getAsAggregate()->getSequence());
1625
1626 return false;
1627 }
1628
1629 return true;
1630 }
1631 case glslang::EOpLinkerObjects:
1632 {
1633 if (visit == glslang::EvPreVisit)
1634 linkageOnly = true;
1635 else
1636 linkageOnly = false;
1637
1638 return true;
1639 }
1640 case glslang::EOpComma:
1641 {
1642 // processing from left to right naturally leaves the right-most
1643 // lying around in the access chain
1644 glslang::TIntermSequence& glslangOperands = node->getSequence();
1645 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1646 glslangOperands[i]->traverse(this);
1647
1648 return false;
1649 }
1650 case glslang::EOpFunction:
1651 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001652 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001653 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001654 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001655 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001656 } else {
1657 handleFunctionEntry(node);
1658 }
1659 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001660 if (inEntryPoint)
1661 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001662 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001663 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001664 }
1665
1666 return true;
1667 case glslang::EOpParameters:
1668 // Parameters will have been consumed by EOpFunction processing, but not
1669 // the body, so we still visited the function node's children, making this
1670 // child redundant.
1671 return false;
1672 case glslang::EOpFunctionCall:
1673 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001674 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001675 if (node->isUserDefined())
1676 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001677 // 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 -07001678 if (result) {
1679 builder.clearAccessChain();
1680 builder.setAccessChainRValue(result);
1681 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001682 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001683
1684 return false;
1685 }
1686 case glslang::EOpConstructMat2x2:
1687 case glslang::EOpConstructMat2x3:
1688 case glslang::EOpConstructMat2x4:
1689 case glslang::EOpConstructMat3x2:
1690 case glslang::EOpConstructMat3x3:
1691 case glslang::EOpConstructMat3x4:
1692 case glslang::EOpConstructMat4x2:
1693 case glslang::EOpConstructMat4x3:
1694 case glslang::EOpConstructMat4x4:
1695 case glslang::EOpConstructDMat2x2:
1696 case glslang::EOpConstructDMat2x3:
1697 case glslang::EOpConstructDMat2x4:
1698 case glslang::EOpConstructDMat3x2:
1699 case glslang::EOpConstructDMat3x3:
1700 case glslang::EOpConstructDMat3x4:
1701 case glslang::EOpConstructDMat4x2:
1702 case glslang::EOpConstructDMat4x3:
1703 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001704 case glslang::EOpConstructIMat2x2:
1705 case glslang::EOpConstructIMat2x3:
1706 case glslang::EOpConstructIMat2x4:
1707 case glslang::EOpConstructIMat3x2:
1708 case glslang::EOpConstructIMat3x3:
1709 case glslang::EOpConstructIMat3x4:
1710 case glslang::EOpConstructIMat4x2:
1711 case glslang::EOpConstructIMat4x3:
1712 case glslang::EOpConstructIMat4x4:
1713 case glslang::EOpConstructUMat2x2:
1714 case glslang::EOpConstructUMat2x3:
1715 case glslang::EOpConstructUMat2x4:
1716 case glslang::EOpConstructUMat3x2:
1717 case glslang::EOpConstructUMat3x3:
1718 case glslang::EOpConstructUMat3x4:
1719 case glslang::EOpConstructUMat4x2:
1720 case glslang::EOpConstructUMat4x3:
1721 case glslang::EOpConstructUMat4x4:
1722 case glslang::EOpConstructBMat2x2:
1723 case glslang::EOpConstructBMat2x3:
1724 case glslang::EOpConstructBMat2x4:
1725 case glslang::EOpConstructBMat3x2:
1726 case glslang::EOpConstructBMat3x3:
1727 case glslang::EOpConstructBMat3x4:
1728 case glslang::EOpConstructBMat4x2:
1729 case glslang::EOpConstructBMat4x3:
1730 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001731 case glslang::EOpConstructF16Mat2x2:
1732 case glslang::EOpConstructF16Mat2x3:
1733 case glslang::EOpConstructF16Mat2x4:
1734 case glslang::EOpConstructF16Mat3x2:
1735 case glslang::EOpConstructF16Mat3x3:
1736 case glslang::EOpConstructF16Mat3x4:
1737 case glslang::EOpConstructF16Mat4x2:
1738 case glslang::EOpConstructF16Mat4x3:
1739 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06001740 isMatrix = true;
1741 // fall through
1742 case glslang::EOpConstructFloat:
1743 case glslang::EOpConstructVec2:
1744 case glslang::EOpConstructVec3:
1745 case glslang::EOpConstructVec4:
1746 case glslang::EOpConstructDouble:
1747 case glslang::EOpConstructDVec2:
1748 case glslang::EOpConstructDVec3:
1749 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001750 case glslang::EOpConstructFloat16:
1751 case glslang::EOpConstructF16Vec2:
1752 case glslang::EOpConstructF16Vec3:
1753 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001754 case glslang::EOpConstructBool:
1755 case glslang::EOpConstructBVec2:
1756 case glslang::EOpConstructBVec3:
1757 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07001758 case glslang::EOpConstructInt8:
1759 case glslang::EOpConstructI8Vec2:
1760 case glslang::EOpConstructI8Vec3:
1761 case glslang::EOpConstructI8Vec4:
1762 case glslang::EOpConstructUint8:
1763 case glslang::EOpConstructU8Vec2:
1764 case glslang::EOpConstructU8Vec3:
1765 case glslang::EOpConstructU8Vec4:
1766 case glslang::EOpConstructInt16:
1767 case glslang::EOpConstructI16Vec2:
1768 case glslang::EOpConstructI16Vec3:
1769 case glslang::EOpConstructI16Vec4:
1770 case glslang::EOpConstructUint16:
1771 case glslang::EOpConstructU16Vec2:
1772 case glslang::EOpConstructU16Vec3:
1773 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001774 case glslang::EOpConstructInt:
1775 case glslang::EOpConstructIVec2:
1776 case glslang::EOpConstructIVec3:
1777 case glslang::EOpConstructIVec4:
1778 case glslang::EOpConstructUint:
1779 case glslang::EOpConstructUVec2:
1780 case glslang::EOpConstructUVec3:
1781 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001782 case glslang::EOpConstructInt64:
1783 case glslang::EOpConstructI64Vec2:
1784 case glslang::EOpConstructI64Vec3:
1785 case glslang::EOpConstructI64Vec4:
1786 case glslang::EOpConstructUint64:
1787 case glslang::EOpConstructU64Vec2:
1788 case glslang::EOpConstructU64Vec3:
1789 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001790 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001791 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001792 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001793 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001794 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001795 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001796 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001797 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001798 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001799 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001800 std::vector<spv::Id> constituents;
1801 for (int c = 0; c < (int)arguments.size(); ++c)
1802 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001803 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001804 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001805 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001806 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001807 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001808
1809 builder.clearAccessChain();
1810 builder.setAccessChainRValue(constructed);
1811
1812 return false;
1813 }
1814
1815 // These six are component-wise compares with component-wise results.
1816 // Forward on to createBinaryOperation(), requesting a vector result.
1817 case glslang::EOpLessThan:
1818 case glslang::EOpGreaterThan:
1819 case glslang::EOpLessThanEqual:
1820 case glslang::EOpGreaterThanEqual:
1821 case glslang::EOpVectorEqual:
1822 case glslang::EOpVectorNotEqual:
1823 {
1824 // Map the operation to a binary
1825 binOp = node->getOp();
1826 reduceComparison = false;
1827 switch (node->getOp()) {
1828 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1829 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1830 default: binOp = node->getOp(); break;
1831 }
1832
1833 break;
1834 }
1835 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001836 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001837 binOp = glslang::EOpMul;
1838 break;
1839 case glslang::EOpOuterProduct:
1840 // two vectors multiplied to make a matrix
1841 binOp = glslang::EOpOuterProduct;
1842 break;
1843 case glslang::EOpDot:
1844 {
qining25262b32016-05-06 17:25:16 -04001845 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001846 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001847 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001848 binOp = glslang::EOpMul;
1849 break;
1850 }
1851 case glslang::EOpMod:
1852 // when an aggregate, this is the floating-point mod built-in function,
1853 // which can be emitted by the one in createBinaryOperation()
1854 binOp = glslang::EOpMod;
1855 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001856 case glslang::EOpEmitVertex:
1857 case glslang::EOpEndPrimitive:
1858 case glslang::EOpBarrier:
1859 case glslang::EOpMemoryBarrier:
1860 case glslang::EOpMemoryBarrierAtomicCounter:
1861 case glslang::EOpMemoryBarrierBuffer:
1862 case glslang::EOpMemoryBarrierImage:
1863 case glslang::EOpMemoryBarrierShared:
1864 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07001865 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001866 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07001867 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001868 case glslang::EOpWorkgroupMemoryBarrier:
1869 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07001870 case glslang::EOpSubgroupBarrier:
1871 case glslang::EOpSubgroupMemoryBarrier:
1872 case glslang::EOpSubgroupMemoryBarrierBuffer:
1873 case glslang::EOpSubgroupMemoryBarrierImage:
1874 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06001875 noReturnValue = true;
1876 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1877 break;
1878
John Kessenich426394d2015-07-23 10:22:48 -06001879 case glslang::EOpAtomicAdd:
1880 case glslang::EOpAtomicMin:
1881 case glslang::EOpAtomicMax:
1882 case glslang::EOpAtomicAnd:
1883 case glslang::EOpAtomicOr:
1884 case glslang::EOpAtomicXor:
1885 case glslang::EOpAtomicExchange:
1886 case glslang::EOpAtomicCompSwap:
1887 atomic = true;
1888 break;
1889
John Kessenich0d0c6d32017-07-23 16:08:26 -06001890 case glslang::EOpAtomicCounterAdd:
1891 case glslang::EOpAtomicCounterSubtract:
1892 case glslang::EOpAtomicCounterMin:
1893 case glslang::EOpAtomicCounterMax:
1894 case glslang::EOpAtomicCounterAnd:
1895 case glslang::EOpAtomicCounterOr:
1896 case glslang::EOpAtomicCounterXor:
1897 case glslang::EOpAtomicCounterExchange:
1898 case glslang::EOpAtomicCounterCompSwap:
1899 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1900 builder.addCapability(spv::CapabilityAtomicStorageOps);
1901 atomic = true;
1902 break;
1903
John Kessenich140f3df2015-06-26 16:58:36 -06001904 default:
1905 break;
1906 }
1907
1908 //
1909 // See if it maps to a regular operation.
1910 //
John Kessenich140f3df2015-06-26 16:58:36 -06001911 if (binOp != glslang::EOpNull) {
1912 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1913 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1914 assert(left && right);
1915
1916 builder.clearAccessChain();
1917 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001918 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001919
1920 builder.clearAccessChain();
1921 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001922 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001923
John Kesseniche485c7a2017-05-31 18:50:53 -06001924 builder.setLine(node->getLoc().line);
qining25262b32016-05-06 17:25:16 -04001925 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001926 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001927 left->getType().getBasicType(), reduceComparison);
1928
1929 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001930 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001931 builder.clearAccessChain();
1932 builder.setAccessChainRValue(result);
1933
1934 return false;
1935 }
1936
John Kessenich426394d2015-07-23 10:22:48 -06001937 //
1938 // Create the list of operands.
1939 //
John Kessenich140f3df2015-06-26 16:58:36 -06001940 glslang::TIntermSequence& glslangOperands = node->getSequence();
1941 std::vector<spv::Id> operands;
1942 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001943 // special case l-value operands; there are just a few
1944 bool lvalue = false;
1945 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001946 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001947 case glslang::EOpModf:
1948 if (arg == 1)
1949 lvalue = true;
1950 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001951 case glslang::EOpInterpolateAtSample:
1952 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001953#ifdef AMD_EXTENSIONS
1954 case glslang::EOpInterpolateAtVertex:
1955#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001956 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001957 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001958
1959 // Does it need a swizzle inversion? If so, evaluation is inverted;
1960 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001961 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001962 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1963 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1964 }
Rex Xu7a26c172015-12-08 17:12:09 +08001965 break;
Rex Xud4782c12015-09-06 16:30:11 +08001966 case glslang::EOpAtomicAdd:
1967 case glslang::EOpAtomicMin:
1968 case glslang::EOpAtomicMax:
1969 case glslang::EOpAtomicAnd:
1970 case glslang::EOpAtomicOr:
1971 case glslang::EOpAtomicXor:
1972 case glslang::EOpAtomicExchange:
1973 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06001974 case glslang::EOpAtomicCounterAdd:
1975 case glslang::EOpAtomicCounterSubtract:
1976 case glslang::EOpAtomicCounterMin:
1977 case glslang::EOpAtomicCounterMax:
1978 case glslang::EOpAtomicCounterAnd:
1979 case glslang::EOpAtomicCounterOr:
1980 case glslang::EOpAtomicCounterXor:
1981 case glslang::EOpAtomicCounterExchange:
1982 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08001983 if (arg == 0)
1984 lvalue = true;
1985 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001986 case glslang::EOpAddCarry:
1987 case glslang::EOpSubBorrow:
1988 if (arg == 2)
1989 lvalue = true;
1990 break;
1991 case glslang::EOpUMulExtended:
1992 case glslang::EOpIMulExtended:
1993 if (arg >= 2)
1994 lvalue = true;
1995 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001996 default:
1997 break;
1998 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001999 builder.clearAccessChain();
2000 if (invertedType != spv::NoType && arg == 0)
2001 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2002 else
2003 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002004 if (lvalue)
2005 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002006 else {
2007 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07002008 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002009 }
John Kessenich140f3df2015-06-26 16:58:36 -06002010 }
John Kessenich426394d2015-07-23 10:22:48 -06002011
John Kesseniche485c7a2017-05-31 18:50:53 -06002012 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06002013 if (atomic) {
2014 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002015 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002016 } else {
2017 // Pass through to generic operations.
2018 switch (glslangOperands.size()) {
2019 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002020 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002021 break;
2022 case 1:
qining25262b32016-05-06 17:25:16 -04002023 result = createUnaryOperation(
2024 node->getOp(), precision,
2025 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06002026 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04002027 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002028 break;
2029 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002030 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002031 break;
2032 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002033 if (invertedType)
2034 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002035 }
2036
2037 if (noReturnValue)
2038 return false;
2039
2040 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002041 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002042 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002043 } else {
2044 builder.clearAccessChain();
2045 builder.setAccessChainRValue(result);
2046 return false;
2047 }
2048}
2049
John Kessenich433e9ff2017-01-26 20:31:11 -07002050// This path handles both if-then-else and ?:
2051// The if-then-else has a node type of void, while
2052// ?: has either a void or a non-void node type
2053//
2054// Leaving the result, when not void:
2055// GLSL only has r-values as the result of a :?, but
2056// if we have an l-value, that can be more efficient if it will
2057// become the base of a complex r-value expression, because the
2058// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002059bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2060{
John Kessenich4bee5312018-02-20 21:29:05 -07002061 // See if it simple and safe, or required, to execute both sides.
2062 // Crucially, side effects must be either semantically required or avoided,
2063 // and there are performance trade-offs.
2064 // Return true if required or a good idea (and safe) to execute both sides,
2065 // false otherwise.
2066 const auto bothSidesPolicy = [&]() -> bool {
2067 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002068 if (node->getTrueBlock() == nullptr ||
2069 node->getFalseBlock() == nullptr)
2070 return false;
2071
John Kessenich4bee5312018-02-20 21:29:05 -07002072 // required? (unless we write additional code to look for side effects
2073 // and make performance trade-offs if none are present)
2074 if (!node->getShortCircuit())
2075 return true;
2076
2077 // if not required to execute both, decide based on performance/practicality...
2078
2079 // see if OpSelect can handle it
2080 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2081 node->getBasicType() == glslang::EbtVoid)
2082 return false;
2083
John Kessenich433e9ff2017-01-26 20:31:11 -07002084 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2085 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2086
2087 // return true if a single operand to ? : is okay for OpSelect
2088 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002089 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002090 };
2091
2092 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2093 operandOkay(node->getFalseBlock()->getAsTyped());
2094 };
2095
John Kessenich4bee5312018-02-20 21:29:05 -07002096 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2097 // emit the condition before doing anything with selection
2098 node->getCondition()->traverse(this);
2099 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2100
2101 // Find a way of executing both sides and selecting the right result.
2102 const auto executeBothSides = [&]() -> void {
2103 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002104 node->getTrueBlock()->traverse(this);
2105 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2106 node->getFalseBlock()->traverse(this);
2107 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2108
John Kesseniche485c7a2017-05-31 18:50:53 -06002109 builder.setLine(node->getLoc().line);
2110
John Kessenich4bee5312018-02-20 21:29:05 -07002111 // done if void
2112 if (node->getBasicType() == glslang::EbtVoid)
2113 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002114
John Kessenich4bee5312018-02-20 21:29:05 -07002115 // emit code to select between trueValue and falseValue
2116
2117 // see if OpSelect can handle it
2118 if (node->getType().isScalar() || node->getType().isVector()) {
2119 // Emit OpSelect for this selection.
2120
2121 // smear condition to vector, if necessary (AST is always scalar)
2122 if (builder.isVector(trueValue))
2123 condition = builder.smearScalar(spv::NoPrecision, condition,
2124 builder.makeVectorType(builder.makeBoolType(),
2125 builder.getNumComponents(trueValue)));
2126
2127 // OpSelect
2128 result = builder.createTriOp(spv::OpSelect,
2129 convertGlslangToSpvType(node->getType()), condition,
2130 trueValue, falseValue);
2131
2132 builder.clearAccessChain();
2133 builder.setAccessChainRValue(result);
2134 } else {
2135 // We need control flow to select the result.
2136 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2137 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2138
2139 // Selection control:
2140 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2141
2142 // make an "if" based on the value created by the condition
2143 spv::Builder::If ifBuilder(condition, control, builder);
2144
2145 // emit the "then" statement
2146 builder.createStore(trueValue, result);
2147 ifBuilder.makeBeginElse();
2148 // emit the "else" statement
2149 builder.createStore(falseValue, result);
2150
2151 // finish off the control flow
2152 ifBuilder.makeEndIf();
2153
2154 builder.clearAccessChain();
2155 builder.setAccessChainLValue(result);
2156 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002157 };
2158
John Kessenich4bee5312018-02-20 21:29:05 -07002159 // Execute the one side needed, as per the condition
2160 const auto executeOneSide = [&]() {
2161 // Always emit control flow.
2162 if (node->getBasicType() != glslang::EbtVoid)
2163 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002164
John Kessenich4bee5312018-02-20 21:29:05 -07002165 // Selection control:
2166 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2167
2168 // make an "if" based on the value created by the condition
2169 spv::Builder::If ifBuilder(condition, control, builder);
2170
2171 // emit the "then" statement
2172 if (node->getTrueBlock() != nullptr) {
2173 node->getTrueBlock()->traverse(this);
2174 if (result != spv::NoResult)
2175 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2176 }
2177
2178 if (node->getFalseBlock() != nullptr) {
2179 ifBuilder.makeBeginElse();
2180 // emit the "else" statement
2181 node->getFalseBlock()->traverse(this);
2182 if (result != spv::NoResult)
2183 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2184 }
2185
2186 // finish off the control flow
2187 ifBuilder.makeEndIf();
2188
2189 if (result != spv::NoResult) {
2190 builder.clearAccessChain();
2191 builder.setAccessChainLValue(result);
2192 }
2193 };
2194
2195 // Try for OpSelect (or a requirement to execute both sides)
2196 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002197 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2198 if (node->getType().getQualifier().isSpecConstant())
2199 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002200 executeBothSides();
2201 } else
2202 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002203
2204 return false;
2205}
2206
2207bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2208{
2209 // emit and get the condition before doing anything with switch
2210 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002211 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002212
Rex Xu57e65922017-07-04 23:23:40 +08002213 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002214 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002215
John Kessenich140f3df2015-06-26 16:58:36 -06002216 // browse the children to sort out code segments
2217 int defaultSegment = -1;
2218 std::vector<TIntermNode*> codeSegments;
2219 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2220 std::vector<int> caseValues;
2221 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2222 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2223 TIntermNode* child = *c;
2224 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002225 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002226 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002227 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002228 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2229 } else
2230 codeSegments.push_back(child);
2231 }
2232
qining25262b32016-05-06 17:25:16 -04002233 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002234 // statements between the last case and the end of the switch statement
2235 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2236 (int)codeSegments.size() == defaultSegment)
2237 codeSegments.push_back(nullptr);
2238
2239 // make the switch statement
2240 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002241 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002242
2243 // emit all the code in the segments
2244 breakForLoop.push(false);
2245 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2246 builder.nextSwitchSegment(segmentBlocks, s);
2247 if (codeSegments[s])
2248 codeSegments[s]->traverse(this);
2249 else
2250 builder.addSwitchBreak();
2251 }
2252 breakForLoop.pop();
2253
2254 builder.endSwitch(segmentBlocks);
2255
2256 return false;
2257}
2258
2259void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2260{
2261 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002262 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002263
2264 builder.clearAccessChain();
2265 builder.setAccessChainRValue(constant);
2266}
2267
2268bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2269{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002270 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002271 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002272
2273 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002274 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2275 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002276
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002277 // Spec requires back edges to target header blocks, and every header block
2278 // must dominate its merge block. Make a header block first to ensure these
2279 // conditions are met. By definition, it will contain OpLoopMerge, followed
2280 // by a block-ending branch. But we don't want to put any other body/test
2281 // instructions in it, since the body/test may have arbitrary instructions,
2282 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002283 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002284 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002285 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002286 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002287 spv::Block& test = builder.makeNewBlock();
2288 builder.createBranch(&test);
2289
2290 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002291 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002292 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002293 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2294
2295 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002296 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002297 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002298 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002299 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002300 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002301
2302 builder.setBuildPoint(&blocks.continue_target);
2303 if (node->getTerminal())
2304 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002305 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002306 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002307 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002308 builder.createBranch(&blocks.body);
2309
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002310 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002311 builder.setBuildPoint(&blocks.body);
2312 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002313 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002314 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002315 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002316
2317 builder.setBuildPoint(&blocks.continue_target);
2318 if (node->getTerminal())
2319 node->getTerminal()->traverse(this);
2320 if (node->getTest()) {
2321 node->getTest()->traverse(this);
2322 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002323 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002324 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002325 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002326 // TODO: unless there was a break/return/discard instruction
2327 // somewhere in the body, this is an infinite loop, so we should
2328 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002329 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002330 }
John Kessenich140f3df2015-06-26 16:58:36 -06002331 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002332 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002333 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002334 return false;
2335}
2336
2337bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2338{
2339 if (node->getExpression())
2340 node->getExpression()->traverse(this);
2341
John Kesseniche485c7a2017-05-31 18:50:53 -06002342 builder.setLine(node->getLoc().line);
2343
John Kessenich140f3df2015-06-26 16:58:36 -06002344 switch (node->getFlowOp()) {
2345 case glslang::EOpKill:
2346 builder.makeDiscard();
2347 break;
2348 case glslang::EOpBreak:
2349 if (breakForLoop.top())
2350 builder.createLoopExit();
2351 else
2352 builder.addSwitchBreak();
2353 break;
2354 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002355 builder.createLoopContinue();
2356 break;
2357 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002358 if (node->getExpression()) {
2359 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2360 spv::Id returnId = accessChainLoad(glslangReturnType);
2361 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2362 builder.clearAccessChain();
2363 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2364 builder.setAccessChainLValue(copyId);
2365 multiTypeStore(glslangReturnType, returnId);
2366 returnId = builder.createLoad(copyId);
2367 }
2368 builder.makeReturn(false, returnId);
2369 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002370 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002371
2372 builder.clearAccessChain();
2373 break;
2374
2375 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002376 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002377 break;
2378 }
2379
2380 return false;
2381}
2382
2383spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2384{
qining25262b32016-05-06 17:25:16 -04002385 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002386 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002387 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002388 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002389 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002390 }
2391
2392 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002393 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002394 spv::Id spvType = convertGlslangToSpvType(node->getType());
2395
Rex Xucabbb782017-03-24 13:41:14 +08002396 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2397 node->getType().containsBasicType(glslang::EbtInt16) ||
2398 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002399 if (contains16BitType) {
2400 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
John Kessenich66011cb2018-03-06 16:12:04 -07002401 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002402 builder.addCapability(spv::CapabilityStorageInputOutput16);
2403 } else if (storageClass == spv::StorageClassPushConstant) {
John Kessenich66011cb2018-03-06 16:12:04 -07002404 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002405 builder.addCapability(spv::CapabilityStoragePushConstant16);
2406 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich66011cb2018-03-06 16:12:04 -07002407 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002408 builder.addCapability(spv::CapabilityStorageUniform16);
2409 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2410 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2411 }
2412 }
Rex Xuf89ad982017-04-07 23:22:33 +08002413
John Kessenich140f3df2015-06-26 16:58:36 -06002414 const char* name = node->getName().c_str();
2415 if (glslang::IsAnonymous(name))
2416 name = "";
2417
2418 return builder.createVariable(storageClass, spvType, name);
2419}
2420
2421// Return type Id of the sampled type.
2422spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2423{
2424 switch (sampler.type) {
2425 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08002426#ifdef AMD_EXTENSIONS
2427 case glslang::EbtFloat16:
2428 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
2429 builder.addCapability(spv::CapabilityFloat16ImageAMD);
2430 return builder.makeFloatType(16);
2431#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002432 case glslang::EbtInt: return builder.makeIntType(32);
2433 case glslang::EbtUint: return builder.makeUintType(32);
2434 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002435 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002436 return builder.makeFloatType(32);
2437 }
2438}
2439
John Kessenich8c8505c2016-07-26 12:50:38 -06002440// If node is a swizzle operation, return the type that should be used if
2441// the swizzle base is first consumed by another operation, before the swizzle
2442// is applied.
2443spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2444{
John Kessenichecba76f2017-01-06 00:34:48 -07002445 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002446 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2447 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2448 else
2449 return spv::NoType;
2450}
2451
2452// When inverting a swizzle with a parent op, this function
2453// will apply the swizzle operation to a completed parent operation.
2454spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2455{
2456 std::vector<unsigned> swizzle;
2457 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2458 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2459}
2460
John Kessenich8c8505c2016-07-26 12:50:38 -06002461// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2462void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2463{
2464 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2465 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2466 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2467}
2468
John Kessenich3ac051e2015-12-20 11:29:16 -07002469// Convert from a glslang type to an SPV type, by calling into a
2470// recursive version of this function. This establishes the inherited
2471// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002472spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2473{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002474 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002475}
2476
2477// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002478// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002479// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002480spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002481{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002482 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002483
2484 switch (type.getBasicType()) {
2485 case glslang::EbtVoid:
2486 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002487 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002488 break;
2489 case glslang::EbtFloat:
2490 spvType = builder.makeFloatType(32);
2491 break;
2492 case glslang::EbtDouble:
2493 spvType = builder.makeFloatType(64);
2494 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002495 case glslang::EbtFloat16:
John Kessenich66011cb2018-03-06 16:12:04 -07002496 builder.addCapability(spv::CapabilityFloat16);
2497#if AMD_EXTENSIONS
2498 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2499 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
2500#endif
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002501 spvType = builder.makeFloatType(16);
2502 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002503 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002504 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2505 // a 32-bit int where non-0 means true.
2506 if (explicitLayout != glslang::ElpNone)
2507 spvType = builder.makeUintType(32);
2508 else
2509 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002510 break;
John Kessenich66011cb2018-03-06 16:12:04 -07002511 case glslang::EbtInt8:
2512 builder.addCapability(spv::CapabilityInt8);
2513 spvType = builder.makeIntType(8);
2514 break;
2515 case glslang::EbtUint8:
2516 builder.addCapability(spv::CapabilityInt8);
2517 spvType = builder.makeUintType(8);
2518 break;
2519 case glslang::EbtInt16:
2520 builder.addCapability(spv::CapabilityInt16);
2521#ifdef AMD_EXTENSIONS
2522 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2523 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2524#endif
2525 spvType = builder.makeIntType(16);
2526 break;
2527 case glslang::EbtUint16:
2528 builder.addCapability(spv::CapabilityInt16);
2529#ifdef AMD_EXTENSIONS
2530 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2531 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2532#endif
2533 spvType = builder.makeUintType(16);
2534 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002535 case glslang::EbtInt:
2536 spvType = builder.makeIntType(32);
2537 break;
2538 case glslang::EbtUint:
2539 spvType = builder.makeUintType(32);
2540 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002541 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002542 spvType = builder.makeIntType(64);
2543 break;
2544 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002545 spvType = builder.makeUintType(64);
2546 break;
John Kessenich426394d2015-07-23 10:22:48 -06002547 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002548 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002549 spvType = builder.makeUintType(32);
2550 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002551 case glslang::EbtSampler:
2552 {
2553 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002554 if (sampler.sampler) {
2555 // pure sampler
2556 spvType = builder.makeSamplerType();
2557 } else {
2558 // an image is present, make its type
2559 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2560 sampler.image ? 2 : 1, TranslateImageFormat(type));
2561 if (sampler.combined) {
2562 // already has both image and sampler, make the combined type
2563 spvType = builder.makeSampledImageType(spvType);
2564 }
John Kessenich55e7d112015-11-15 21:33:39 -07002565 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002566 }
John Kessenich140f3df2015-06-26 16:58:36 -06002567 break;
2568 case glslang::EbtStruct:
2569 case glslang::EbtBlock:
2570 {
2571 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002572 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002573
2574 // Try to share structs for different layouts, but not yet for other
2575 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002576 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002577 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002578 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002579 break;
2580
2581 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002582 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002583 memberRemapper[glslangMembers].resize(glslangMembers->size());
2584 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002585 }
2586 break;
2587 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002588 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002589 break;
2590 }
2591
2592 if (type.isMatrix())
2593 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2594 else {
2595 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2596 if (type.getVectorSize() > 1)
2597 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2598 }
2599
2600 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002601 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2602
John Kessenichc9a80832015-09-12 12:17:44 -06002603 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002604 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002605 // We need to decorate array strides for types needing explicit layout, except blocks.
2606 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002607 // Use a dummy glslang type for querying internal strides of
2608 // arrays of arrays, but using just a one-dimensional array.
2609 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06002610 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
2611 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07002612
2613 // Will compute the higher-order strides here, rather than making a whole
2614 // pile of types and doing repetitive recursion on their contents.
2615 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2616 }
John Kessenichf8842e52016-01-04 19:22:56 -07002617
2618 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002619 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002620 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002621 if (stride > 0)
2622 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002623 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002624 }
2625 } else {
2626 // single-dimensional array, and don't yet have stride
2627
John Kessenichf8842e52016-01-04 19:22:56 -07002628 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002629 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2630 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002631 }
John Kessenich31ed4832015-09-09 17:51:38 -06002632
John Kessenichc9a80832015-09-12 12:17:44 -06002633 // Do the outer dimension, which might not be known for a runtime-sized array
2634 if (type.isRuntimeSizedArray()) {
2635 spvType = builder.makeRuntimeArray(spvType);
2636 } else {
2637 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002638 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002639 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002640 if (stride > 0)
2641 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002642 }
2643
2644 return spvType;
2645}
2646
John Kessenich0e737842017-03-24 18:38:16 -06002647// TODO: this functionality should exist at a higher level, in creating the AST
2648//
2649// Identify interface members that don't have their required extension turned on.
2650//
2651bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2652{
2653 auto& extensions = glslangIntermediate->getRequestedExtensions();
2654
Rex Xubcf291a2017-03-29 23:01:36 +08002655 if (member.getFieldName() == "gl_ViewportMask" &&
2656 extensions.find("GL_NV_viewport_array2") == extensions.end())
2657 return true;
2658 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2659 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2660 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002661 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2662 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2663 return true;
2664 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2665 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2666 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002667 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2668 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2669 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002670
2671 return false;
2672};
2673
John Kessenich6090df02016-06-30 21:18:02 -06002674// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2675// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2676// Mutually recursive with convertGlslangToSpvType().
2677spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2678 const glslang::TTypeList* glslangMembers,
2679 glslang::TLayoutPacking explicitLayout,
2680 const glslang::TQualifier& qualifier)
2681{
2682 // Create a vector of struct types for SPIR-V to consume
2683 std::vector<spv::Id> spvMembers;
2684 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 -06002685 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2686 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2687 if (glslangMember.hiddenMember()) {
2688 ++memberDelta;
2689 if (type.getBasicType() == glslang::EbtBlock)
2690 memberRemapper[glslangMembers][i] = -1;
2691 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002692 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002693 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002694 if (filterMember(glslangMember))
2695 continue;
2696 }
John Kessenich6090df02016-06-30 21:18:02 -06002697 // modify just this child's view of the qualifier
2698 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2699 InheritQualifiers(memberQualifier, qualifier);
2700
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002701 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002702 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002703 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002704
2705 // recurse
2706 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2707 }
2708 }
2709
2710 // Make the SPIR-V type
2711 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002712 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002713 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2714
2715 // Decorate it
2716 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2717
2718 return spvType;
2719}
2720
2721void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2722 const glslang::TTypeList* glslangMembers,
2723 glslang::TLayoutPacking explicitLayout,
2724 const glslang::TQualifier& qualifier,
2725 spv::Id spvType)
2726{
2727 // Name and decorate the non-hidden members
2728 int offset = -1;
2729 int locationOffset = 0; // for use within the members of this struct
2730 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2731 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2732 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002733 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002734 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002735 if (filterMember(glslangMember))
2736 continue;
2737 }
John Kessenich6090df02016-06-30 21:18:02 -06002738
2739 // modify just this child's view of the qualifier
2740 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2741 InheritQualifiers(memberQualifier, qualifier);
2742
2743 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07002744 if (member < 0)
2745 continue;
2746
2747 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2748 builder.addMemberDecoration(spvType, member,
2749 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2750 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2751 // Add interpolation and auxiliary storage decorations only to
2752 // top-level members of Input and Output storage classes
2753 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2754 type.getQualifier().storage == glslang::EvqVaryingOut) {
2755 if (type.getBasicType() == glslang::EbtBlock ||
2756 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
2757 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2758 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002759 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002760 }
2761 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002762
John Kessenich5d610ee2018-03-07 18:05:55 -07002763 if (type.getBasicType() == glslang::EbtBlock &&
2764 qualifier.storage == glslang::EvqBuffer) {
2765 // Add memory decorations only to top-level members of shader storage block
2766 std::vector<spv::Decoration> memory;
2767 TranslateMemoryDecoration(memberQualifier, memory);
2768 for (unsigned int i = 0; i < memory.size(); ++i)
2769 builder.addMemberDecoration(spvType, member, memory[i]);
2770 }
John Kessenich6090df02016-06-30 21:18:02 -06002771
John Kessenich5d610ee2018-03-07 18:05:55 -07002772 // Location assignment was already completed correctly by the front end,
2773 // just track whether a member needs to be decorated.
2774 // Ignore member locations if the container is an array, as that's
2775 // ill-specified and decisions have been made to not allow this.
2776 if (! type.isArray() && memberQualifier.hasLocation())
2777 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002778
John Kessenich5d610ee2018-03-07 18:05:55 -07002779 if (qualifier.hasLocation()) // track for upcoming inheritance
2780 locationOffset += glslangIntermediate->computeTypeLocationSize(
2781 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06002782
John Kessenich5d610ee2018-03-07 18:05:55 -07002783 // component, XFB, others
2784 if (glslangMember.getQualifier().hasComponent())
2785 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
2786 glslangMember.getQualifier().layoutComponent);
2787 if (glslangMember.getQualifier().hasXfbOffset())
2788 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
2789 glslangMember.getQualifier().layoutXfbOffset);
2790 else if (explicitLayout != glslang::ElpNone) {
2791 // figure out what to do with offset, which is accumulating
2792 int nextOffset;
2793 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2794 if (offset >= 0)
2795 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2796 offset = nextOffset;
2797 }
John Kessenich6090df02016-06-30 21:18:02 -06002798
John Kessenich5d610ee2018-03-07 18:05:55 -07002799 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2800 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
2801 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06002802
John Kessenich5d610ee2018-03-07 18:05:55 -07002803 // built-in variable decorations
2804 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
2805 if (builtIn != spv::BuiltInMax)
2806 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002807
2808#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07002809 if (builtIn == spv::BuiltInLayer) {
2810 // SPV_NV_viewport_array2 extension
2811 if (glslangMember.getQualifier().layoutViewportRelative){
2812 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2813 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2814 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08002815 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002816 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2817 builder.addMemberDecoration(spvType, member,
2818 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
2819 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2820 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2821 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08002822 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002823 }
2824 if (glslangMember.getQualifier().layoutPassthrough) {
2825 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2826 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2827 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2828 }
chaoc771d89f2017-01-13 01:10:53 -08002829#endif
John Kessenich5d610ee2018-03-07 18:05:55 -07002830 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
2831 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
2832 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
2833 memberQualifier.semanticName);
John Kessenich6090df02016-06-30 21:18:02 -06002834 }
2835 }
2836
2837 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07002838 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2839 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002840 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2841 builder.addCapability(spv::CapabilityGeometryStreams);
2842 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2843 }
John Kessenich6090df02016-06-30 21:18:02 -06002844}
2845
John Kessenich6c292d32016-02-15 20:58:50 -07002846// Turn the expression forming the array size into an id.
2847// This is not quite trivial, because of specialization constants.
2848// Sometimes, a raw constant is turned into an Id, and sometimes
2849// a specialization constant expression is.
2850spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2851{
2852 // First, see if this is sized with a node, meaning a specialization constant:
2853 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2854 if (specNode != nullptr) {
2855 builder.clearAccessChain();
2856 specNode->traverse(this);
2857 return accessChainLoad(specNode->getAsTyped()->getType());
2858 }
qining25262b32016-05-06 17:25:16 -04002859
John Kessenich6c292d32016-02-15 20:58:50 -07002860 // Otherwise, need a compile-time (front end) size, get it:
2861 int size = arraySizes.getDimSize(dim);
2862 assert(size > 0);
2863 return builder.makeUintConstant(size);
2864}
2865
John Kessenich103bef92016-02-08 21:38:15 -07002866// Wrap the builder's accessChainLoad to:
2867// - localize handling of RelaxedPrecision
2868// - use the SPIR-V inferred type instead of another conversion of the glslang type
2869// (avoids unnecessary work and possible type punning for structures)
2870// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002871spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2872{
John Kessenich103bef92016-02-08 21:38:15 -07002873 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2874 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2875
2876 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002877 if (type.getBasicType() == glslang::EbtBool) {
2878 if (builder.isScalarType(nominalTypeId)) {
2879 // Conversion for bool
2880 spv::Id boolType = builder.makeBoolType();
2881 if (nominalTypeId != boolType)
2882 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2883 } else if (builder.isVectorType(nominalTypeId)) {
2884 // Conversion for bvec
2885 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2886 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2887 if (nominalTypeId != bvecType)
2888 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2889 }
2890 }
John Kessenich103bef92016-02-08 21:38:15 -07002891
2892 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002893}
2894
Rex Xu27253232016-02-23 17:51:09 +08002895// Wrap the builder's accessChainStore to:
2896// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002897//
2898// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002899void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2900{
2901 // Need to convert to abstract types when necessary
2902 if (type.getBasicType() == glslang::EbtBool) {
2903 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2904
2905 if (builder.isScalarType(nominalTypeId)) {
2906 // Conversion for bool
2907 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002908 if (nominalTypeId != boolType) {
2909 // keep these outside arguments, for determinant order-of-evaluation
2910 spv::Id one = builder.makeUintConstant(1);
2911 spv::Id zero = builder.makeUintConstant(0);
2912 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2913 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002914 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002915 } else if (builder.isVectorType(nominalTypeId)) {
2916 // Conversion for bvec
2917 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2918 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002919 if (nominalTypeId != bvecType) {
2920 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002921 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2922 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2923 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002924 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002925 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2926 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002927 }
2928 }
2929
2930 builder.accessChainStore(rvalue);
2931}
2932
John Kessenich4bf71552016-09-02 11:20:21 -06002933// For storing when types match at the glslang level, but not might match at the
2934// SPIR-V level.
2935//
2936// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002937// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002938// as in a member-decorated way.
2939//
2940// NOTE: This function can handle any store request; if it's not special it
2941// simplifies to a simple OpStore.
2942//
2943// Implicitly uses the existing builder.accessChain as the storage target.
2944void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2945{
John Kessenichb3e24e42016-09-11 12:33:43 -06002946 // we only do the complex path here if it's an aggregate
2947 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002948 accessChainStore(type, rValue);
2949 return;
2950 }
2951
John Kessenichb3e24e42016-09-11 12:33:43 -06002952 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002953 spv::Id rType = builder.getTypeId(rValue);
2954 spv::Id lValue = builder.accessChainGetLValue();
2955 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2956 if (lType == rType) {
2957 accessChainStore(type, rValue);
2958 return;
2959 }
2960
John Kessenichb3e24e42016-09-11 12:33:43 -06002961 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002962 // where the two types were the same type in GLSL. This requires member
2963 // by member copy, recursively.
2964
John Kessenichb3e24e42016-09-11 12:33:43 -06002965 // If an array, copy element by element.
2966 if (type.isArray()) {
2967 glslang::TType glslangElementType(type, 0);
2968 spv::Id elementRType = builder.getContainedTypeId(rType);
2969 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2970 // get the source member
2971 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002972
John Kessenichb3e24e42016-09-11 12:33:43 -06002973 // set up the target storage
2974 builder.clearAccessChain();
2975 builder.setAccessChainLValue(lValue);
2976 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002977
John Kessenichb3e24e42016-09-11 12:33:43 -06002978 // store the member
2979 multiTypeStore(glslangElementType, elementRValue);
2980 }
2981 } else {
2982 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002983
John Kessenichb3e24e42016-09-11 12:33:43 -06002984 // loop over structure members
2985 const glslang::TTypeList& members = *type.getStruct();
2986 for (int m = 0; m < (int)members.size(); ++m) {
2987 const glslang::TType& glslangMemberType = *members[m].type;
2988
2989 // get the source member
2990 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2991 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2992
2993 // set up the target storage
2994 builder.clearAccessChain();
2995 builder.setAccessChainLValue(lValue);
2996 builder.accessChainPush(builder.makeIntConstant(m));
2997
2998 // store the member
2999 multiTypeStore(glslangMemberType, memberRValue);
3000 }
John Kessenich4bf71552016-09-02 11:20:21 -06003001 }
3002}
3003
John Kessenichf85e8062015-12-19 13:57:10 -07003004// Decide whether or not this type should be
3005// decorated with offsets and strides, and if so
3006// whether std140 or std430 rules should be applied.
3007glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003008{
John Kessenichf85e8062015-12-19 13:57:10 -07003009 // has to be a block
3010 if (type.getBasicType() != glslang::EbtBlock)
3011 return glslang::ElpNone;
3012
3013 // has to be a uniform or buffer block
3014 if (type.getQualifier().storage != glslang::EvqUniform &&
3015 type.getQualifier().storage != glslang::EvqBuffer)
3016 return glslang::ElpNone;
3017
3018 // return the layout to use
3019 switch (type.getQualifier().layoutPacking) {
3020 case glslang::ElpStd140:
3021 case glslang::ElpStd430:
3022 return type.getQualifier().layoutPacking;
3023 default:
3024 return glslang::ElpNone;
3025 }
John Kessenich31ed4832015-09-09 17:51:38 -06003026}
3027
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003028// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003029int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003030{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003031 int size;
John Kessenich49987892015-12-29 17:11:44 -07003032 int stride;
3033 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003034
3035 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003036}
3037
John Kessenich49987892015-12-29 17:11:44 -07003038// 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 -07003039// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003040int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003041{
John Kessenich49987892015-12-29 17:11:44 -07003042 glslang::TType elementType;
3043 elementType.shallowCopy(matrixType);
3044 elementType.clearArraySizes();
3045
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003046 int size;
John Kessenich49987892015-12-29 17:11:44 -07003047 int stride;
3048 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
3049
3050 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003051}
3052
John Kessenich5e4b1242015-08-06 22:53:06 -06003053// Given a member type of a struct, realign the current offset for it, and compute
3054// the next (not yet aligned) offset for the next member, which will get aligned
3055// on the next call.
3056// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3057// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3058// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003059void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003060 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003061{
3062 // this will get a positive value when deemed necessary
3063 nextOffset = -1;
3064
John Kessenich5e4b1242015-08-06 22:53:06 -06003065 // override anything in currentOffset with user-set offset
3066 if (memberType.getQualifier().hasOffset())
3067 currentOffset = memberType.getQualifier().layoutOffset;
3068
3069 // It could be that current linker usage in glslang updated all the layoutOffset,
3070 // in which case the following code does not matter. But, that's not quite right
3071 // once cross-compilation unit GLSL validation is done, as the original user
3072 // settings are needed in layoutOffset, and then the following will come into play.
3073
John Kessenichf85e8062015-12-19 13:57:10 -07003074 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003075 if (! memberType.getQualifier().hasOffset())
3076 currentOffset = -1;
3077
3078 return;
3079 }
3080
John Kessenichf85e8062015-12-19 13:57:10 -07003081 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003082 if (currentOffset < 0)
3083 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003084
John Kessenich5e4b1242015-08-06 22:53:06 -06003085 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3086 // but possibly not yet correctly aligned.
3087
3088 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003089 int dummyStride;
3090 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003091
3092 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003093 // TODO: make this consistent in early phases of code:
3094 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3095 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3096 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06003097 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003098 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003099 int dummySize;
3100 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3101 if (componentAlignment <= 4)
3102 memberAlignment = componentAlignment;
3103 }
3104
3105 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003106 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003107
3108 // Bump up to vec4 if there is a bad straddle
3109 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
3110 glslang::RoundToPow2(currentOffset, 16);
3111
John Kessenich5e4b1242015-08-06 22:53:06 -06003112 nextOffset = currentOffset + memberSize;
3113}
3114
David Netoa901ffe2016-06-08 14:11:40 +01003115void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003116{
David Netoa901ffe2016-06-08 14:11:40 +01003117 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3118 switch (glslangBuiltIn)
3119 {
3120 case glslang::EbvClipDistance:
3121 case glslang::EbvCullDistance:
3122 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003123#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003124 case glslang::EbvViewportMaskNV:
3125 case glslang::EbvSecondaryPositionNV:
3126 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003127 case glslang::EbvPositionPerViewNV:
3128 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08003129#endif
David Netoa901ffe2016-06-08 14:11:40 +01003130 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3131 // Alternately, we could just call this for any glslang built-in, since the
3132 // capability already guards against duplicates.
3133 TranslateBuiltInDecoration(glslangBuiltIn, false);
3134 break;
3135 default:
3136 // Capabilities were already generated when the struct was declared.
3137 break;
3138 }
John Kessenichebb50532016-05-16 19:22:05 -06003139}
3140
John Kessenich6fccb3c2016-09-19 16:01:41 -06003141bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003142{
John Kessenicheee9d532016-09-19 18:09:30 -06003143 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003144}
3145
John Kessenichd41993d2017-09-10 15:21:05 -06003146// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003147// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3148// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd41993d2017-09-10 15:21:05 -06003149bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier)
3150{
John Kessenich6a14f782017-12-04 02:48:10 -07003151 assert(qualifier == glslang::EvqIn ||
3152 qualifier == glslang::EvqOut ||
3153 qualifier == glslang::EvqInOut ||
3154 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003155 return qualifier != glslang::EvqConstReadOnly;
3156}
3157
3158// Is parameter pass-by-original?
3159bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3160 bool implicitThisParam)
3161{
3162 if (implicitThisParam) // implicit this
3163 return true;
3164 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003165 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003166 return paramType.containsOpaque() || // sampler, etc.
3167 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3168}
3169
John Kessenich140f3df2015-06-26 16:58:36 -06003170// Make all the functions, skeletally, without actually visiting their bodies.
3171void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3172{
John Kessenichfad62972017-07-18 02:35:46 -06003173 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
3174 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3175 if (paramPrecision != spv::NoPrecision)
3176 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06003177 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06003178 };
3179
John Kessenich140f3df2015-06-26 16:58:36 -06003180 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3181 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003182 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003183 continue;
3184
3185 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003186 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003187 //
qining25262b32016-05-06 17:25:16 -04003188 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003189 // function. What it is an address of varies:
3190 //
John Kessenich4bf71552016-09-02 11:20:21 -06003191 // - "in" parameters not marked as "const" can be written to without modifying the calling
3192 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003193 //
3194 // - "const in" parameters can just be the r-value, as no writes need occur.
3195 //
John Kessenich4bf71552016-09-02 11:20:21 -06003196 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3197 // 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 -06003198
3199 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003200 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003201 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3202
John Kessenichfad62972017-07-18 02:35:46 -06003203 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3204 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003205
John Kessenichfad62972017-07-18 02:35:46 -06003206 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003207 for (int p = 0; p < (int)parameters.size(); ++p) {
3208 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3209 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003210 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003211 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003212 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003213 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3214 else
John Kessenich4bf71552016-09-02 11:20:21 -06003215 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003216 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003217 paramTypes.push_back(typeId);
3218 }
3219
3220 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003221 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3222 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003223 glslFunction->getName().c_str(), paramTypes,
3224 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003225 if (implicitThis)
3226 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003227
3228 // Track function to emit/call later
3229 functionMap[glslFunction->getName().c_str()] = function;
3230
3231 // Set the parameter id's
3232 for (int p = 0; p < (int)parameters.size(); ++p) {
3233 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3234 // give a name too
3235 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3236 }
3237 }
3238}
3239
3240// Process all the initializers, while skipping the functions and link objects
3241void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3242{
3243 builder.setBuildPoint(shaderEntry->getLastBlock());
3244 for (int i = 0; i < (int)initializers.size(); ++i) {
3245 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3246 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3247
3248 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003249 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003250 initializer->traverse(this);
3251 }
3252 }
3253}
3254
3255// Process all the functions, while skipping initializers.
3256void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3257{
3258 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3259 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003260 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003261 node->traverse(this);
3262 }
3263}
3264
3265void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3266{
qining25262b32016-05-06 17:25:16 -04003267 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003268 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003269 currentFunction = functionMap[node->getName().c_str()];
3270 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003271 builder.setBuildPoint(functionBlock);
3272}
3273
Rex Xu04db3f52015-09-16 11:44:02 +08003274void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003275{
Rex Xufc618912015-09-09 16:42:49 +08003276 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003277
3278 glslang::TSampler sampler = {};
3279 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003280#ifdef AMD_EXTENSIONS
3281 bool f16ShadowCompare = false;
3282#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003283 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003284 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3285 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003286#ifdef AMD_EXTENSIONS
3287 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3288#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003289 }
3290
John Kessenich140f3df2015-06-26 16:58:36 -06003291 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3292 builder.clearAccessChain();
3293 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003294
3295 // Special case l-value operands
3296 bool lvalue = false;
3297 switch (node.getOp()) {
3298 case glslang::EOpImageAtomicAdd:
3299 case glslang::EOpImageAtomicMin:
3300 case glslang::EOpImageAtomicMax:
3301 case glslang::EOpImageAtomicAnd:
3302 case glslang::EOpImageAtomicOr:
3303 case glslang::EOpImageAtomicXor:
3304 case glslang::EOpImageAtomicExchange:
3305 case glslang::EOpImageAtomicCompSwap:
3306 if (i == 0)
3307 lvalue = true;
3308 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003309 case glslang::EOpSparseImageLoad:
3310 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3311 lvalue = true;
3312 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003313#ifdef AMD_EXTENSIONS
3314 case glslang::EOpSparseTexture:
3315 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3316 lvalue = true;
3317 break;
3318 case glslang::EOpSparseTextureClamp:
3319 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3320 lvalue = true;
3321 break;
3322 case glslang::EOpSparseTextureLod:
3323 case glslang::EOpSparseTextureOffset:
3324 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
3325 lvalue = true;
3326 break;
3327#else
Rex Xu48edadf2015-12-31 16:11:41 +08003328 case glslang::EOpSparseTexture:
3329 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3330 lvalue = true;
3331 break;
3332 case glslang::EOpSparseTextureClamp:
3333 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3334 lvalue = true;
3335 break;
3336 case glslang::EOpSparseTextureLod:
3337 case glslang::EOpSparseTextureOffset:
3338 if (i == 3)
3339 lvalue = true;
3340 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003341#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003342 case glslang::EOpSparseTextureFetch:
3343 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3344 lvalue = true;
3345 break;
3346 case glslang::EOpSparseTextureFetchOffset:
3347 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3348 lvalue = true;
3349 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003350#ifdef AMD_EXTENSIONS
3351 case glslang::EOpSparseTextureLodOffset:
3352 case glslang::EOpSparseTextureGrad:
3353 case glslang::EOpSparseTextureOffsetClamp:
3354 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
3355 lvalue = true;
3356 break;
3357 case glslang::EOpSparseTextureGradOffset:
3358 case glslang::EOpSparseTextureGradClamp:
3359 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
3360 lvalue = true;
3361 break;
3362 case glslang::EOpSparseTextureGradOffsetClamp:
3363 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
3364 lvalue = true;
3365 break;
3366#else
Rex Xu48edadf2015-12-31 16:11:41 +08003367 case glslang::EOpSparseTextureLodOffset:
3368 case glslang::EOpSparseTextureGrad:
3369 case glslang::EOpSparseTextureOffsetClamp:
3370 if (i == 4)
3371 lvalue = true;
3372 break;
3373 case glslang::EOpSparseTextureGradOffset:
3374 case glslang::EOpSparseTextureGradClamp:
3375 if (i == 5)
3376 lvalue = true;
3377 break;
3378 case glslang::EOpSparseTextureGradOffsetClamp:
3379 if (i == 6)
3380 lvalue = true;
3381 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003382#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08003383 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003384 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3385 lvalue = true;
3386 break;
3387 case glslang::EOpSparseTextureGatherOffset:
3388 case glslang::EOpSparseTextureGatherOffsets:
3389 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3390 lvalue = true;
3391 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003392#ifdef AMD_EXTENSIONS
3393 case glslang::EOpSparseTextureGatherLod:
3394 if (i == 3)
3395 lvalue = true;
3396 break;
3397 case glslang::EOpSparseTextureGatherLodOffset:
3398 case glslang::EOpSparseTextureGatherLodOffsets:
3399 if (i == 4)
3400 lvalue = true;
3401 break;
Rex Xu129799a2017-07-05 17:23:28 +08003402 case glslang::EOpSparseImageLoadLod:
3403 if (i == 3)
3404 lvalue = true;
3405 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003406#endif
Rex Xufc618912015-09-09 16:42:49 +08003407 default:
3408 break;
3409 }
3410
Rex Xu6b86d492015-09-16 17:48:22 +08003411 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003412 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003413 else
John Kessenich32cfd492016-02-02 12:37:46 -07003414 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003415 }
3416}
3417
John Kessenichfc51d282015-08-19 13:34:18 -06003418void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003419{
John Kessenichfc51d282015-08-19 13:34:18 -06003420 builder.clearAccessChain();
3421 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003422 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003423}
John Kessenich140f3df2015-06-26 16:58:36 -06003424
John Kessenichfc51d282015-08-19 13:34:18 -06003425spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3426{
John Kesseniche485c7a2017-05-31 18:50:53 -06003427 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003428 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003429
3430 builder.setLine(node->getLoc().line);
3431
John Kessenichfc51d282015-08-19 13:34:18 -06003432 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003433 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3434 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08003435#ifdef AMD_EXTENSIONS
3436 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
3437 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
3438 : false;
3439#endif
3440
John Kessenichfc51d282015-08-19 13:34:18 -06003441 std::vector<spv::Id> arguments;
3442 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003443 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003444 else
3445 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003446 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003447
3448 spv::Builder::TextureParameters params = { };
3449 params.sampler = arguments[0];
3450
Rex Xu04db3f52015-09-16 11:44:02 +08003451 glslang::TCrackedTextureOp cracked;
3452 node->crackTexture(sampler, cracked);
3453
amhagan05506bb2017-06-13 16:53:02 -04003454 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003455
John Kessenichfc51d282015-08-19 13:34:18 -06003456 // Check for queries
3457 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003458 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3459 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003460 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003461
John Kessenichfc51d282015-08-19 13:34:18 -06003462 switch (node->getOp()) {
3463 case glslang::EOpImageQuerySize:
3464 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003465 if (arguments.size() > 1) {
3466 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003467 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003468 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003469 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003470 case glslang::EOpImageQuerySamples:
3471 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003472 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003473 case glslang::EOpTextureQueryLod:
3474 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003475 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003476 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003477 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003478 case glslang::EOpSparseTexelsResident:
3479 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003480 default:
3481 assert(0);
3482 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003483 }
John Kessenich140f3df2015-06-26 16:58:36 -06003484 }
3485
LoopDawg4425f242018-02-18 11:40:01 -07003486 int components = node->getType().getVectorSize();
3487
3488 if (node->getOp() == glslang::EOpTextureFetch) {
3489 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3490 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3491 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3492 // here around e.g. which ones return scalars or other types.
3493 components = 4;
3494 }
3495
3496 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3497
3498 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3499
Rex Xufc618912015-09-09 16:42:49 +08003500 // Check for image functions other than queries
3501 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003502 std::vector<spv::Id> operands;
3503 auto opIt = arguments.begin();
3504 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003505
3506 // Handle subpass operations
3507 // TODO: GLSL should change to have the "MS" only on the type rather than the
3508 // built-in function.
3509 if (cracked.subpass) {
3510 // add on the (0,0) coordinate
3511 spv::Id zero = builder.makeIntConstant(0);
3512 std::vector<spv::Id> comps;
3513 comps.push_back(zero);
3514 comps.push_back(zero);
3515 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3516 if (sampler.ms) {
3517 operands.push_back(spv::ImageOperandsSampleMask);
3518 operands.push_back(*(opIt++));
3519 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003520 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3521 builder.setPrecision(result, precision);
3522 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003523 }
3524
John Kessenich56bab042015-09-16 10:54:31 -06003525 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003526#ifdef AMD_EXTENSIONS
3527 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3528#else
John Kessenich56bab042015-09-16 10:54:31 -06003529 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003530#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003531 if (sampler.ms) {
3532 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003533 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003534#ifdef AMD_EXTENSIONS
3535 } else if (cracked.lod) {
3536 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3537 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3538
3539 operands.push_back(spv::ImageOperandsLodMask);
3540 operands.push_back(*opIt);
3541#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003542 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003543 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3544 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003545
LoopDawg4425f242018-02-18 11:40:01 -07003546 std::vector<spv::Id> result = { builder.createOp(spv::OpImageRead, resultType(), operands) };
3547 builder.setPrecision(result[0], precision);
3548
3549 // If needed, add a conversion constructor to the proper size.
3550 if (components != node->getType().getVectorSize())
3551 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3552
3553 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08003554#ifdef AMD_EXTENSIONS
3555 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3556#else
John Kessenich56bab042015-09-16 10:54:31 -06003557 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003558#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003559 if (sampler.ms) {
3560 operands.push_back(*(opIt + 1));
3561 operands.push_back(spv::ImageOperandsSampleMask);
3562 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003563#ifdef AMD_EXTENSIONS
3564 } else if (cracked.lod) {
3565 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3566 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3567
3568 operands.push_back(*(opIt + 1));
3569 operands.push_back(spv::ImageOperandsLodMask);
3570 operands.push_back(*opIt);
3571#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003572 } else
3573 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003574 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003575 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3576 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003577 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003578#ifdef AMD_EXTENSIONS
3579 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3580#else
Rex Xu5eafa472016-02-19 22:24:03 +08003581 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003582#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003583 builder.addCapability(spv::CapabilitySparseResidency);
3584 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3585 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3586
3587 if (sampler.ms) {
3588 operands.push_back(spv::ImageOperandsSampleMask);
3589 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003590#ifdef AMD_EXTENSIONS
3591 } else if (cracked.lod) {
3592 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3593 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3594
3595 operands.push_back(spv::ImageOperandsLodMask);
3596 operands.push_back(*opIt++);
3597#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003598 }
3599
3600 // Create the return type that was a special structure
3601 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003602 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003603 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3604 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3605
3606 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3607
3608 // Decode the return type
3609 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3610 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003611 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003612 // Process image atomic operations
3613
3614 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3615 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003616 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003617
John Kessenich8c8505c2016-07-26 12:50:38 -06003618 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003619 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003620
3621 std::vector<spv::Id> operands;
3622 operands.push_back(pointer);
3623 for (; opIt != arguments.end(); ++opIt)
3624 operands.push_back(*opIt);
3625
John Kessenich8c8505c2016-07-26 12:50:38 -06003626 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003627 }
3628 }
3629
amhagan05506bb2017-06-13 16:53:02 -04003630#ifdef AMD_EXTENSIONS
3631 // Check for fragment mask functions other than queries
3632 if (cracked.fragMask) {
3633 assert(sampler.ms);
3634
3635 auto opIt = arguments.begin();
3636 std::vector<spv::Id> operands;
3637
3638 // Extract the image if necessary
3639 if (builder.isSampledImage(params.sampler))
3640 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3641
3642 operands.push_back(params.sampler);
3643 ++opIt;
3644
3645 if (sampler.isSubpass()) {
3646 // add on the (0,0) coordinate
3647 spv::Id zero = builder.makeIntConstant(0);
3648 std::vector<spv::Id> comps;
3649 comps.push_back(zero);
3650 comps.push_back(zero);
3651 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3652 }
3653
3654 for (; opIt != arguments.end(); ++opIt)
3655 operands.push_back(*opIt);
3656
3657 spv::Op fragMaskOp = spv::OpNop;
3658 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3659 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3660 else if (node->getOp() == glslang::EOpFragmentFetch)
3661 fragMaskOp = spv::OpFragmentFetchAMD;
3662
3663 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3664 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3665 return builder.createOp(fragMaskOp, resultType(), operands);
3666 }
3667#endif
3668
Rex Xufc618912015-09-09 16:42:49 +08003669 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003670 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003671 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3672
John Kessenichfc51d282015-08-19 13:34:18 -06003673 // check for bias argument
3674 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003675#ifdef AMD_EXTENSIONS
3676 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3677#else
Rex Xu71519fe2015-11-11 15:35:47 +08003678 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003679#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003680 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003681#ifdef AMD_EXTENSIONS
3682 if (cracked.gather)
3683 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08003684
3685 if (f16ShadowCompare)
3686 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003687#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003688 if (cracked.offset)
3689 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003690#ifdef AMD_EXTENSIONS
3691 else if (cracked.offsets)
3692 ++nonBiasArgCount;
3693#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003694 if (cracked.grad)
3695 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003696 if (cracked.lodClamp)
3697 ++nonBiasArgCount;
3698 if (sparse)
3699 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003700
3701 if ((int)arguments.size() > nonBiasArgCount)
3702 bias = true;
3703 }
3704
John Kessenicha5c33d62016-06-02 23:45:21 -06003705 // See if the sampler param should really be just the SPV image part
3706 if (cracked.fetch) {
3707 // a fetch needs to have the image extracted first
3708 if (builder.isSampledImage(params.sampler))
3709 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3710 }
3711
Rex Xu225e0fc2016-11-17 17:47:59 +08003712#ifdef AMD_EXTENSIONS
3713 if (cracked.gather) {
3714 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3715 if (bias || cracked.lod ||
3716 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3717 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003718 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003719 }
3720 }
3721#endif
3722
John Kessenichfc51d282015-08-19 13:34:18 -06003723 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003724
John Kessenichfc51d282015-08-19 13:34:18 -06003725 params.coords = arguments[1];
3726 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003727 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003728
3729 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08003730#ifdef AMD_EXTENSIONS
3731 if (cubeCompare || f16ShadowCompare) {
3732#else
Rex Xu48edadf2015-12-31 16:11:41 +08003733 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08003734#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003735 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003736 ++extraArgs;
3737 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003738 params.Dref = arguments[2];
3739 ++extraArgs;
3740 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003741 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003742 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003743 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003744 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003745 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003746 dRefComp = builder.getNumComponents(params.coords) - 1;
3747 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003748 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3749 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003750
3751 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003752 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003753 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003754 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003755 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3756 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3757 noImplicitLod = true;
3758 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003759
3760 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003761 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003762 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003763 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003764 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003765
3766 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003767 if (cracked.grad) {
3768 params.gradX = arguments[2 + extraArgs];
3769 params.gradY = arguments[3 + extraArgs];
3770 extraArgs += 2;
3771 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003772
3773 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003774 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003775 params.offset = arguments[2 + extraArgs];
3776 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003777 } else if (cracked.offsets) {
3778 params.offsets = arguments[2 + extraArgs];
3779 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003780 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003781
3782 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003783 if (cracked.lodClamp) {
3784 params.lodClamp = arguments[2 + extraArgs];
3785 ++extraArgs;
3786 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003787
3788 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003789 if (sparse) {
3790 params.texelOut = arguments[2 + extraArgs];
3791 ++extraArgs;
3792 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003793
John Kessenich76d4dfc2016-06-16 12:43:23 -06003794 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003795 if (cracked.gather && ! sampler.shadow) {
3796 // default component is 0, if missing, otherwise an argument
3797 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003798 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003799 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003800 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003801 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003802 }
3803
3804 // bias
3805 if (bias) {
3806 params.bias = arguments[2 + extraArgs];
3807 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003808 }
John Kessenichfc51d282015-08-19 13:34:18 -06003809
John Kessenich65336482016-06-16 14:06:26 -06003810 // projective component (might not to move)
3811 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3812 // are divided by the last component of P."
3813 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3814 // unused components will appear after all used components."
3815 if (cracked.proj) {
3816 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3817 int projTargetComp;
3818 switch (sampler.dim) {
3819 case glslang::Esd1D: projTargetComp = 1; break;
3820 case glslang::Esd2D: projTargetComp = 2; break;
3821 case glslang::EsdRect: projTargetComp = 2; break;
3822 default: projTargetComp = projSourceComp; break;
3823 }
3824 // copy the projective coordinate if we have to
3825 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003826 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003827 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3828 projSourceComp);
3829 params.coords = builder.createCompositeInsert(projComp, params.coords,
3830 builder.getTypeId(params.coords), projTargetComp);
3831 }
3832 }
3833
LoopDawg4425f242018-02-18 11:40:01 -07003834 std::vector<spv::Id> result = {
3835 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
3836 };
3837
3838 if (components != node->getType().getVectorSize())
3839 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3840
3841 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06003842}
3843
3844spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3845{
3846 // Grab the function's pointer from the previously created function
3847 spv::Function* function = functionMap[node->getName().c_str()];
3848 if (! function)
3849 return 0;
3850
3851 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3852 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3853
3854 // See comments in makeFunctions() for details about the semantics for parameter passing.
3855 //
3856 // These imply we need a four step process:
3857 // 1. Evaluate the arguments
3858 // 2. Allocate and make copies of in, out, and inout arguments
3859 // 3. Make the call
3860 // 4. Copy back the results
3861
3862 // 1. Evaluate the arguments
3863 std::vector<spv::Builder::AccessChain> lValues;
3864 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003865 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003866 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003867 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003868 // build l-value
3869 builder.clearAccessChain();
3870 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003871 argTypes.push_back(&paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003872 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenich6a14f782017-12-04 02:48:10 -07003873 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0) ||
3874 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003875 // save l-value
3876 lValues.push_back(builder.getAccessChain());
3877 } else {
3878 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003879 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003880 }
3881 }
3882
3883 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3884 // copy the original into that space.
3885 //
3886 // Also, build up the list of actual arguments to pass in for the call
3887 int lValueCount = 0;
3888 int rValueCount = 0;
3889 std::vector<spv::Id> spvArgs;
3890 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003891 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003892 spv::Id arg;
John Kessenichd41993d2017-09-10 15:21:05 -06003893 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003894 builder.setAccessChain(lValues[lValueCount]);
3895 arg = builder.accessChainGetLValue();
3896 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06003897 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003898 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003899 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3900 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3901 // need to copy the input into output space
3902 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003903 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003904 builder.clearAccessChain();
3905 builder.setAccessChainLValue(arg);
3906 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003907 }
3908 ++lValueCount;
3909 } else {
3910 arg = rValues[rValueCount];
3911 ++rValueCount;
3912 }
3913 spvArgs.push_back(arg);
3914 }
3915
3916 // 3. Make the call.
3917 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003918 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003919
3920 // 4. Copy back out an "out" arguments.
3921 lValueCount = 0;
3922 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003923 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenichd41993d2017-09-10 15:21:05 -06003924 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0))
3925 ++lValueCount;
3926 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003927 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3928 spv::Id copy = builder.createLoad(spvArgs[a]);
3929 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003930 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003931 }
3932 ++lValueCount;
3933 }
3934 }
3935
3936 return result;
3937}
3938
3939// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003940spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3941 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003942 spv::Id typeId, spv::Id left, spv::Id right,
3943 glslang::TBasicType typeProxy, bool reduceComparison)
3944{
John Kessenich66011cb2018-03-06 16:12:04 -07003945 bool isUnsigned = isTypeUnsignedInt(typeProxy);
3946 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08003947 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003948
3949 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003950 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003951 bool comparison = false;
3952
3953 switch (op) {
3954 case glslang::EOpAdd:
3955 case glslang::EOpAddAssign:
3956 if (isFloat)
3957 binOp = spv::OpFAdd;
3958 else
3959 binOp = spv::OpIAdd;
3960 break;
3961 case glslang::EOpSub:
3962 case glslang::EOpSubAssign:
3963 if (isFloat)
3964 binOp = spv::OpFSub;
3965 else
3966 binOp = spv::OpISub;
3967 break;
3968 case glslang::EOpMul:
3969 case glslang::EOpMulAssign:
3970 if (isFloat)
3971 binOp = spv::OpFMul;
3972 else
3973 binOp = spv::OpIMul;
3974 break;
3975 case glslang::EOpVectorTimesScalar:
3976 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003977 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003978 if (builder.isVector(right))
3979 std::swap(left, right);
3980 assert(builder.isScalar(right));
3981 needMatchingVectors = false;
3982 binOp = spv::OpVectorTimesScalar;
3983 } else
3984 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003985 break;
3986 case glslang::EOpVectorTimesMatrix:
3987 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003988 binOp = spv::OpVectorTimesMatrix;
3989 break;
3990 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003991 binOp = spv::OpMatrixTimesVector;
3992 break;
3993 case glslang::EOpMatrixTimesScalar:
3994 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003995 binOp = spv::OpMatrixTimesScalar;
3996 break;
3997 case glslang::EOpMatrixTimesMatrix:
3998 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003999 binOp = spv::OpMatrixTimesMatrix;
4000 break;
4001 case glslang::EOpOuterProduct:
4002 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004003 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004004 break;
4005
4006 case glslang::EOpDiv:
4007 case glslang::EOpDivAssign:
4008 if (isFloat)
4009 binOp = spv::OpFDiv;
4010 else if (isUnsigned)
4011 binOp = spv::OpUDiv;
4012 else
4013 binOp = spv::OpSDiv;
4014 break;
4015 case glslang::EOpMod:
4016 case glslang::EOpModAssign:
4017 if (isFloat)
4018 binOp = spv::OpFMod;
4019 else if (isUnsigned)
4020 binOp = spv::OpUMod;
4021 else
4022 binOp = spv::OpSMod;
4023 break;
4024 case glslang::EOpRightShift:
4025 case glslang::EOpRightShiftAssign:
4026 if (isUnsigned)
4027 binOp = spv::OpShiftRightLogical;
4028 else
4029 binOp = spv::OpShiftRightArithmetic;
4030 break;
4031 case glslang::EOpLeftShift:
4032 case glslang::EOpLeftShiftAssign:
4033 binOp = spv::OpShiftLeftLogical;
4034 break;
4035 case glslang::EOpAnd:
4036 case glslang::EOpAndAssign:
4037 binOp = spv::OpBitwiseAnd;
4038 break;
4039 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004040 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004041 binOp = spv::OpLogicalAnd;
4042 break;
4043 case glslang::EOpInclusiveOr:
4044 case glslang::EOpInclusiveOrAssign:
4045 binOp = spv::OpBitwiseOr;
4046 break;
4047 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004048 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004049 binOp = spv::OpLogicalOr;
4050 break;
4051 case glslang::EOpExclusiveOr:
4052 case glslang::EOpExclusiveOrAssign:
4053 binOp = spv::OpBitwiseXor;
4054 break;
4055 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004056 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004057 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004058 break;
4059
4060 case glslang::EOpLessThan:
4061 case glslang::EOpGreaterThan:
4062 case glslang::EOpLessThanEqual:
4063 case glslang::EOpGreaterThanEqual:
4064 case glslang::EOpEqual:
4065 case glslang::EOpNotEqual:
4066 case glslang::EOpVectorEqual:
4067 case glslang::EOpVectorNotEqual:
4068 comparison = true;
4069 break;
4070 default:
4071 break;
4072 }
4073
John Kessenich7c1aa102015-10-15 13:29:11 -06004074 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004075 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004076 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07004077 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04004078 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004079
4080 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004081 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06004082 builder.promoteScalar(precision, left, right);
4083
qining25262b32016-05-06 17:25:16 -04004084 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenich5d610ee2018-03-07 18:05:55 -07004085 builder.addDecoration(result, noContraction);
qining25262b32016-05-06 17:25:16 -04004086 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004087 }
4088
4089 if (! comparison)
4090 return 0;
4091
John Kessenich7c1aa102015-10-15 13:29:11 -06004092 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004093
John Kessenich4583b612016-08-07 19:14:22 -06004094 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
4095 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07004096 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06004097
4098 switch (op) {
4099 case glslang::EOpLessThan:
4100 if (isFloat)
4101 binOp = spv::OpFOrdLessThan;
4102 else if (isUnsigned)
4103 binOp = spv::OpULessThan;
4104 else
4105 binOp = spv::OpSLessThan;
4106 break;
4107 case glslang::EOpGreaterThan:
4108 if (isFloat)
4109 binOp = spv::OpFOrdGreaterThan;
4110 else if (isUnsigned)
4111 binOp = spv::OpUGreaterThan;
4112 else
4113 binOp = spv::OpSGreaterThan;
4114 break;
4115 case glslang::EOpLessThanEqual:
4116 if (isFloat)
4117 binOp = spv::OpFOrdLessThanEqual;
4118 else if (isUnsigned)
4119 binOp = spv::OpULessThanEqual;
4120 else
4121 binOp = spv::OpSLessThanEqual;
4122 break;
4123 case glslang::EOpGreaterThanEqual:
4124 if (isFloat)
4125 binOp = spv::OpFOrdGreaterThanEqual;
4126 else if (isUnsigned)
4127 binOp = spv::OpUGreaterThanEqual;
4128 else
4129 binOp = spv::OpSGreaterThanEqual;
4130 break;
4131 case glslang::EOpEqual:
4132 case glslang::EOpVectorEqual:
4133 if (isFloat)
4134 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004135 else if (isBool)
4136 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004137 else
4138 binOp = spv::OpIEqual;
4139 break;
4140 case glslang::EOpNotEqual:
4141 case glslang::EOpVectorNotEqual:
4142 if (isFloat)
4143 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004144 else if (isBool)
4145 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004146 else
4147 binOp = spv::OpINotEqual;
4148 break;
4149 default:
4150 break;
4151 }
4152
qining25262b32016-05-06 17:25:16 -04004153 if (binOp != spv::OpNop) {
4154 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenich5d610ee2018-03-07 18:05:55 -07004155 builder.addDecoration(result, noContraction);
qining25262b32016-05-06 17:25:16 -04004156 return builder.setPrecision(result, precision);
4157 }
John Kessenich140f3df2015-06-26 16:58:36 -06004158
4159 return 0;
4160}
4161
John Kessenich04bb8a02015-12-12 12:28:14 -07004162//
4163// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
4164// These can be any of:
4165//
4166// matrix * scalar
4167// scalar * matrix
4168// matrix * matrix linear algebraic
4169// matrix * vector
4170// vector * matrix
4171// matrix * matrix componentwise
4172// matrix op matrix op in {+, -, /}
4173// matrix op scalar op in {+, -, /}
4174// scalar op matrix op in {+, -, /}
4175//
qining25262b32016-05-06 17:25:16 -04004176spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07004177{
4178 bool firstClass = true;
4179
4180 // First, handle first-class matrix operations (* and matrix/scalar)
4181 switch (op) {
4182 case spv::OpFDiv:
4183 if (builder.isMatrix(left) && builder.isScalar(right)) {
4184 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01004185 spv::Id resultType = builder.getTypeId(right);
4186 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07004187 op = spv::OpMatrixTimesScalar;
4188 } else
4189 firstClass = false;
4190 break;
4191 case spv::OpMatrixTimesScalar:
4192 if (builder.isMatrix(right))
4193 std::swap(left, right);
4194 assert(builder.isScalar(right));
4195 break;
4196 case spv::OpVectorTimesMatrix:
4197 assert(builder.isVector(left));
4198 assert(builder.isMatrix(right));
4199 break;
4200 case spv::OpMatrixTimesVector:
4201 assert(builder.isMatrix(left));
4202 assert(builder.isVector(right));
4203 break;
4204 case spv::OpMatrixTimesMatrix:
4205 assert(builder.isMatrix(left));
4206 assert(builder.isMatrix(right));
4207 break;
4208 default:
4209 firstClass = false;
4210 break;
4211 }
4212
qining25262b32016-05-06 17:25:16 -04004213 if (firstClass) {
4214 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenich5d610ee2018-03-07 18:05:55 -07004215 builder.addDecoration(result, noContraction);
qining25262b32016-05-06 17:25:16 -04004216 return builder.setPrecision(result, precision);
4217 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004218
LoopDawg592860c2016-06-09 08:57:35 -06004219 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004220 // The result type of all of them is the same type as the (a) matrix operand.
4221 // The algorithm is to:
4222 // - break the matrix(es) into vectors
4223 // - smear any scalar to a vector
4224 // - do vector operations
4225 // - make a matrix out the vector results
4226 switch (op) {
4227 case spv::OpFAdd:
4228 case spv::OpFSub:
4229 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004230 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004231 case spv::OpFMul:
4232 {
4233 // one time set up...
4234 bool leftMat = builder.isMatrix(left);
4235 bool rightMat = builder.isMatrix(right);
4236 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4237 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4238 spv::Id scalarType = builder.getScalarTypeId(typeId);
4239 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4240 std::vector<spv::Id> results;
4241 spv::Id smearVec = spv::NoResult;
4242 if (builder.isScalar(left))
4243 smearVec = builder.smearScalar(precision, left, vecType);
4244 else if (builder.isScalar(right))
4245 smearVec = builder.smearScalar(precision, right, vecType);
4246
4247 // do each vector op
4248 for (unsigned int c = 0; c < numCols; ++c) {
4249 std::vector<unsigned int> indexes;
4250 indexes.push_back(c);
4251 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4252 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004253 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenich5d610ee2018-03-07 18:05:55 -07004254 builder.addDecoration(result, noContraction);
qining25262b32016-05-06 17:25:16 -04004255 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004256 }
4257
4258 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004259 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07004260 }
4261 default:
4262 assert(0);
4263 return spv::NoResult;
4264 }
4265}
4266
qining25262b32016-05-06 17:25:16 -04004267spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004268{
4269 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004270 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004271 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07004272 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4273 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004274
4275 switch (op) {
4276 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004277 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004278 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004279 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04004280 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004281 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004282 unaryOp = spv::OpSNegate;
4283 break;
4284
4285 case glslang::EOpLogicalNot:
4286 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004287 unaryOp = spv::OpLogicalNot;
4288 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004289 case glslang::EOpBitwiseNot:
4290 unaryOp = spv::OpNot;
4291 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004292
John Kessenich140f3df2015-06-26 16:58:36 -06004293 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004294 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004295 break;
4296 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004297 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004298 break;
4299 case glslang::EOpTranspose:
4300 unaryOp = spv::OpTranspose;
4301 break;
4302
4303 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004304 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004305 break;
4306 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004307 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004308 break;
4309 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004310 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004311 break;
4312 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004313 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004314 break;
4315 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004316 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004317 break;
4318 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004319 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004320 break;
4321 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004322 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004323 break;
4324 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004325 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004326 break;
4327
4328 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004329 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004330 break;
4331 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004332 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004333 break;
4334 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004335 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004336 break;
4337 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004338 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004339 break;
4340 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004341 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004342 break;
4343 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004344 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004345 break;
4346
4347 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004348 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004349 break;
4350 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004351 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004352 break;
4353
4354 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004355 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004356 break;
4357 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004358 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004359 break;
4360 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004361 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004362 break;
4363 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004364 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004365 break;
4366 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004367 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004368 break;
4369 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004370 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004371 break;
4372
4373 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004374 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004375 break;
4376 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004377 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004378 break;
4379 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004380 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004381 break;
4382 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004383 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004384 break;
4385 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004386 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004387 break;
4388 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004389 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004390 break;
4391
4392 case glslang::EOpIsNan:
4393 unaryOp = spv::OpIsNan;
4394 break;
4395 case glslang::EOpIsInf:
4396 unaryOp = spv::OpIsInf;
4397 break;
LoopDawg592860c2016-06-09 08:57:35 -06004398 case glslang::EOpIsFinite:
4399 unaryOp = spv::OpIsFinite;
4400 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004401
Rex Xucbc426e2015-12-15 16:03:10 +08004402 case glslang::EOpFloatBitsToInt:
4403 case glslang::EOpFloatBitsToUint:
4404 case glslang::EOpIntBitsToFloat:
4405 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004406 case glslang::EOpDoubleBitsToInt64:
4407 case glslang::EOpDoubleBitsToUint64:
4408 case glslang::EOpInt64BitsToDouble:
4409 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004410 case glslang::EOpFloat16BitsToInt16:
4411 case glslang::EOpFloat16BitsToUint16:
4412 case glslang::EOpInt16BitsToFloat16:
4413 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08004414 unaryOp = spv::OpBitcast;
4415 break;
4416
John Kessenich140f3df2015-06-26 16:58:36 -06004417 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004418 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004419 break;
4420 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004421 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004422 break;
4423 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004424 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004425 break;
4426 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004427 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004428 break;
4429 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004430 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004431 break;
4432 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004433 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004434 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004435 case glslang::EOpPackSnorm4x8:
4436 libCall = spv::GLSLstd450PackSnorm4x8;
4437 break;
4438 case glslang::EOpUnpackSnorm4x8:
4439 libCall = spv::GLSLstd450UnpackSnorm4x8;
4440 break;
4441 case glslang::EOpPackUnorm4x8:
4442 libCall = spv::GLSLstd450PackUnorm4x8;
4443 break;
4444 case glslang::EOpUnpackUnorm4x8:
4445 libCall = spv::GLSLstd450UnpackUnorm4x8;
4446 break;
4447 case glslang::EOpPackDouble2x32:
4448 libCall = spv::GLSLstd450PackDouble2x32;
4449 break;
4450 case glslang::EOpUnpackDouble2x32:
4451 libCall = spv::GLSLstd450UnpackDouble2x32;
4452 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004453
Rex Xu8ff43de2016-04-22 16:51:45 +08004454 case glslang::EOpPackInt2x32:
4455 case glslang::EOpUnpackInt2x32:
4456 case glslang::EOpPackUint2x32:
4457 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07004458 case glslang::EOpPack16:
4459 case glslang::EOpPack32:
4460 case glslang::EOpPack64:
4461 case glslang::EOpUnpack32:
4462 case glslang::EOpUnpack16:
4463 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08004464 case glslang::EOpPackInt2x16:
4465 case glslang::EOpUnpackInt2x16:
4466 case glslang::EOpPackUint2x16:
4467 case glslang::EOpUnpackUint2x16:
4468 case glslang::EOpPackInt4x16:
4469 case glslang::EOpUnpackInt4x16:
4470 case glslang::EOpPackUint4x16:
4471 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004472 case glslang::EOpPackFloat2x16:
4473 case glslang::EOpUnpackFloat2x16:
4474 unaryOp = spv::OpBitcast;
4475 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004476
John Kessenich140f3df2015-06-26 16:58:36 -06004477 case glslang::EOpDPdx:
4478 unaryOp = spv::OpDPdx;
4479 break;
4480 case glslang::EOpDPdy:
4481 unaryOp = spv::OpDPdy;
4482 break;
4483 case glslang::EOpFwidth:
4484 unaryOp = spv::OpFwidth;
4485 break;
4486 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004487 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004488 unaryOp = spv::OpDPdxFine;
4489 break;
4490 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004491 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004492 unaryOp = spv::OpDPdyFine;
4493 break;
4494 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004495 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004496 unaryOp = spv::OpFwidthFine;
4497 break;
4498 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004499 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004500 unaryOp = spv::OpDPdxCoarse;
4501 break;
4502 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004503 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004504 unaryOp = spv::OpDPdyCoarse;
4505 break;
4506 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004507 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004508 unaryOp = spv::OpFwidthCoarse;
4509 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004510 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004511 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004512 libCall = spv::GLSLstd450InterpolateAtCentroid;
4513 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004514 case glslang::EOpAny:
4515 unaryOp = spv::OpAny;
4516 break;
4517 case glslang::EOpAll:
4518 unaryOp = spv::OpAll;
4519 break;
4520
4521 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004522 if (isFloat)
4523 libCall = spv::GLSLstd450FAbs;
4524 else
4525 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004526 break;
4527 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004528 if (isFloat)
4529 libCall = spv::GLSLstd450FSign;
4530 else
4531 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004532 break;
4533
John Kessenichfc51d282015-08-19 13:34:18 -06004534 case glslang::EOpAtomicCounterIncrement:
4535 case glslang::EOpAtomicCounterDecrement:
4536 case glslang::EOpAtomicCounter:
4537 {
4538 // Handle all of the atomics in one place, in createAtomicOperation()
4539 std::vector<spv::Id> operands;
4540 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004541 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004542 }
4543
John Kessenichfc51d282015-08-19 13:34:18 -06004544 case glslang::EOpBitFieldReverse:
4545 unaryOp = spv::OpBitReverse;
4546 break;
4547 case glslang::EOpBitCount:
4548 unaryOp = spv::OpBitCount;
4549 break;
4550 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004551 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004552 break;
4553 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004554 if (isUnsigned)
4555 libCall = spv::GLSLstd450FindUMsb;
4556 else
4557 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004558 break;
4559
Rex Xu574ab042016-04-14 16:53:07 +08004560 case glslang::EOpBallot:
4561 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004562 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004563 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004564 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004565#ifdef AMD_EXTENSIONS
4566 case glslang::EOpMinInvocations:
4567 case glslang::EOpMaxInvocations:
4568 case glslang::EOpAddInvocations:
4569 case glslang::EOpMinInvocationsNonUniform:
4570 case glslang::EOpMaxInvocationsNonUniform:
4571 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004572 case glslang::EOpMinInvocationsInclusiveScan:
4573 case glslang::EOpMaxInvocationsInclusiveScan:
4574 case glslang::EOpAddInvocationsInclusiveScan:
4575 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4576 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4577 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4578 case glslang::EOpMinInvocationsExclusiveScan:
4579 case glslang::EOpMaxInvocationsExclusiveScan:
4580 case glslang::EOpAddInvocationsExclusiveScan:
4581 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4582 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4583 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004584#endif
Rex Xu51596642016-09-21 18:56:12 +08004585 {
4586 std::vector<spv::Id> operands;
4587 operands.push_back(operand);
4588 return createInvocationsOperation(op, typeId, operands, typeProxy);
4589 }
John Kessenich66011cb2018-03-06 16:12:04 -07004590 case glslang::EOpSubgroupAll:
4591 case glslang::EOpSubgroupAny:
4592 case glslang::EOpSubgroupAllEqual:
4593 case glslang::EOpSubgroupBroadcastFirst:
4594 case glslang::EOpSubgroupBallot:
4595 case glslang::EOpSubgroupInverseBallot:
4596 case glslang::EOpSubgroupBallotBitCount:
4597 case glslang::EOpSubgroupBallotInclusiveBitCount:
4598 case glslang::EOpSubgroupBallotExclusiveBitCount:
4599 case glslang::EOpSubgroupBallotFindLSB:
4600 case glslang::EOpSubgroupBallotFindMSB:
4601 case glslang::EOpSubgroupAdd:
4602 case glslang::EOpSubgroupMul:
4603 case glslang::EOpSubgroupMin:
4604 case glslang::EOpSubgroupMax:
4605 case glslang::EOpSubgroupAnd:
4606 case glslang::EOpSubgroupOr:
4607 case glslang::EOpSubgroupXor:
4608 case glslang::EOpSubgroupInclusiveAdd:
4609 case glslang::EOpSubgroupInclusiveMul:
4610 case glslang::EOpSubgroupInclusiveMin:
4611 case glslang::EOpSubgroupInclusiveMax:
4612 case glslang::EOpSubgroupInclusiveAnd:
4613 case glslang::EOpSubgroupInclusiveOr:
4614 case glslang::EOpSubgroupInclusiveXor:
4615 case glslang::EOpSubgroupExclusiveAdd:
4616 case glslang::EOpSubgroupExclusiveMul:
4617 case glslang::EOpSubgroupExclusiveMin:
4618 case glslang::EOpSubgroupExclusiveMax:
4619 case glslang::EOpSubgroupExclusiveAnd:
4620 case glslang::EOpSubgroupExclusiveOr:
4621 case glslang::EOpSubgroupExclusiveXor:
4622 case glslang::EOpSubgroupQuadSwapHorizontal:
4623 case glslang::EOpSubgroupQuadSwapVertical:
4624 case glslang::EOpSubgroupQuadSwapDiagonal: {
4625 std::vector<spv::Id> operands;
4626 operands.push_back(operand);
4627 return createSubgroupOperation(op, typeId, operands, typeProxy);
4628 }
Rex Xu9d93a232016-05-05 12:30:44 +08004629#ifdef AMD_EXTENSIONS
4630 case glslang::EOpMbcnt:
4631 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4632 libCall = spv::MbcntAMD;
4633 break;
4634
4635 case glslang::EOpCubeFaceIndex:
4636 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4637 libCall = spv::CubeFaceIndexAMD;
4638 break;
4639
4640 case glslang::EOpCubeFaceCoord:
4641 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4642 libCall = spv::CubeFaceCoordAMD;
4643 break;
4644#endif
Rex Xu338b1852016-05-05 20:38:33 +08004645
John Kessenich140f3df2015-06-26 16:58:36 -06004646 default:
4647 return 0;
4648 }
4649
4650 spv::Id id;
4651 if (libCall >= 0) {
4652 std::vector<spv::Id> args;
4653 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004654 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004655 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004656 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004657 }
John Kessenich140f3df2015-06-26 16:58:36 -06004658
John Kessenich5d610ee2018-03-07 18:05:55 -07004659 builder.addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004660 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004661}
4662
John Kessenich7a53f762016-01-20 11:19:27 -07004663// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004664spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07004665{
4666 // Handle unary operations vector by vector.
4667 // The result type is the same type as the original type.
4668 // The algorithm is to:
4669 // - break the matrix into vectors
4670 // - apply the operation to each vector
4671 // - make a matrix out the vector results
4672
4673 // get the types sorted out
4674 int numCols = builder.getNumColumns(operand);
4675 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004676 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4677 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004678 std::vector<spv::Id> results;
4679
4680 // do each vector op
4681 for (int c = 0; c < numCols; ++c) {
4682 std::vector<unsigned int> indexes;
4683 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004684 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4685 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenich5d610ee2018-03-07 18:05:55 -07004686 builder.addDecoration(destVec, noContraction);
Rex Xuc1992e52016-05-17 18:57:18 +08004687 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004688 }
4689
4690 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004691 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004692}
4693
John Kessenich66011cb2018-03-06 16:12:04 -07004694spv::Id TGlslangToSpvTraverser::createConversionOperation(glslang::TOperator op, spv::Id operand, int vectorSize)
4695{
4696 spv::Op convOp = spv::OpNop;
4697 spv::Id type = 0;
4698
4699 spv::Id result = 0;
4700
4701 switch(op) {
4702 case glslang::EOpConvInt8ToUint16:
4703 convOp = spv::OpSConvert;
4704 type = builder.makeIntType(16);
4705 break;
4706 case glslang::EOpConvInt8ToUint:
4707 convOp = spv::OpSConvert;
4708 type = builder.makeIntType(32);
4709 break;
4710 case glslang::EOpConvInt8ToUint64:
4711 convOp = spv::OpSConvert;
4712 type = builder.makeIntType(64);
4713 break;
4714 case glslang::EOpConvInt16ToUint8:
4715 convOp = spv::OpSConvert;
4716 type = builder.makeIntType(8);
4717 break;
4718 case glslang::EOpConvInt16ToUint:
4719 convOp = spv::OpSConvert;
4720 type = builder.makeIntType(32);
4721 break;
4722 case glslang::EOpConvInt16ToUint64:
4723 convOp = spv::OpSConvert;
4724 type = builder.makeIntType(64);
4725 break;
4726 case glslang::EOpConvIntToUint8:
4727 convOp = spv::OpSConvert;
4728 type = builder.makeIntType(8);
4729 break;
4730 case glslang::EOpConvIntToUint16:
4731 convOp = spv::OpSConvert;
4732 type = builder.makeIntType(16);
4733 break;
4734 case glslang::EOpConvIntToUint64:
4735 convOp = spv::OpSConvert;
4736 type = builder.makeIntType(64);
4737 break;
4738 case glslang::EOpConvInt64ToUint8:
4739 convOp = spv::OpSConvert;
4740 type = builder.makeIntType(8);
4741 break;
4742 case glslang::EOpConvInt64ToUint16:
4743 convOp = spv::OpSConvert;
4744 type = builder.makeIntType(16);
4745 break;
4746 case glslang::EOpConvInt64ToUint:
4747 convOp = spv::OpSConvert;
4748 type = builder.makeIntType(32);
4749 break;
4750 case glslang::EOpConvUint8ToInt16:
4751 convOp = spv::OpUConvert;
4752 type = builder.makeIntType(16);
4753 break;
4754 case glslang::EOpConvUint8ToInt:
4755 convOp = spv::OpUConvert;
4756 type = builder.makeIntType(32);
4757 break;
4758 case glslang::EOpConvUint8ToInt64:
4759 convOp = spv::OpUConvert;
4760 type = builder.makeIntType(64);
4761 break;
4762 case glslang::EOpConvUint16ToInt8:
4763 convOp = spv::OpUConvert;
4764 type = builder.makeIntType(8);
4765 break;
4766 case glslang::EOpConvUint16ToInt:
4767 convOp = spv::OpUConvert;
4768 type = builder.makeIntType(32);
4769 break;
4770 case glslang::EOpConvUint16ToInt64:
4771 convOp = spv::OpUConvert;
4772 type = builder.makeIntType(64);
4773 break;
4774 case glslang::EOpConvUintToInt8:
4775 convOp = spv::OpUConvert;
4776 type = builder.makeIntType(8);
4777 break;
4778 case glslang::EOpConvUintToInt16:
4779 convOp = spv::OpUConvert;
4780 type = builder.makeIntType(16);
4781 break;
4782 case glslang::EOpConvUintToInt64:
4783 convOp = spv::OpUConvert;
4784 type = builder.makeIntType(64);
4785 break;
4786 case glslang::EOpConvUint64ToInt8:
4787 convOp = spv::OpUConvert;
4788 type = builder.makeIntType(8);
4789 break;
4790 case glslang::EOpConvUint64ToInt16:
4791 convOp = spv::OpUConvert;
4792 type = builder.makeIntType(16);
4793 break;
4794 case glslang::EOpConvUint64ToInt:
4795 convOp = spv::OpUConvert;
4796 type = builder.makeIntType(32);
4797 break;
4798
4799 default:
4800 assert(false && "Default missing");
4801 break;
4802 }
4803
4804 if (vectorSize > 0)
4805 type = builder.makeVectorType(type, vectorSize);
4806
4807 result = builder.createUnaryOp(convOp, type, operand);
4808 return result;
4809}
4810
Rex Xu73e3ce72016-04-27 18:48:17 +08004811spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destType, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004812{
4813 spv::Op convOp = spv::OpNop;
4814 spv::Id zero = 0;
4815 spv::Id one = 0;
4816
4817 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4818
4819 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07004820 case glslang::EOpConvInt8ToBool:
4821 case glslang::EOpConvUint8ToBool:
4822 zero = builder.makeUint8Constant(0);
4823 zero = makeSmearedConstant(zero, vectorSize);
4824 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08004825 case glslang::EOpConvInt16ToBool:
4826 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07004827 zero = builder.makeUint16Constant(0);
4828 zero = makeSmearedConstant(zero, vectorSize);
4829 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4830 case glslang::EOpConvIntToBool:
4831 case glslang::EOpConvUintToBool:
4832 zero = builder.makeUintConstant(0);
4833 zero = makeSmearedConstant(zero, vectorSize);
4834 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4835 case glslang::EOpConvInt64ToBool:
4836 case glslang::EOpConvUint64ToBool:
4837 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004838 zero = makeSmearedConstant(zero, vectorSize);
4839 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4840
4841 case glslang::EOpConvFloatToBool:
4842 zero = builder.makeFloatConstant(0.0F);
4843 zero = makeSmearedConstant(zero, vectorSize);
4844 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4845
4846 case glslang::EOpConvDoubleToBool:
4847 zero = builder.makeDoubleConstant(0.0);
4848 zero = makeSmearedConstant(zero, vectorSize);
4849 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4850
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004851 case glslang::EOpConvFloat16ToBool:
4852 zero = builder.makeFloat16Constant(0.0F);
4853 zero = makeSmearedConstant(zero, vectorSize);
4854 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004855
John Kessenich140f3df2015-06-26 16:58:36 -06004856 case glslang::EOpConvBoolToFloat:
4857 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004858 zero = builder.makeFloatConstant(0.0F);
4859 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004860 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004861
John Kessenich140f3df2015-06-26 16:58:36 -06004862 case glslang::EOpConvBoolToDouble:
4863 convOp = spv::OpSelect;
4864 zero = builder.makeDoubleConstant(0.0);
4865 one = builder.makeDoubleConstant(1.0);
4866 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004867
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004868 case glslang::EOpConvBoolToFloat16:
4869 convOp = spv::OpSelect;
4870 zero = builder.makeFloat16Constant(0.0F);
4871 one = builder.makeFloat16Constant(1.0F);
4872 break;
John Kessenich66011cb2018-03-06 16:12:04 -07004873
4874 case glslang::EOpConvBoolToInt8:
4875 zero = builder.makeInt8Constant(0);
4876 one = builder.makeInt8Constant(1);
4877 convOp = spv::OpSelect;
4878 break;
4879
4880 case glslang::EOpConvBoolToUint8:
4881 zero = builder.makeUint8Constant(0);
4882 one = builder.makeUint8Constant(1);
4883 convOp = spv::OpSelect;
4884 break;
4885
4886 case glslang::EOpConvBoolToInt16:
4887 zero = builder.makeInt16Constant(0);
4888 one = builder.makeInt16Constant(1);
4889 convOp = spv::OpSelect;
4890 break;
4891
4892 case glslang::EOpConvBoolToUint16:
4893 zero = builder.makeUint16Constant(0);
4894 one = builder.makeUint16Constant(1);
4895 convOp = spv::OpSelect;
4896 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004897
John Kessenich140f3df2015-06-26 16:58:36 -06004898 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004899 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004900 if (op == glslang::EOpConvBoolToInt64)
4901 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08004902 else
4903 zero = builder.makeIntConstant(0);
4904
4905 if (op == glslang::EOpConvBoolToInt64)
4906 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08004907 else
4908 one = builder.makeIntConstant(1);
4909
John Kessenich140f3df2015-06-26 16:58:36 -06004910 convOp = spv::OpSelect;
4911 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004912
John Kessenich140f3df2015-06-26 16:58:36 -06004913 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004914 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004915 if (op == glslang::EOpConvBoolToUint64)
4916 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08004917 else
4918 zero = builder.makeUintConstant(0);
4919
4920 if (op == glslang::EOpConvBoolToUint64)
4921 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08004922 else
4923 one = builder.makeUintConstant(1);
4924
John Kessenich140f3df2015-06-26 16:58:36 -06004925 convOp = spv::OpSelect;
4926 break;
4927
John Kessenich66011cb2018-03-06 16:12:04 -07004928 case glslang::EOpConvInt8ToFloat16:
4929 case glslang::EOpConvInt8ToFloat:
4930 case glslang::EOpConvInt8ToDouble:
4931 case glslang::EOpConvInt16ToFloat16:
4932 case glslang::EOpConvInt16ToFloat:
4933 case glslang::EOpConvInt16ToDouble:
4934 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06004935 case glslang::EOpConvIntToFloat:
4936 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004937 case glslang::EOpConvInt64ToFloat:
4938 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004939 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06004940 convOp = spv::OpConvertSToF;
4941 break;
4942
John Kessenich66011cb2018-03-06 16:12:04 -07004943 case glslang::EOpConvUint8ToFloat16:
4944 case glslang::EOpConvUint8ToFloat:
4945 case glslang::EOpConvUint8ToDouble:
4946 case glslang::EOpConvUint16ToFloat16:
4947 case glslang::EOpConvUint16ToFloat:
4948 case glslang::EOpConvUint16ToDouble:
4949 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06004950 case glslang::EOpConvUintToFloat:
4951 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004952 case glslang::EOpConvUint64ToFloat:
4953 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004954 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06004955 convOp = spv::OpConvertUToF;
4956 break;
4957
4958 case glslang::EOpConvDoubleToFloat:
4959 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004960 case glslang::EOpConvDoubleToFloat16:
4961 case glslang::EOpConvFloat16ToDouble:
4962 case glslang::EOpConvFloatToFloat16:
4963 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06004964 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004965 if (builder.isMatrixType(destType))
4966 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004967 break;
4968
John Kessenich66011cb2018-03-06 16:12:04 -07004969 case glslang::EOpConvFloat16ToInt8:
4970 case glslang::EOpConvFloatToInt8:
4971 case glslang::EOpConvDoubleToInt8:
4972 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08004973 case glslang::EOpConvFloatToInt16:
4974 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004975 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07004976 case glslang::EOpConvFloatToInt:
4977 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004978 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07004979 case glslang::EOpConvFloatToInt64:
4980 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06004981 convOp = spv::OpConvertFToS;
4982 break;
4983
John Kessenich66011cb2018-03-06 16:12:04 -07004984 case glslang::EOpConvUint8ToInt8:
4985 case glslang::EOpConvInt8ToUint8:
4986 case glslang::EOpConvUint16ToInt16:
4987 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06004988 case glslang::EOpConvUintToInt:
4989 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004990 case glslang::EOpConvUint64ToInt64:
4991 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04004992 if (builder.isInSpecConstCodeGenMode()) {
4993 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07004994 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
4995 zero = builder.makeUint8Constant(0);
4996 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08004997 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07004998 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
4999 zero = builder.makeUint64Constant(0);
5000 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005001 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005002 }
qining189b2032016-04-12 23:16:20 -04005003 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005004 // Use OpIAdd, instead of OpBitcast to do the conversion when
5005 // generating for OpSpecConstantOp instruction.
5006 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5007 }
5008 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005009 convOp = spv::OpBitcast;
5010 break;
5011
John Kessenich66011cb2018-03-06 16:12:04 -07005012 case glslang::EOpConvFloat16ToUint8:
5013 case glslang::EOpConvFloatToUint8:
5014 case glslang::EOpConvDoubleToUint8:
5015 case glslang::EOpConvFloat16ToUint16:
5016 case glslang::EOpConvFloatToUint16:
5017 case glslang::EOpConvDoubleToUint16:
5018 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005019 case glslang::EOpConvFloatToUint:
5020 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005021 case glslang::EOpConvFloatToUint64:
5022 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005023 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005024 convOp = spv::OpConvertFToU;
5025 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005026
John Kessenich66011cb2018-03-06 16:12:04 -07005027 case glslang::EOpConvInt8ToInt16:
5028 case glslang::EOpConvInt8ToInt:
5029 case glslang::EOpConvInt8ToInt64:
5030 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005031 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005032 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005033 case glslang::EOpConvIntToInt8:
5034 case glslang::EOpConvIntToInt16:
5035 case glslang::EOpConvIntToInt64:
5036 case glslang::EOpConvInt64ToInt8:
5037 case glslang::EOpConvInt64ToInt16:
5038 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005039 convOp = spv::OpSConvert;
5040 break;
5041
John Kessenich66011cb2018-03-06 16:12:04 -07005042 case glslang::EOpConvUint8ToUint16:
5043 case glslang::EOpConvUint8ToUint:
5044 case glslang::EOpConvUint8ToUint64:
5045 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005046 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005047 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005048 case glslang::EOpConvUintToUint8:
5049 case glslang::EOpConvUintToUint16:
5050 case glslang::EOpConvUintToUint64:
5051 case glslang::EOpConvUint64ToUint8:
5052 case glslang::EOpConvUint64ToUint16:
5053 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005054 convOp = spv::OpUConvert;
5055 break;
5056
John Kessenich66011cb2018-03-06 16:12:04 -07005057 case glslang::EOpConvInt8ToUint16:
5058 case glslang::EOpConvInt8ToUint:
5059 case glslang::EOpConvInt8ToUint64:
5060 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005061 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005062 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005063 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005064 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005065 case glslang::EOpConvIntToUint64:
5066 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005067 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005068 case glslang::EOpConvInt64ToUint:
5069 case glslang::EOpConvUint8ToInt16:
5070 case glslang::EOpConvUint8ToInt:
5071 case glslang::EOpConvUint8ToInt64:
5072 case glslang::EOpConvUint16ToInt8:
5073 case glslang::EOpConvUint16ToInt:
5074 case glslang::EOpConvUint16ToInt64:
5075 case glslang::EOpConvUintToInt8:
5076 case glslang::EOpConvUintToInt16:
5077 case glslang::EOpConvUintToInt64:
5078 case glslang::EOpConvUint64ToInt8:
5079 case glslang::EOpConvUint64ToInt16:
5080 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005081 // OpSConvert/OpUConvert + OpBitCast
John Kessenich66011cb2018-03-06 16:12:04 -07005082 operand = createConversionOperation(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005083
5084 if (builder.isInSpecConstCodeGenMode()) {
5085 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005086 switch(op) {
5087 case glslang::EOpConvInt16ToUint8:
5088 case glslang::EOpConvIntToUint8:
5089 case glslang::EOpConvInt64ToUint8:
5090 case glslang::EOpConvUint16ToInt8:
5091 case glslang::EOpConvUintToInt8:
5092 case glslang::EOpConvUint64ToInt8:
5093 zero = builder.makeUint8Constant(0);
5094 break;
5095 case glslang::EOpConvInt8ToUint16:
5096 case glslang::EOpConvIntToUint16:
5097 case glslang::EOpConvInt64ToUint16:
5098 case glslang::EOpConvUint8ToInt16:
5099 case glslang::EOpConvUintToInt16:
5100 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005101 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005102 break;
5103 case glslang::EOpConvInt8ToUint:
5104 case glslang::EOpConvInt16ToUint:
5105 case glslang::EOpConvInt64ToUint:
5106 case glslang::EOpConvUint8ToInt:
5107 case glslang::EOpConvUint16ToInt:
5108 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005109 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005110 break;
5111 case glslang::EOpConvInt8ToUint64:
5112 case glslang::EOpConvInt16ToUint64:
5113 case glslang::EOpConvIntToUint64:
5114 case glslang::EOpConvUint8ToInt64:
5115 case glslang::EOpConvUint16ToInt64:
5116 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005117 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005118 break;
5119 default:
5120 assert(false && "Default missing");
5121 break;
5122 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005123 zero = makeSmearedConstant(zero, vectorSize);
5124 // Use OpIAdd, instead of OpBitcast to do the conversion when
5125 // generating for OpSpecConstantOp instruction.
5126 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5127 }
5128 // For normal run-time conversion instruction, use OpBitcast.
5129 convOp = spv::OpBitcast;
5130 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005131 default:
5132 break;
5133 }
5134
5135 spv::Id result = 0;
5136 if (convOp == spv::OpNop)
5137 return result;
5138
5139 if (convOp == spv::OpSelect) {
5140 zero = makeSmearedConstant(zero, vectorSize);
5141 one = makeSmearedConstant(one, vectorSize);
5142 result = builder.createTriOp(convOp, destType, operand, one, zero);
5143 } else
5144 result = builder.createUnaryOp(convOp, destType, operand);
5145
John Kessenich32cfd492016-02-02 12:37:46 -07005146 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005147}
5148
5149spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
5150{
5151 if (vectorSize == 0)
5152 return constant;
5153
5154 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
5155 std::vector<spv::Id> components;
5156 for (int c = 0; c < vectorSize; ++c)
5157 components.push_back(constant);
5158 return builder.makeCompositeConstant(vectorTypeId, components);
5159}
5160
John Kessenich426394d2015-07-23 10:22:48 -06005161// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07005162spv::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 -06005163{
5164 spv::Op opCode = spv::OpNop;
5165
5166 switch (op) {
5167 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08005168 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005169 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06005170 opCode = spv::OpAtomicIAdd;
5171 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06005172 case glslang::EOpAtomicCounterSubtract:
5173 opCode = spv::OpAtomicISub;
5174 break;
John Kessenich426394d2015-07-23 10:22:48 -06005175 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08005176 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005177 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08005178 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06005179 break;
5180 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08005181 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005182 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08005183 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06005184 break;
5185 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08005186 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005187 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06005188 opCode = spv::OpAtomicAnd;
5189 break;
5190 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08005191 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005192 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06005193 opCode = spv::OpAtomicOr;
5194 break;
5195 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08005196 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005197 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06005198 opCode = spv::OpAtomicXor;
5199 break;
5200 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08005201 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005202 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06005203 opCode = spv::OpAtomicExchange;
5204 break;
5205 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08005206 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005207 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06005208 opCode = spv::OpAtomicCompareExchange;
5209 break;
5210 case glslang::EOpAtomicCounterIncrement:
5211 opCode = spv::OpAtomicIIncrement;
5212 break;
5213 case glslang::EOpAtomicCounterDecrement:
5214 opCode = spv::OpAtomicIDecrement;
5215 break;
5216 case glslang::EOpAtomicCounter:
5217 opCode = spv::OpAtomicLoad;
5218 break;
5219 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005220 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06005221 break;
5222 }
5223
Rex Xue8fe8b02017-09-26 15:42:56 +08005224 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
5225 builder.addCapability(spv::CapabilityInt64Atomics);
5226
John Kessenich426394d2015-07-23 10:22:48 -06005227 // Sort out the operands
5228 // - mapping from glslang -> SPV
5229 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06005230 // - compare-exchange swaps the value and comparator
5231 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06005232 // - EOpAtomicCounterDecrement needs a post decrement
John Kessenich426394d2015-07-23 10:22:48 -06005233 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
5234 auto opIt = operands.begin(); // walk the glslang operands
5235 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08005236 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
5237 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
5238 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08005239 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
5240 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08005241 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06005242 spvAtomicOperands.push_back(*(opIt + 1));
5243 spvAtomicOperands.push_back(*opIt);
5244 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08005245 }
John Kessenich426394d2015-07-23 10:22:48 -06005246
John Kessenich3e60a6f2015-09-14 22:45:16 -06005247 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06005248 for (; opIt != operands.end(); ++opIt)
5249 spvAtomicOperands.push_back(*opIt);
5250
John Kessenich48d6e792017-10-06 21:21:48 -06005251 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
5252
5253 // GLSL and HLSL atomic-counter decrement return post-decrement value,
5254 // while SPIR-V returns pre-decrement value. Translate between these semantics.
5255 if (op == glslang::EOpAtomicCounterDecrement)
5256 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
5257
5258 return resultId;
John Kessenich426394d2015-07-23 10:22:48 -06005259}
5260
John Kessenich91cef522016-05-05 16:45:40 -06005261// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08005262spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06005263{
John Kessenich66011cb2018-03-06 16:12:04 -07005264 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5265 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08005266
Rex Xu51596642016-09-21 18:56:12 +08005267 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08005268 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08005269 spv::GroupOperation groupOperation = spv::GroupOperationMax;
5270
chaocf200da82016-12-20 12:44:35 -08005271 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
5272 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08005273 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
5274 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005275 } else if (op == glslang::EOpAnyInvocation ||
5276 op == glslang::EOpAllInvocations ||
5277 op == glslang::EOpAllInvocationsEqual) {
5278 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
5279 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08005280 } else {
5281 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04005282#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08005283 if (op == glslang::EOpMinInvocationsNonUniform ||
5284 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08005285 op == glslang::EOpAddInvocationsNonUniform ||
5286 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5287 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5288 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
5289 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
5290 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
5291 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08005292 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04005293#endif
Rex Xu51596642016-09-21 18:56:12 +08005294
5295 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08005296#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08005297 switch (op) {
5298 case glslang::EOpMinInvocations:
5299 case glslang::EOpMaxInvocations:
5300 case glslang::EOpAddInvocations:
5301 case glslang::EOpMinInvocationsNonUniform:
5302 case glslang::EOpMaxInvocationsNonUniform:
5303 case glslang::EOpAddInvocationsNonUniform:
5304 groupOperation = spv::GroupOperationReduce;
5305 spvGroupOperands.push_back(groupOperation);
5306 break;
5307 case glslang::EOpMinInvocationsInclusiveScan:
5308 case glslang::EOpMaxInvocationsInclusiveScan:
5309 case glslang::EOpAddInvocationsInclusiveScan:
5310 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5311 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5312 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5313 groupOperation = spv::GroupOperationInclusiveScan;
5314 spvGroupOperands.push_back(groupOperation);
5315 break;
5316 case glslang::EOpMinInvocationsExclusiveScan:
5317 case glslang::EOpMaxInvocationsExclusiveScan:
5318 case glslang::EOpAddInvocationsExclusiveScan:
5319 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5320 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5321 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5322 groupOperation = spv::GroupOperationExclusiveScan;
5323 spvGroupOperands.push_back(groupOperation);
5324 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07005325 default:
5326 break;
Rex Xu430ef402016-10-14 17:22:23 +08005327 }
Rex Xu9d93a232016-05-05 12:30:44 +08005328#endif
Rex Xu51596642016-09-21 18:56:12 +08005329 }
5330
5331 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
5332 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06005333
5334 switch (op) {
5335 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005336 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08005337 break;
John Kessenich91cef522016-05-05 16:45:40 -06005338 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005339 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08005340 break;
John Kessenich91cef522016-05-05 16:45:40 -06005341 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005342 opCode = spv::OpSubgroupAllEqualKHR;
5343 break;
Rex Xu51596642016-09-21 18:56:12 +08005344 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08005345 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08005346 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005347 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005348 break;
5349 case glslang::EOpReadFirstInvocation:
5350 opCode = spv::OpSubgroupFirstInvocationKHR;
5351 break;
5352 case glslang::EOpBallot:
5353 {
5354 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
5355 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
5356 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
5357 //
5358 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
5359 //
5360 spv::Id uintType = builder.makeUintType(32);
5361 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
5362 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
5363
5364 std::vector<spv::Id> components;
5365 components.push_back(builder.createCompositeExtract(result, uintType, 0));
5366 components.push_back(builder.createCompositeExtract(result, uintType, 1));
5367
5368 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
5369 return builder.createUnaryOp(spv::OpBitcast, typeId,
5370 builder.createCompositeConstruct(uvec2Type, components));
5371 }
5372
Rex Xu9d93a232016-05-05 12:30:44 +08005373#ifdef AMD_EXTENSIONS
5374 case glslang::EOpMinInvocations:
5375 case glslang::EOpMaxInvocations:
5376 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08005377 case glslang::EOpMinInvocationsInclusiveScan:
5378 case glslang::EOpMaxInvocationsInclusiveScan:
5379 case glslang::EOpAddInvocationsInclusiveScan:
5380 case glslang::EOpMinInvocationsExclusiveScan:
5381 case glslang::EOpMaxInvocationsExclusiveScan:
5382 case glslang::EOpAddInvocationsExclusiveScan:
5383 if (op == glslang::EOpMinInvocations ||
5384 op == glslang::EOpMinInvocationsInclusiveScan ||
5385 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005386 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005387 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005388 else {
5389 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005390 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005391 else
Rex Xu51596642016-09-21 18:56:12 +08005392 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005393 }
Rex Xu430ef402016-10-14 17:22:23 +08005394 } else if (op == glslang::EOpMaxInvocations ||
5395 op == glslang::EOpMaxInvocationsInclusiveScan ||
5396 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005397 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005398 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005399 else {
5400 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005401 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005402 else
Rex Xu51596642016-09-21 18:56:12 +08005403 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005404 }
5405 } else {
5406 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005407 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005408 else
Rex Xu51596642016-09-21 18:56:12 +08005409 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005410 }
5411
Rex Xu2bbbe062016-08-23 15:41:05 +08005412 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005413 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005414
5415 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005416 case glslang::EOpMinInvocationsNonUniform:
5417 case glslang::EOpMaxInvocationsNonUniform:
5418 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005419 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5420 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5421 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5422 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5423 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5424 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5425 if (op == glslang::EOpMinInvocationsNonUniform ||
5426 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5427 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005428 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005429 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005430 else {
5431 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005432 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005433 else
Rex Xu51596642016-09-21 18:56:12 +08005434 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005435 }
5436 }
Rex Xu430ef402016-10-14 17:22:23 +08005437 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5438 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5439 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005440 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005441 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005442 else {
5443 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005444 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005445 else
Rex Xu51596642016-09-21 18:56:12 +08005446 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005447 }
5448 }
5449 else {
5450 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005451 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005452 else
Rex Xu51596642016-09-21 18:56:12 +08005453 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005454 }
5455
Rex Xu2bbbe062016-08-23 15:41:05 +08005456 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005457 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005458
5459 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005460#endif
John Kessenich91cef522016-05-05 16:45:40 -06005461 default:
5462 logger->missingFunctionality("invocation operation");
5463 return spv::NoResult;
5464 }
Rex Xu51596642016-09-21 18:56:12 +08005465
5466 assert(opCode != spv::OpNop);
5467 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005468}
5469
Rex Xu2bbbe062016-08-23 15:41:05 +08005470// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005471spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005472{
Rex Xub7072052016-09-26 15:53:40 +08005473#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005474 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5475 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005476 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005477 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005478 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5479 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5480 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005481#else
5482 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5483 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005484 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5485 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005486#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005487
5488 // Handle group invocation operations scalar by scalar.
5489 // The result type is the same type as the original type.
5490 // The algorithm is to:
5491 // - break the vector into scalars
5492 // - apply the operation to each scalar
5493 // - make a vector out the scalar results
5494
5495 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005496 int numComponents = builder.getNumComponents(operands[0]);
5497 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005498 std::vector<spv::Id> results;
5499
5500 // do each scalar op
5501 for (int comp = 0; comp < numComponents; ++comp) {
5502 std::vector<unsigned int> indexes;
5503 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005504 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005505 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005506 if (op == spv::OpSubgroupReadInvocationKHR) {
5507 spvGroupOperands.push_back(scalar);
5508 spvGroupOperands.push_back(operands[1]);
5509 } else if (op == spv::OpGroupBroadcast) {
5510 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005511 spvGroupOperands.push_back(scalar);
5512 spvGroupOperands.push_back(operands[1]);
5513 } else {
chaocf200da82016-12-20 12:44:35 -08005514 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005515 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005516 spvGroupOperands.push_back(scalar);
5517 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005518
Rex Xub7072052016-09-26 15:53:40 +08005519 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005520 }
5521
5522 // put the pieces together
5523 return builder.createCompositeConstruct(typeId, results);
5524}
Rex Xu2bbbe062016-08-23 15:41:05 +08005525
John Kessenich66011cb2018-03-06 16:12:04 -07005526// Create subgroup invocation operations.
5527spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
5528{
5529 // Add the required capabilities.
5530 switch (op) {
5531 case glslang::EOpSubgroupElect:
5532 builder.addCapability(spv::CapabilityGroupNonUniform);
5533 break;
5534 case glslang::EOpSubgroupAll:
5535 case glslang::EOpSubgroupAny:
5536 case glslang::EOpSubgroupAllEqual:
5537 builder.addCapability(spv::CapabilityGroupNonUniform);
5538 builder.addCapability(spv::CapabilityGroupNonUniformVote);
5539 break;
5540 case glslang::EOpSubgroupBroadcast:
5541 case glslang::EOpSubgroupBroadcastFirst:
5542 case glslang::EOpSubgroupBallot:
5543 case glslang::EOpSubgroupInverseBallot:
5544 case glslang::EOpSubgroupBallotBitExtract:
5545 case glslang::EOpSubgroupBallotBitCount:
5546 case glslang::EOpSubgroupBallotInclusiveBitCount:
5547 case glslang::EOpSubgroupBallotExclusiveBitCount:
5548 case glslang::EOpSubgroupBallotFindLSB:
5549 case glslang::EOpSubgroupBallotFindMSB:
5550 builder.addCapability(spv::CapabilityGroupNonUniform);
5551 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
5552 break;
5553 case glslang::EOpSubgroupShuffle:
5554 case glslang::EOpSubgroupShuffleXor:
5555 builder.addCapability(spv::CapabilityGroupNonUniform);
5556 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
5557 break;
5558 case glslang::EOpSubgroupShuffleUp:
5559 case glslang::EOpSubgroupShuffleDown:
5560 builder.addCapability(spv::CapabilityGroupNonUniform);
5561 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
5562 break;
5563 case glslang::EOpSubgroupAdd:
5564 case glslang::EOpSubgroupMul:
5565 case glslang::EOpSubgroupMin:
5566 case glslang::EOpSubgroupMax:
5567 case glslang::EOpSubgroupAnd:
5568 case glslang::EOpSubgroupOr:
5569 case glslang::EOpSubgroupXor:
5570 case glslang::EOpSubgroupInclusiveAdd:
5571 case glslang::EOpSubgroupInclusiveMul:
5572 case glslang::EOpSubgroupInclusiveMin:
5573 case glslang::EOpSubgroupInclusiveMax:
5574 case glslang::EOpSubgroupInclusiveAnd:
5575 case glslang::EOpSubgroupInclusiveOr:
5576 case glslang::EOpSubgroupInclusiveXor:
5577 case glslang::EOpSubgroupExclusiveAdd:
5578 case glslang::EOpSubgroupExclusiveMul:
5579 case glslang::EOpSubgroupExclusiveMin:
5580 case glslang::EOpSubgroupExclusiveMax:
5581 case glslang::EOpSubgroupExclusiveAnd:
5582 case glslang::EOpSubgroupExclusiveOr:
5583 case glslang::EOpSubgroupExclusiveXor:
5584 builder.addCapability(spv::CapabilityGroupNonUniform);
5585 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
5586 break;
5587 case glslang::EOpSubgroupClusteredAdd:
5588 case glslang::EOpSubgroupClusteredMul:
5589 case glslang::EOpSubgroupClusteredMin:
5590 case glslang::EOpSubgroupClusteredMax:
5591 case glslang::EOpSubgroupClusteredAnd:
5592 case glslang::EOpSubgroupClusteredOr:
5593 case glslang::EOpSubgroupClusteredXor:
5594 builder.addCapability(spv::CapabilityGroupNonUniform);
5595 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
5596 break;
5597 case glslang::EOpSubgroupQuadBroadcast:
5598 case glslang::EOpSubgroupQuadSwapHorizontal:
5599 case glslang::EOpSubgroupQuadSwapVertical:
5600 case glslang::EOpSubgroupQuadSwapDiagonal:
5601 builder.addCapability(spv::CapabilityGroupNonUniform);
5602 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
5603 break;
5604 default: assert(0 && "Unhandled subgroup operation!");
5605 }
5606
5607 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
5608 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
5609 const bool isBool = typeProxy == glslang::EbtBool;
5610
5611 spv::Op opCode = spv::OpNop;
5612
5613 // Figure out which opcode to use.
5614 switch (op) {
5615 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
5616 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
5617 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
5618 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
5619 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
5620 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
5621 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
5622 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
5623 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
5624 case glslang::EOpSubgroupBallotBitCount:
5625 case glslang::EOpSubgroupBallotInclusiveBitCount:
5626 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
5627 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
5628 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
5629 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
5630 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
5631 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
5632 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
5633 case glslang::EOpSubgroupAdd:
5634 case glslang::EOpSubgroupInclusiveAdd:
5635 case glslang::EOpSubgroupExclusiveAdd:
5636 case glslang::EOpSubgroupClusteredAdd:
5637 if (isFloat) {
5638 opCode = spv::OpGroupNonUniformFAdd;
5639 } else {
5640 opCode = spv::OpGroupNonUniformIAdd;
5641 }
5642 break;
5643 case glslang::EOpSubgroupMul:
5644 case glslang::EOpSubgroupInclusiveMul:
5645 case glslang::EOpSubgroupExclusiveMul:
5646 case glslang::EOpSubgroupClusteredMul:
5647 if (isFloat) {
5648 opCode = spv::OpGroupNonUniformFMul;
5649 } else {
5650 opCode = spv::OpGroupNonUniformIMul;
5651 }
5652 break;
5653 case glslang::EOpSubgroupMin:
5654 case glslang::EOpSubgroupInclusiveMin:
5655 case glslang::EOpSubgroupExclusiveMin:
5656 case glslang::EOpSubgroupClusteredMin:
5657 if (isFloat) {
5658 opCode = spv::OpGroupNonUniformFMin;
5659 } else if (isUnsigned) {
5660 opCode = spv::OpGroupNonUniformUMin;
5661 } else {
5662 opCode = spv::OpGroupNonUniformSMin;
5663 }
5664 break;
5665 case glslang::EOpSubgroupMax:
5666 case glslang::EOpSubgroupInclusiveMax:
5667 case glslang::EOpSubgroupExclusiveMax:
5668 case glslang::EOpSubgroupClusteredMax:
5669 if (isFloat) {
5670 opCode = spv::OpGroupNonUniformFMax;
5671 } else if (isUnsigned) {
5672 opCode = spv::OpGroupNonUniformUMax;
5673 } else {
5674 opCode = spv::OpGroupNonUniformSMax;
5675 }
5676 break;
5677 case glslang::EOpSubgroupAnd:
5678 case glslang::EOpSubgroupInclusiveAnd:
5679 case glslang::EOpSubgroupExclusiveAnd:
5680 case glslang::EOpSubgroupClusteredAnd:
5681 if (isBool) {
5682 opCode = spv::OpGroupNonUniformLogicalAnd;
5683 } else {
5684 opCode = spv::OpGroupNonUniformBitwiseAnd;
5685 }
5686 break;
5687 case glslang::EOpSubgroupOr:
5688 case glslang::EOpSubgroupInclusiveOr:
5689 case glslang::EOpSubgroupExclusiveOr:
5690 case glslang::EOpSubgroupClusteredOr:
5691 if (isBool) {
5692 opCode = spv::OpGroupNonUniformLogicalOr;
5693 } else {
5694 opCode = spv::OpGroupNonUniformBitwiseOr;
5695 }
5696 break;
5697 case glslang::EOpSubgroupXor:
5698 case glslang::EOpSubgroupInclusiveXor:
5699 case glslang::EOpSubgroupExclusiveXor:
5700 case glslang::EOpSubgroupClusteredXor:
5701 if (isBool) {
5702 opCode = spv::OpGroupNonUniformLogicalXor;
5703 } else {
5704 opCode = spv::OpGroupNonUniformBitwiseXor;
5705 }
5706 break;
5707 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
5708 case glslang::EOpSubgroupQuadSwapHorizontal:
5709 case glslang::EOpSubgroupQuadSwapVertical:
5710 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
5711 default: assert(0 && "Unhandled subgroup operation!");
5712 }
5713
5714 std::vector<spv::Id> spvGroupOperands;
5715
5716 // Every operation begins with the Execution Scope operand.
5717 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
5718
5719 // Next, for all operations that use a Group Operation, push that as an operand.
5720 switch (op) {
5721 default: break;
5722 case glslang::EOpSubgroupBallotBitCount:
5723 case glslang::EOpSubgroupAdd:
5724 case glslang::EOpSubgroupMul:
5725 case glslang::EOpSubgroupMin:
5726 case glslang::EOpSubgroupMax:
5727 case glslang::EOpSubgroupAnd:
5728 case glslang::EOpSubgroupOr:
5729 case glslang::EOpSubgroupXor:
5730 spvGroupOperands.push_back(spv::GroupOperationReduce);
5731 break;
5732 case glslang::EOpSubgroupBallotInclusiveBitCount:
5733 case glslang::EOpSubgroupInclusiveAdd:
5734 case glslang::EOpSubgroupInclusiveMul:
5735 case glslang::EOpSubgroupInclusiveMin:
5736 case glslang::EOpSubgroupInclusiveMax:
5737 case glslang::EOpSubgroupInclusiveAnd:
5738 case glslang::EOpSubgroupInclusiveOr:
5739 case glslang::EOpSubgroupInclusiveXor:
5740 spvGroupOperands.push_back(spv::GroupOperationInclusiveScan);
5741 break;
5742 case glslang::EOpSubgroupBallotExclusiveBitCount:
5743 case glslang::EOpSubgroupExclusiveAdd:
5744 case glslang::EOpSubgroupExclusiveMul:
5745 case glslang::EOpSubgroupExclusiveMin:
5746 case glslang::EOpSubgroupExclusiveMax:
5747 case glslang::EOpSubgroupExclusiveAnd:
5748 case glslang::EOpSubgroupExclusiveOr:
5749 case glslang::EOpSubgroupExclusiveXor:
5750 spvGroupOperands.push_back(spv::GroupOperationExclusiveScan);
5751 break;
5752 case glslang::EOpSubgroupClusteredAdd:
5753 case glslang::EOpSubgroupClusteredMul:
5754 case glslang::EOpSubgroupClusteredMin:
5755 case glslang::EOpSubgroupClusteredMax:
5756 case glslang::EOpSubgroupClusteredAnd:
5757 case glslang::EOpSubgroupClusteredOr:
5758 case glslang::EOpSubgroupClusteredXor:
5759 spvGroupOperands.push_back(spv::GroupOperationClusteredReduce);
5760 break;
5761 }
5762
5763 // Push back the operands next.
5764 for (auto opIt : operands) {
5765 spvGroupOperands.push_back(opIt);
5766 }
5767
5768 // Some opcodes have additional operands.
5769 switch (op) {
5770 default: break;
5771 case glslang::EOpSubgroupQuadSwapHorizontal: spvGroupOperands.push_back(builder.makeUintConstant(0)); break;
5772 case glslang::EOpSubgroupQuadSwapVertical: spvGroupOperands.push_back(builder.makeUintConstant(1)); break;
5773 case glslang::EOpSubgroupQuadSwapDiagonal: spvGroupOperands.push_back(builder.makeUintConstant(2)); break;
5774 }
5775
5776 return builder.createOp(opCode, typeId, spvGroupOperands);
5777}
5778
John Kessenich5e4b1242015-08-06 22:53:06 -06005779spv::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 -06005780{
John Kessenich66011cb2018-03-06 16:12:04 -07005781 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5782 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06005783
John Kessenich140f3df2015-06-26 16:58:36 -06005784 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005785 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005786 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005787 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005788 spv::Id typeId0 = 0;
5789 if (consumedOperands > 0)
5790 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005791 spv::Id typeId1 = 0;
5792 if (consumedOperands > 1)
5793 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005794 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005795
5796 switch (op) {
5797 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005798 if (isFloat)
5799 libCall = spv::GLSLstd450FMin;
5800 else if (isUnsigned)
5801 libCall = spv::GLSLstd450UMin;
5802 else
5803 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005804 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005805 break;
5806 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06005807 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06005808 break;
5809 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06005810 if (isFloat)
5811 libCall = spv::GLSLstd450FMax;
5812 else if (isUnsigned)
5813 libCall = spv::GLSLstd450UMax;
5814 else
5815 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005816 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005817 break;
5818 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005819 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005820 break;
5821 case glslang::EOpDot:
5822 opCode = spv::OpDot;
5823 break;
5824 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005825 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005826 break;
5827
5828 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005829 if (isFloat)
5830 libCall = spv::GLSLstd450FClamp;
5831 else if (isUnsigned)
5832 libCall = spv::GLSLstd450UClamp;
5833 else
5834 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005835 builder.promoteScalar(precision, operands.front(), operands[1]);
5836 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005837 break;
5838 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005839 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5840 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005841 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005842 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005843 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005844 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005845 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005846 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005847 break;
5848 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005849 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005850 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005851 break;
5852 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005853 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005854 builder.promoteScalar(precision, operands[0], operands[2]);
5855 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005856 break;
5857
5858 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005859 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005860 break;
5861 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005862 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005863 break;
5864 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005865 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005866 break;
5867 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005868 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005869 break;
5870 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005871 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005872 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005873 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005874 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005875 libCall = spv::GLSLstd450InterpolateAtSample;
5876 break;
5877 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005878 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005879 libCall = spv::GLSLstd450InterpolateAtOffset;
5880 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005881 case glslang::EOpAddCarry:
5882 opCode = spv::OpIAddCarry;
5883 typeId = builder.makeStructResultType(typeId0, typeId0);
5884 consumedOperands = 2;
5885 break;
5886 case glslang::EOpSubBorrow:
5887 opCode = spv::OpISubBorrow;
5888 typeId = builder.makeStructResultType(typeId0, typeId0);
5889 consumedOperands = 2;
5890 break;
5891 case glslang::EOpUMulExtended:
5892 opCode = spv::OpUMulExtended;
5893 typeId = builder.makeStructResultType(typeId0, typeId0);
5894 consumedOperands = 2;
5895 break;
5896 case glslang::EOpIMulExtended:
5897 opCode = spv::OpSMulExtended;
5898 typeId = builder.makeStructResultType(typeId0, typeId0);
5899 consumedOperands = 2;
5900 break;
5901 case glslang::EOpBitfieldExtract:
5902 if (isUnsigned)
5903 opCode = spv::OpBitFieldUExtract;
5904 else
5905 opCode = spv::OpBitFieldSExtract;
5906 break;
5907 case glslang::EOpBitfieldInsert:
5908 opCode = spv::OpBitFieldInsert;
5909 break;
5910
5911 case glslang::EOpFma:
5912 libCall = spv::GLSLstd450Fma;
5913 break;
5914 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005915 {
5916 libCall = spv::GLSLstd450FrexpStruct;
5917 assert(builder.isPointerType(typeId1));
5918 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08005919 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08005920 if (builder.getNumComponents(operands[0]) == 1)
5921 frexpIntType = builder.makeIntegerType(width, true);
5922 else
5923 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5924 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5925 consumedOperands = 1;
5926 }
John Kessenich55e7d112015-11-15 21:33:39 -07005927 break;
5928 case glslang::EOpLdexp:
5929 libCall = spv::GLSLstd450Ldexp;
5930 break;
5931
Rex Xu574ab042016-04-14 16:53:07 +08005932 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005933 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005934
John Kessenich66011cb2018-03-06 16:12:04 -07005935 case glslang::EOpSubgroupBroadcast:
5936 case glslang::EOpSubgroupBallotBitExtract:
5937 case glslang::EOpSubgroupShuffle:
5938 case glslang::EOpSubgroupShuffleXor:
5939 case glslang::EOpSubgroupShuffleUp:
5940 case glslang::EOpSubgroupShuffleDown:
5941 case glslang::EOpSubgroupClusteredAdd:
5942 case glslang::EOpSubgroupClusteredMul:
5943 case glslang::EOpSubgroupClusteredMin:
5944 case glslang::EOpSubgroupClusteredMax:
5945 case glslang::EOpSubgroupClusteredAnd:
5946 case glslang::EOpSubgroupClusteredOr:
5947 case glslang::EOpSubgroupClusteredXor:
5948 case glslang::EOpSubgroupQuadBroadcast:
5949 return createSubgroupOperation(op, typeId, operands, typeProxy);
5950
Rex Xu9d93a232016-05-05 12:30:44 +08005951#ifdef AMD_EXTENSIONS
5952 case glslang::EOpSwizzleInvocations:
5953 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5954 libCall = spv::SwizzleInvocationsAMD;
5955 break;
5956 case glslang::EOpSwizzleInvocationsMasked:
5957 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5958 libCall = spv::SwizzleInvocationsMaskedAMD;
5959 break;
5960 case glslang::EOpWriteInvocation:
5961 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5962 libCall = spv::WriteInvocationAMD;
5963 break;
5964
5965 case glslang::EOpMin3:
5966 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5967 if (isFloat)
5968 libCall = spv::FMin3AMD;
5969 else {
5970 if (isUnsigned)
5971 libCall = spv::UMin3AMD;
5972 else
5973 libCall = spv::SMin3AMD;
5974 }
5975 break;
5976 case glslang::EOpMax3:
5977 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5978 if (isFloat)
5979 libCall = spv::FMax3AMD;
5980 else {
5981 if (isUnsigned)
5982 libCall = spv::UMax3AMD;
5983 else
5984 libCall = spv::SMax3AMD;
5985 }
5986 break;
5987 case glslang::EOpMid3:
5988 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5989 if (isFloat)
5990 libCall = spv::FMid3AMD;
5991 else {
5992 if (isUnsigned)
5993 libCall = spv::UMid3AMD;
5994 else
5995 libCall = spv::SMid3AMD;
5996 }
5997 break;
5998
5999 case glslang::EOpInterpolateAtVertex:
6000 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
6001 libCall = spv::InterpolateAtVertexAMD;
6002 break;
6003#endif
6004
John Kessenich140f3df2015-06-26 16:58:36 -06006005 default:
6006 return 0;
6007 }
6008
6009 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07006010 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05006011 // Use an extended instruction from the standard library.
6012 // Construct the call arguments, without modifying the original operands vector.
6013 // We might need the remaining arguments, e.g. in the EOpFrexp case.
6014 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08006015 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07006016 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07006017 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06006018 case 0:
6019 // should all be handled by visitAggregate and createNoArgOperation
6020 assert(0);
6021 return 0;
6022 case 1:
6023 // should all be handled by createUnaryOperation
6024 assert(0);
6025 return 0;
6026 case 2:
6027 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
6028 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006029 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006030 // anything 3 or over doesn't have l-value operands, so all should be consumed
6031 assert(consumedOperands == operands.size());
6032 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06006033 break;
6034 }
6035 }
6036
John Kessenich55e7d112015-11-15 21:33:39 -07006037 // Decode the return types that were structures
6038 switch (op) {
6039 case glslang::EOpAddCarry:
6040 case glslang::EOpSubBorrow:
6041 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6042 id = builder.createCompositeExtract(id, typeId0, 0);
6043 break;
6044 case glslang::EOpUMulExtended:
6045 case glslang::EOpIMulExtended:
6046 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
6047 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6048 break;
6049 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006050 {
6051 assert(operands.size() == 2);
6052 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
6053 // "exp" is floating-point type (from HLSL intrinsic)
6054 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
6055 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
6056 builder.createStore(member1, operands[1]);
6057 } else
6058 // "exp" is integer type (from GLSL built-in function)
6059 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
6060 id = builder.createCompositeExtract(id, typeId0, 0);
6061 }
John Kessenich55e7d112015-11-15 21:33:39 -07006062 break;
6063 default:
6064 break;
6065 }
6066
John Kessenich32cfd492016-02-02 12:37:46 -07006067 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006068}
6069
Rex Xu9d93a232016-05-05 12:30:44 +08006070// Intrinsics with no arguments (or no return value, and no precision).
6071spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06006072{
6073 // TODO: get the barrier operands correct
6074
6075 switch (op) {
6076 case glslang::EOpEmitVertex:
6077 builder.createNoResultOp(spv::OpEmitVertex);
6078 return 0;
6079 case glslang::EOpEndPrimitive:
6080 builder.createNoResultOp(spv::OpEndPrimitive);
6081 return 0;
6082 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006083 if (glslangIntermediate->getStage() == EShLangTessControl) {
6084 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
6085 // TODO: prefer the following, when available:
6086 // builder.createControlBarrier(spv::ScopePatch, spv::ScopePatch,
6087 // spv::MemorySemanticsPatchMask |
6088 // spv::MemorySemanticsAcquireReleaseMask);
6089 } else {
6090 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6091 spv::MemorySemanticsWorkgroupMemoryMask |
6092 spv::MemorySemanticsAcquireReleaseMask);
6093 }
John Kessenich140f3df2015-06-26 16:58:36 -06006094 return 0;
6095 case glslang::EOpMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006096 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory |
6097 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006098 return 0;
6099 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich82979362017-12-11 04:02:24 -07006100 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask |
6101 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006102 return 0;
6103 case glslang::EOpMemoryBarrierBuffer:
John Kessenich82979362017-12-11 04:02:24 -07006104 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6105 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006106 return 0;
6107 case glslang::EOpMemoryBarrierImage:
John Kessenich82979362017-12-11 04:02:24 -07006108 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask |
6109 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006110 return 0;
6111 case glslang::EOpMemoryBarrierShared:
John Kessenich82979362017-12-11 04:02:24 -07006112 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask |
6113 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006114 return 0;
6115 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006116 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
6117 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006118 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06006119 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006120 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07006121 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07006122 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006123 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07006124 case glslang::EOpDeviceMemoryBarrier:
6125 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6126 spv::MemorySemanticsImageMemoryMask |
6127 spv::MemorySemanticsAcquireReleaseMask);
6128 return 0;
6129 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
6130 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6131 spv::MemorySemanticsImageMemoryMask |
6132 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006133 return 0;
6134 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07006135 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6136 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006137 return 0;
6138 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006139 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6140 spv::MemorySemanticsWorkgroupMemoryMask |
6141 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006142 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07006143 case glslang::EOpSubgroupBarrier:
6144 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6145 spv::MemorySemanticsAcquireReleaseMask);
6146 return spv::NoResult;
6147 case glslang::EOpSubgroupMemoryBarrier:
6148 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6149 spv::MemorySemanticsAcquireReleaseMask);
6150 return spv::NoResult;
6151 case glslang::EOpSubgroupMemoryBarrierBuffer:
6152 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
6153 spv::MemorySemanticsAcquireReleaseMask);
6154 return spv::NoResult;
6155 case glslang::EOpSubgroupMemoryBarrierImage:
6156 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
6157 spv::MemorySemanticsAcquireReleaseMask);
6158 return spv::NoResult;
6159 case glslang::EOpSubgroupMemoryBarrierShared:
6160 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6161 spv::MemorySemanticsAcquireReleaseMask);
6162 return spv::NoResult;
6163 case glslang::EOpSubgroupElect: {
6164 std::vector<spv::Id> operands;
6165 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
6166 }
Rex Xu9d93a232016-05-05 12:30:44 +08006167#ifdef AMD_EXTENSIONS
6168 case glslang::EOpTime:
6169 {
6170 std::vector<spv::Id> args; // Dummy arguments
6171 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
6172 return builder.setPrecision(id, precision);
6173 }
6174#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006175 default:
Lei Zhang17535f72016-05-04 15:55:59 -04006176 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06006177 return 0;
6178 }
6179}
6180
6181spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
6182{
John Kessenich2f273362015-07-18 22:34:27 -06006183 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06006184 spv::Id id;
6185 if (symbolValues.end() != iter) {
6186 id = iter->second;
6187 return id;
6188 }
6189
6190 // it was not found, create it
6191 id = createSpvVariable(symbol);
6192 symbolValues[symbol->getId()] = id;
6193
Rex Xuc884b4a2016-06-29 15:03:44 +08006194 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006195 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
6196 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
6197 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07006198 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07006199 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06006200 if (symbol->getQualifier().hasIndex())
6201 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
6202 if (symbol->getQualifier().hasComponent())
6203 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06006204 // atomic counters use this:
6205 if (symbol->getQualifier().hasOffset())
6206 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006207 }
6208
scygan2c864272016-05-18 18:09:17 +02006209 if (symbol->getQualifier().hasLocation())
6210 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07006211 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07006212 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07006213 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06006214 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07006215 }
John Kessenich140f3df2015-06-26 16:58:36 -06006216 if (symbol->getQualifier().hasSet())
6217 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07006218 else if (IsDescriptorResource(symbol->getType())) {
6219 // default to 0
6220 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
6221 }
John Kessenich140f3df2015-06-26 16:58:36 -06006222 if (symbol->getQualifier().hasBinding())
6223 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07006224 if (symbol->getQualifier().hasAttachment())
6225 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06006226 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07006227 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06006228 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06006229 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07006230 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06006231 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07006232 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
6233 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
6234 builder.addDecoration(id, spv::DecorationXfbStride, stride);
6235 }
6236 if (symbol->getQualifier().hasXfbOffset())
6237 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006238 }
6239
Rex Xu1da878f2016-02-21 20:59:01 +08006240 if (symbol->getType().isImage()) {
6241 std::vector<spv::Decoration> memory;
6242 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
6243 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07006244 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08006245 }
6246
John Kessenich140f3df2015-06-26 16:58:36 -06006247 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06006248 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06006249 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07006250 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06006251
John Kessenichecba76f2017-01-06 00:34:48 -07006252#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08006253 if (builtIn == spv::BuiltInSampleMask) {
6254 spv::Decoration decoration;
6255 // GL_NV_sample_mask_override_coverage extension
6256 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08006257 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08006258 else
6259 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07006260 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08006261 if (decoration != spv::DecorationMax) {
6262 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
6263 }
6264 }
chaoc771d89f2017-01-13 01:10:53 -08006265 else if (builtIn == spv::BuiltInLayer) {
6266 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06006267 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006268 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08006269 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
6270 builder.addExtension(spv::E_SPV_NV_viewport_array2);
6271 }
John Kessenichb41bff62017-08-11 13:07:17 -06006272 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006273 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
6274 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08006275 builder.addCapability(spv::CapabilityShaderStereoViewNV);
6276 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
6277 }
6278 }
6279
chaoc6e5acae2016-12-20 13:28:52 -08006280 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006281 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08006282 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08006283 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
6284 }
chaoc0ad6a4e2016-12-19 16:29:34 -08006285#endif
6286
John Kessenich5d610ee2018-03-07 18:05:55 -07006287 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
6288 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
6289 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
6290 symbol->getType().getQualifier().semanticName);
6291 }
6292
John Kessenich140f3df2015-06-26 16:58:36 -06006293 return id;
6294}
6295
John Kessenich55e7d112015-11-15 21:33:39 -07006296// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07006297// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07006298//
6299// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
6300//
6301// Recursively walk the nodes. The nodes form a tree whose leaves are
6302// regular constants, which themselves are trees that createSpvConstant()
6303// recursively walks. So, this function walks the "top" of the tree:
6304// - emit specialization constant-building instructions for specConstant
6305// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04006306spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07006307{
John Kessenich7cc0e282016-03-20 00:46:02 -06006308 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07006309
qining4f4bb812016-04-03 23:55:17 -04006310 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07006311 if (! node.getQualifier().specConstant) {
6312 // hand off to the non-spec-constant path
6313 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
6314 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04006315 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07006316 nextConst, false);
6317 }
6318
6319 // We now know we have a specialization constant to build
6320
John Kessenichd94c0032016-05-30 19:29:40 -06006321 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04006322 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
6323 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
6324 std::vector<spv::Id> dimConstId;
6325 for (int dim = 0; dim < 3; ++dim) {
6326 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
6327 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07006328 if (specConst) {
6329 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
6330 glslangIntermediate->getLocalSizeSpecId(dim));
6331 }
qining4f4bb812016-04-03 23:55:17 -04006332 }
6333 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
6334 }
6335
6336 // An AST node labelled as specialization constant should be a symbol node.
6337 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
6338 if (auto* sn = node.getAsSymbolNode()) {
6339 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04006340 // Traverse the constant constructor sub tree like generating normal run-time instructions.
6341 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
6342 // will set the builder into spec constant op instruction generating mode.
6343 sub_tree->traverse(this);
6344 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04006345 } else if (auto* const_union_array = &sn->getConstArray()){
6346 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01006347 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
6348 builder.addName(id, sn->getName().c_str());
6349 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07006350 }
6351 }
qining4f4bb812016-04-03 23:55:17 -04006352
6353 // Neither a front-end constant node, nor a specialization constant node with constant union array or
6354 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04006355 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04006356 exit(1);
6357 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07006358}
6359
John Kessenich140f3df2015-06-26 16:58:36 -06006360// Use 'consts' as the flattened glslang source of scalar constants to recursively
6361// build the aggregate SPIR-V constant.
6362//
6363// If there are not enough elements present in 'consts', 0 will be substituted;
6364// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
6365//
qining08408382016-03-21 09:51:37 -04006366spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06006367{
6368 // vector of constants for SPIR-V
6369 std::vector<spv::Id> spvConsts;
6370
6371 // Type is used for struct and array constants
6372 spv::Id typeId = convertGlslangToSpvType(glslangType);
6373
6374 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006375 glslang::TType elementType(glslangType, 0);
6376 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04006377 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006378 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006379 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06006380 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04006381 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006382 } else if (glslangType.getStruct()) {
6383 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
6384 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04006385 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06006386 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06006387 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
6388 bool zero = nextConst >= consts.size();
6389 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006390 case glslang::EbtInt8:
6391 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
6392 break;
6393 case glslang::EbtUint8:
6394 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
6395 break;
6396 case glslang::EbtInt16:
6397 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
6398 break;
6399 case glslang::EbtUint16:
6400 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
6401 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006402 case glslang::EbtInt:
6403 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
6404 break;
6405 case glslang::EbtUint:
6406 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
6407 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006408 case glslang::EbtInt64:
6409 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
6410 break;
6411 case glslang::EbtUint64:
6412 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
6413 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006414 case glslang::EbtFloat:
6415 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
6416 break;
6417 case glslang::EbtDouble:
6418 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
6419 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006420 case glslang::EbtFloat16:
6421 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
6422 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006423 case glslang::EbtBool:
6424 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
6425 break;
6426 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006427 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06006428 break;
6429 }
6430 ++nextConst;
6431 }
6432 } else {
6433 // we have a non-aggregate (scalar) constant
6434 bool zero = nextConst >= consts.size();
6435 spv::Id scalar = 0;
6436 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006437 case glslang::EbtInt8:
6438 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
6439 break;
6440 case glslang::EbtUint8:
6441 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
6442 break;
6443 case glslang::EbtInt16:
6444 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
6445 break;
6446 case glslang::EbtUint16:
6447 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
6448 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006449 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07006450 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006451 break;
6452 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07006453 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006454 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006455 case glslang::EbtInt64:
6456 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
6457 break;
6458 case glslang::EbtUint64:
6459 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
6460 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006461 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07006462 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006463 break;
6464 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07006465 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006466 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006467 case glslang::EbtFloat16:
6468 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
6469 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006470 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07006471 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006472 break;
6473 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006474 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06006475 break;
6476 }
6477 ++nextConst;
6478 return scalar;
6479 }
6480
6481 return builder.makeCompositeConstant(typeId, spvConsts);
6482}
6483
John Kessenich7c1aa102015-10-15 13:29:11 -06006484// Return true if the node is a constant or symbol whose reading has no
6485// non-trivial observable cost or effect.
6486bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
6487{
6488 // don't know what this is
6489 if (node == nullptr)
6490 return false;
6491
6492 // a constant is safe
6493 if (node->getAsConstantUnion() != nullptr)
6494 return true;
6495
6496 // not a symbol means non-trivial
6497 if (node->getAsSymbolNode() == nullptr)
6498 return false;
6499
6500 // a symbol, depends on what's being read
6501 switch (node->getType().getQualifier().storage) {
6502 case glslang::EvqTemporary:
6503 case glslang::EvqGlobal:
6504 case glslang::EvqIn:
6505 case glslang::EvqInOut:
6506 case glslang::EvqConst:
6507 case glslang::EvqConstReadOnly:
6508 case glslang::EvqUniform:
6509 return true;
6510 default:
6511 return false;
6512 }
qining25262b32016-05-06 17:25:16 -04006513}
John Kessenich7c1aa102015-10-15 13:29:11 -06006514
6515// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06006516// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06006517// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06006518// Return true if trivial.
6519bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
6520{
6521 if (node == nullptr)
6522 return false;
6523
John Kessenich84cc15f2017-05-24 16:44:47 -06006524 // count non scalars as trivial, as well as anything coming from HLSL
6525 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06006526 return true;
6527
John Kessenich7c1aa102015-10-15 13:29:11 -06006528 // symbols and constants are trivial
6529 if (isTrivialLeaf(node))
6530 return true;
6531
6532 // otherwise, it needs to be a simple operation or one or two leaf nodes
6533
6534 // not a simple operation
6535 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
6536 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
6537 if (binaryNode == nullptr && unaryNode == nullptr)
6538 return false;
6539
6540 // not on leaf nodes
6541 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
6542 return false;
6543
6544 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
6545 return false;
6546 }
6547
6548 switch (node->getAsOperator()->getOp()) {
6549 case glslang::EOpLogicalNot:
6550 case glslang::EOpConvIntToBool:
6551 case glslang::EOpConvUintToBool:
6552 case glslang::EOpConvFloatToBool:
6553 case glslang::EOpConvDoubleToBool:
6554 case glslang::EOpEqual:
6555 case glslang::EOpNotEqual:
6556 case glslang::EOpLessThan:
6557 case glslang::EOpGreaterThan:
6558 case glslang::EOpLessThanEqual:
6559 case glslang::EOpGreaterThanEqual:
6560 case glslang::EOpIndexDirect:
6561 case glslang::EOpIndexDirectStruct:
6562 case glslang::EOpLogicalXor:
6563 case glslang::EOpAny:
6564 case glslang::EOpAll:
6565 return true;
6566 default:
6567 return false;
6568 }
6569}
6570
6571// Emit short-circuiting code, where 'right' is never evaluated unless
6572// the left side is true (for &&) or false (for ||).
6573spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
6574{
6575 spv::Id boolTypeId = builder.makeBoolType();
6576
6577 // emit left operand
6578 builder.clearAccessChain();
6579 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006580 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006581
6582 // Operands to accumulate OpPhi operands
6583 std::vector<spv::Id> phiOperands;
6584 // accumulate left operand's phi information
6585 phiOperands.push_back(leftId);
6586 phiOperands.push_back(builder.getBuildPoint()->getId());
6587
6588 // Make the two kinds of operation symmetric with a "!"
6589 // || => emit "if (! left) result = right"
6590 // && => emit "if ( left) result = right"
6591 //
6592 // TODO: this runtime "not" for || could be avoided by adding functionality
6593 // to 'builder' to have an "else" without an "then"
6594 if (op == glslang::EOpLogicalOr)
6595 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
6596
6597 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08006598 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06006599
6600 // emit right operand as the "then" part of the "if"
6601 builder.clearAccessChain();
6602 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006603 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006604
6605 // accumulate left operand's phi information
6606 phiOperands.push_back(rightId);
6607 phiOperands.push_back(builder.getBuildPoint()->getId());
6608
6609 // finish the "if"
6610 ifBuilder.makeEndIf();
6611
6612 // phi together the two results
6613 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
6614}
6615
Frank Henigman541f7bb2018-01-16 00:18:26 -05006616#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08006617// Return type Id of the imported set of extended instructions corresponds to the name.
6618// Import this set if it has not been imported yet.
6619spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
6620{
6621 if (extBuiltinMap.find(name) != extBuiltinMap.end())
6622 return extBuiltinMap[name];
6623 else {
Rex Xu51596642016-09-21 18:56:12 +08006624 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08006625 spv::Id extBuiltins = builder.import(name);
6626 extBuiltinMap[name] = extBuiltins;
6627 return extBuiltins;
6628 }
6629}
Frank Henigman541f7bb2018-01-16 00:18:26 -05006630#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006631
John Kessenich140f3df2015-06-26 16:58:36 -06006632}; // end anonymous namespace
6633
6634namespace glslang {
6635
John Kessenich68d78fd2015-07-12 19:28:10 -06006636void GetSpirvVersion(std::string& version)
6637{
John Kessenich9e55f632015-07-15 10:03:39 -06006638 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06006639 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07006640 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06006641 version = buf;
6642}
6643
John Kessenicha372a3e2017-11-02 22:32:14 -06006644// For low-order part of the generator's magic number. Bump up
6645// when there is a change in the style (e.g., if SSA form changes,
6646// or a different instruction sequence to do something gets used).
6647int GetSpirvGeneratorVersion()
6648{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07006649 // return 1; // start
6650 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07006651 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07006652 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07006653 // return 5; // make OpArrayLength result type be an int with signedness of 0
6654 return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
6655 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenicha372a3e2017-11-02 22:32:14 -06006656}
6657
John Kessenich140f3df2015-06-26 16:58:36 -06006658// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006659void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06006660{
6661 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06006662 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006663 if (out.fail())
6664 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06006665 for (int i = 0; i < (int)spirv.size(); ++i) {
6666 unsigned int word = spirv[i];
6667 out.write((const char*)&word, 4);
6668 }
6669 out.close();
6670}
6671
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006672// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08006673void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006674{
6675 std::ofstream out;
6676 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006677 if (out.fail())
6678 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07006679 out << "\t// " <<
6680 glslang::GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
6681 std::endl;
Flavio15017db2017-02-15 14:29:33 -08006682 if (varName != nullptr) {
6683 out << "\t #pragma once" << std::endl;
6684 out << "const uint32_t " << varName << "[] = {" << std::endl;
6685 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006686 const int WORDS_PER_LINE = 8;
6687 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
6688 out << "\t";
6689 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
6690 const unsigned int word = spirv[i + j];
6691 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
6692 if (i + j + 1 < (int)spirv.size()) {
6693 out << ",";
6694 }
6695 }
6696 out << std::endl;
6697 }
Flavio15017db2017-02-15 14:29:33 -08006698 if (varName != nullptr) {
6699 out << "};";
6700 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006701 out.close();
6702}
6703
GregFcd1f1692017-09-21 18:40:22 -06006704#ifdef ENABLE_OPT
6705void errHandler(const std::string& str) {
6706 std::cerr << str << std::endl;
6707}
6708#endif
6709
John Kessenich140f3df2015-06-26 16:58:36 -06006710//
6711// Set up the glslang traversal
6712//
John Kessenich121853f2017-05-31 17:11:16 -06006713void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06006714{
Lei Zhang17535f72016-05-04 15:55:59 -04006715 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06006716 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04006717}
6718
John Kessenich121853f2017-05-31 17:11:16 -06006719void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
6720 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04006721{
John Kessenich140f3df2015-06-26 16:58:36 -06006722 TIntermNode* root = intermediate.getTreeRoot();
6723
6724 if (root == 0)
6725 return;
6726
John Kessenich121853f2017-05-31 17:11:16 -06006727 glslang::SpvOptions defaultOptions;
6728 if (options == nullptr)
6729 options = &defaultOptions;
6730
John Kessenich140f3df2015-06-26 16:58:36 -06006731 glslang::GetThreadPoolAllocator().push();
6732
John Kessenich2b5ea9f2018-01-31 18:35:56 -07006733 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06006734 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07006735 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06006736 it.dumpSpv(spirv);
6737
GregFcd1f1692017-09-21 18:40:22 -06006738#ifdef ENABLE_OPT
6739 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
6740 // eg. forward and remove memory writes of opaque types.
6741 if ((intermediate.getSource() == EShSourceHlsl ||
6742 options->optimizeSize) &&
6743 !options->disableOptimizer) {
6744 spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
6745
6746 spvtools::Optimizer optimizer(target_env);
6747 optimizer.SetMessageConsumer([](spv_message_level_t level,
6748 const char* source,
6749 const spv_position_t& position,
6750 const char* message) {
6751 std::cerr << StringifyMessage(level, source, position, message)
6752 << std::endl;
6753 });
6754
6755 optimizer.RegisterPass(CreateInlineExhaustivePass());
GregFe0639282017-12-21 10:55:57 -07006756 optimizer.RegisterPass(CreateEliminateDeadFunctionsPass());
6757 optimizer.RegisterPass(CreateScalarReplacementPass());
GregFcd1f1692017-09-21 18:40:22 -06006758 optimizer.RegisterPass(CreateLocalAccessChainConvertPass());
6759 optimizer.RegisterPass(CreateLocalSingleBlockLoadStoreElimPass());
6760 optimizer.RegisterPass(CreateLocalSingleStoreElimPass());
6761 optimizer.RegisterPass(CreateInsertExtractElimPass());
GregF8a4848f2018-02-07 16:04:42 -07006762 optimizer.RegisterPass(CreateDeadInsertElimPass());
GregFcd1f1692017-09-21 18:40:22 -06006763 optimizer.RegisterPass(CreateAggressiveDCEPass());
6764 optimizer.RegisterPass(CreateDeadBranchElimPass());
GregFcc80d802017-10-23 16:48:42 -06006765 optimizer.RegisterPass(CreateCFGCleanupPass());
GregFcd1f1692017-09-21 18:40:22 -06006766 optimizer.RegisterPass(CreateBlockMergePass());
6767 optimizer.RegisterPass(CreateLocalMultiStoreElimPass());
6768 optimizer.RegisterPass(CreateInsertExtractElimPass());
GregF8a4848f2018-02-07 16:04:42 -07006769 optimizer.RegisterPass(CreateDeadInsertElimPass());
6770 if (options->optimizeSize) {
6771 optimizer.RegisterPass(CreateRedundancyEliminationPass());
6772 // TODO(greg-lunarg): Add this when AMD driver issues are resolved
6773 // optimizer.RegisterPass(CreateCommonUniformElimPass());
6774 }
GregFcd1f1692017-09-21 18:40:22 -06006775 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFcd1f1692017-09-21 18:40:22 -06006776
6777 if (!optimizer.Run(spirv.data(), spirv.size(), &spirv))
6778 return;
6779
6780 // Remove dead module-level objects: functions, types, vars
6781 // TODO(greg-lunarg): Switch to spirv-opt versions when available
6782 spv::spirvbin_t Remapper(0);
6783 Remapper.registerErrorHandler(errHandler);
6784 Remapper.remap(spirv, spv::spirvbin_t::DCE_ALL);
6785 }
6786#endif
6787
John Kessenich140f3df2015-06-26 16:58:36 -06006788 glslang::GetThreadPoolAllocator().pop();
6789}
6790
6791}; // end namespace glslang